diff --git a/README.md b/README.md index c4ca212..8b7b3c7 100644 --- a/README.md +++ b/README.md @@ -197,10 +197,14 @@ touch README.md git init git checkout -b main git add README.md -git commit -m "first commit" +git commit -m "first commit" git remote add origin https://gitlab.peanutsmediaserver.com/aaron/gameStatusUpdate.git git push -u origin main -### Pushing an existing repository from the command line -git remote add origin https://gitlab.peanutsmediaserver.com/aaron/gameStatusUpdate.git -git push -u origin main \ No newline at end of file +### Pushing an existing repository from the command line with version tag +git add . +git commit -m "comment for the commit" +git tag -a vX.X.X -m "version X.X.X" +git push origin vX.X.X +git push origin main +git push --tags \ No newline at end of file diff --git a/bin/golangci-lint b/bin/golangci-lint new file mode 100755 index 0000000..2af8b9f Binary files /dev/null and b/bin/golangci-lint differ diff --git a/bin/gotestsum b/bin/gotestsum new file mode 100755 index 0000000..26141ea Binary files /dev/null and b/bin/gotestsum differ diff --git a/dist/com.mattermost.plugin-gameStatusUpdate-0.0.0+0560327.tar.gz b/dist/com.mattermost.plugin-gameStatusUpdate-0.0.0+0560327.tar.gz new file mode 100644 index 0000000..af2294a Binary files /dev/null and b/dist/com.mattermost.plugin-gameStatusUpdate-0.0.0+0560327.tar.gz differ diff --git a/dist/com.mattermost.plugin-gameStatusUpdate/assets/.gitkeep b/dist/com.mattermost.plugin-gameStatusUpdate/assets/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/dist/com.mattermost.plugin-gameStatusUpdate/assets/starter-template-icon.svg b/dist/com.mattermost.plugin-gameStatusUpdate/assets/starter-template-icon.svg new file mode 100644 index 0000000..3ec77a4 --- /dev/null +++ b/dist/com.mattermost.plugin-gameStatusUpdate/assets/starter-template-icon.svg @@ -0,0 +1,14 @@ + + + + blue-icon + Created with Sketch. + + + + + + + + + \ No newline at end of file diff --git a/dist/com.mattermost.plugin-gameStatusUpdate/plugin.json b/dist/com.mattermost.plugin-gameStatusUpdate/plugin.json new file mode 100644 index 0000000..eab7429 --- /dev/null +++ b/dist/com.mattermost.plugin-gameStatusUpdate/plugin.json @@ -0,0 +1,28 @@ +{ + "id": "com.mattermost.plugin-gameStatusUpdate", + "name": "game status update", + "description": "This plugin serves as a starting point for writing a Mattermost plugin.", + "homepage_url": "https://gitlab.peanutsmediaserver.com/aaron/gameStatusUpdate", + "support_url": "https://gitlab.peanutsmediaserver.com/aaron/gameStatusUpdate/issues", + "icon_path": "assets/starter-template-icon.svg", + "version": "0.0.0+0560327", + "min_server_version": "6.2.1", + "server": { + "executables": { + "darwin-amd64": "server/dist/plugin-darwin-amd64", + "darwin-arm64": "server/dist/plugin-darwin-arm64", + "linux-amd64": "server/dist/plugin-linux-amd64", + "linux-arm64": "server/dist/plugin-linux-arm64", + "windows-amd64": "server/dist/plugin-windows-amd64.exe" + }, + "executable": "" + }, + "webapp": { + "bundle_path": "webapp/dist/main.js" + }, + "settings_schema": { + "header": "", + "footer": "", + "settings": [] + } +} \ No newline at end of file diff --git a/dist/com.mattermost.plugin-gameStatusUpdate/public/hello.html b/dist/com.mattermost.plugin-gameStatusUpdate/public/hello.html new file mode 100644 index 0000000..7d6ba4a --- /dev/null +++ b/dist/com.mattermost.plugin-gameStatusUpdate/public/hello.html @@ -0,0 +1 @@ +Hello from the static files public folder for the com.mattermost.plugin-starter-template plugin! diff --git a/dist/com.mattermost.plugin-gameStatusUpdate/server/dist/plugin-darwin-amd64 b/dist/com.mattermost.plugin-gameStatusUpdate/server/dist/plugin-darwin-amd64 new file mode 100755 index 0000000..fb81369 Binary files /dev/null and b/dist/com.mattermost.plugin-gameStatusUpdate/server/dist/plugin-darwin-amd64 differ diff --git a/dist/com.mattermost.plugin-gameStatusUpdate/server/dist/plugin-darwin-arm64 b/dist/com.mattermost.plugin-gameStatusUpdate/server/dist/plugin-darwin-arm64 new file mode 100755 index 0000000..dfe11af Binary files /dev/null and b/dist/com.mattermost.plugin-gameStatusUpdate/server/dist/plugin-darwin-arm64 differ diff --git a/dist/com.mattermost.plugin-gameStatusUpdate/server/dist/plugin-linux-amd64 b/dist/com.mattermost.plugin-gameStatusUpdate/server/dist/plugin-linux-amd64 new file mode 100755 index 0000000..78b831a Binary files /dev/null and b/dist/com.mattermost.plugin-gameStatusUpdate/server/dist/plugin-linux-amd64 differ diff --git a/dist/com.mattermost.plugin-gameStatusUpdate/server/dist/plugin-linux-arm64 b/dist/com.mattermost.plugin-gameStatusUpdate/server/dist/plugin-linux-arm64 new file mode 100755 index 0000000..45091a2 Binary files /dev/null and b/dist/com.mattermost.plugin-gameStatusUpdate/server/dist/plugin-linux-arm64 differ diff --git a/dist/com.mattermost.plugin-gameStatusUpdate/server/dist/plugin-windows-amd64.exe b/dist/com.mattermost.plugin-gameStatusUpdate/server/dist/plugin-windows-amd64.exe new file mode 100755 index 0000000..d74e754 Binary files /dev/null and b/dist/com.mattermost.plugin-gameStatusUpdate/server/dist/plugin-windows-amd64.exe differ diff --git a/dist/com.mattermost.plugin-gameStatusUpdate/webapp/dist/main.js b/dist/com.mattermost.plugin-gameStatusUpdate/webapp/dist/main.js new file mode 100644 index 0000000..7f27f8e --- /dev/null +++ b/dist/com.mattermost.plugin-gameStatusUpdate/webapp/dist/main.js @@ -0,0 +1 @@ +(()=>{var t={9662:(t,r,e)=>{var n=e(614),o=e(6330),i=TypeError;t.exports=function(t){if(n(t))return t;throw i(o(t)+" is not a function")}},9483:(t,r,e)=>{var n=e(4411),o=e(6330),i=TypeError;t.exports=function(t){if(n(t))return t;throw i(o(t)+" is not a constructor")}},6077:(t,r,e)=>{var n=e(614),o=String,i=TypeError;t.exports=function(t){if("object"==typeof t||n(t))return t;throw i("Can't set "+o(t)+" as a prototype")}},5787:(t,r,e)=>{var n=e(7976),o=TypeError;t.exports=function(t,r){if(n(r,t))return t;throw o("Incorrect invocation")}},9670:(t,r,e)=>{var n=e(111),o=String,i=TypeError;t.exports=function(t){if(n(t))return t;throw i(o(t)+" is not an object")}},1318:(t,r,e)=>{var n=e(5656),o=e(1400),i=e(6244),a=function(t){return function(r,e,a){var c,u=n(r),s=i(u),f=o(a,s);if(t&&e!=e){for(;s>f;)if((c=u[f++])!=c)return!0}else for(;s>f;f++)if((t||f in u)&&u[f]===e)return t||f||0;return!t&&-1}};t.exports={includes:a(!0),indexOf:a(!1)}},206:(t,r,e)=>{var n=e(1702);t.exports=n([].slice)},7072:(t,r,e)=>{var n=e(5112)("iterator"),o=!1;try{var i=0,a={next:function(){return{done:!!i++}},return:function(){o=!0}};a[n]=function(){return this},Array.from(a,(function(){throw 2}))}catch(t){}t.exports=function(t,r){if(!r&&!o)return!1;var e=!1;try{var i={};i[n]=function(){return{next:function(){return{done:e=!0}}}},t(i)}catch(t){}return e}},4326:(t,r,e)=>{var n=e(1702),o=n({}.toString),i=n("".slice);t.exports=function(t){return i(o(t),8,-1)}},648:(t,r,e)=>{var n=e(1694),o=e(614),i=e(4326),a=e(5112)("toStringTag"),c=Object,u="Arguments"==i(function(){return arguments}());t.exports=n?i:function(t){var r,e,n;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(e=function(t,r){try{return t[r]}catch(t){}}(r=c(t),a))?e:u?i(r):"Object"==(n=i(r))&&o(r.callee)?"Arguments":n}},9920:(t,r,e)=>{var n=e(2597),o=e(3887),i=e(1236),a=e(3070);t.exports=function(t,r,e){for(var c=o(r),u=a.f,s=i.f,f=0;f{var n=e(9781),o=e(3070),i=e(9114);t.exports=n?function(t,r,e){return o.f(t,r,i(1,e))}:function(t,r,e){return t[r]=e,t}},9114:t=>{t.exports=function(t,r){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:r}}},8052:(t,r,e)=>{var n=e(614),o=e(8880),i=e(6339),a=e(3072);t.exports=function(t,r,e,c){c||(c={});var u=c.enumerable,s=void 0!==c.name?c.name:r;return n(e)&&i(e,s,c),c.global?u?t[r]=e:a(r,e):(c.unsafe?t[r]&&(u=!0):delete t[r],u?t[r]=e:o(t,r,e)),t}},3072:(t,r,e)=>{var n=e(7854),o=Object.defineProperty;t.exports=function(t,r){try{o(n,t,{value:r,configurable:!0,writable:!0})}catch(e){n[t]=r}return r}},9781:(t,r,e)=>{var n=e(7293);t.exports=!n((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]}))},317:(t,r,e)=>{var n=e(7854),o=e(111),i=n.document,a=o(i)&&o(i.createElement);t.exports=function(t){return a?i.createElement(t):{}}},7871:t=>{t.exports="object"==typeof window&&"object"!=typeof Deno},1528:(t,r,e)=>{var n=e(8113),o=e(7854);t.exports=/ipad|iphone|ipod/i.test(n)&&void 0!==o.Pebble},6833:(t,r,e)=>{var n=e(8113);t.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(n)},5268:(t,r,e)=>{var n=e(4326),o=e(7854);t.exports="process"==n(o.process)},1036:(t,r,e)=>{var n=e(8113);t.exports=/web0s(?!.*chrome)/i.test(n)},8113:(t,r,e)=>{var n=e(5005);t.exports=n("navigator","userAgent")||""},7392:(t,r,e)=>{var n,o,i=e(7854),a=e(8113),c=i.process,u=i.Deno,s=c&&c.versions||u&&u.version,f=s&&s.v8;f&&(o=(n=f.split("."))[0]>0&&n[0]<4?1:+(n[0]+n[1])),!o&&a&&(!(n=a.match(/Edge\/(\d+)/))||n[1]>=74)&&(n=a.match(/Chrome\/(\d+)/))&&(o=+n[1]),t.exports=o},748:t=>{t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},2109:(t,r,e)=>{var n=e(7854),o=e(1236).f,i=e(8880),a=e(8052),c=e(3072),u=e(9920),s=e(4705);t.exports=function(t,r){var e,f,p,v,l,h=t.target,d=t.global,y=t.stat;if(e=d?n:y?n[h]||c(h,{}):(n[h]||{}).prototype)for(f in r){if(v=r[f],p=t.dontCallGetSet?(l=o(e,f))&&l.value:e[f],!s(d?f:h+(y?".":"#")+f,t.forced)&&void 0!==p){if(typeof v==typeof p)continue;u(v,p)}(t.sham||p&&p.sham)&&i(v,"sham",!0),a(e,f,v,t)}}},7293:t=>{t.exports=function(t){try{return!!t()}catch(t){return!0}}},2104:(t,r,e)=>{var n=e(4374),o=Function.prototype,i=o.apply,a=o.call;t.exports="object"==typeof Reflect&&Reflect.apply||(n?a.bind(i):function(){return a.apply(i,arguments)})},9974:(t,r,e)=>{var n=e(1702),o=e(9662),i=e(4374),a=n(n.bind);t.exports=function(t,r){return o(t),void 0===r?t:i?a(t,r):function(){return t.apply(r,arguments)}}},4374:(t,r,e)=>{var n=e(7293);t.exports=!n((function(){var t=function(){}.bind();return"function"!=typeof t||t.hasOwnProperty("prototype")}))},6916:(t,r,e)=>{var n=e(4374),o=Function.prototype.call;t.exports=n?o.bind(o):function(){return o.apply(o,arguments)}},6530:(t,r,e)=>{var n=e(9781),o=e(2597),i=Function.prototype,a=n&&Object.getOwnPropertyDescriptor,c=o(i,"name"),u=c&&"something"===function(){}.name,s=c&&(!n||n&&a(i,"name").configurable);t.exports={EXISTS:c,PROPER:u,CONFIGURABLE:s}},1702:(t,r,e)=>{var n=e(4374),o=Function.prototype,i=o.bind,a=o.call,c=n&&i.bind(a,a);t.exports=n?function(t){return t&&c(t)}:function(t){return t&&function(){return a.apply(t,arguments)}}},5005:(t,r,e)=>{var n=e(7854),o=e(614);t.exports=function(t,r){return arguments.length<2?(e=n[t],o(e)?e:void 0):n[t]&&n[t][r];var e}},1246:(t,r,e)=>{var n=e(648),o=e(8173),i=e(7497),a=e(5112)("iterator");t.exports=function(t){if(null!=t)return o(t,a)||o(t,"@@iterator")||i[n(t)]}},8554:(t,r,e)=>{var n=e(6916),o=e(9662),i=e(9670),a=e(6330),c=e(1246),u=TypeError;t.exports=function(t,r){var e=arguments.length<2?c(t):r;if(o(e))return i(n(e,t));throw u(a(t)+" is not iterable")}},8173:(t,r,e)=>{var n=e(9662);t.exports=function(t,r){var e=t[r];return null==e?void 0:n(e)}},7854:(t,r,e)=>{var n=function(t){return t&&t.Math==Math&&t};t.exports=n("object"==typeof globalThis&&globalThis)||n("object"==typeof window&&window)||n("object"==typeof self&&self)||n("object"==typeof e.g&&e.g)||function(){return this}()||Function("return this")()},2597:(t,r,e)=>{var n=e(1702),o=e(7908),i=n({}.hasOwnProperty);t.exports=Object.hasOwn||function(t,r){return i(o(t),r)}},3501:t=>{t.exports={}},842:(t,r,e)=>{var n=e(7854);t.exports=function(t,r){var e=n.console;e&&e.error&&(1==arguments.length?e.error(t):e.error(t,r))}},490:(t,r,e)=>{var n=e(5005);t.exports=n("document","documentElement")},4664:(t,r,e)=>{var n=e(9781),o=e(7293),i=e(317);t.exports=!n&&!o((function(){return 7!=Object.defineProperty(i("div"),"a",{get:function(){return 7}}).a}))},8361:(t,r,e)=>{var n=e(1702),o=e(7293),i=e(4326),a=Object,c=n("".split);t.exports=o((function(){return!a("z").propertyIsEnumerable(0)}))?function(t){return"String"==i(t)?c(t,""):a(t)}:a},2788:(t,r,e)=>{var n=e(1702),o=e(614),i=e(5465),a=n(Function.toString);o(i.inspectSource)||(i.inspectSource=function(t){return a(t)}),t.exports=i.inspectSource},9909:(t,r,e)=>{var n,o,i,a=e(8536),c=e(7854),u=e(1702),s=e(111),f=e(8880),p=e(2597),v=e(5465),l=e(6200),h=e(3501),d="Object already initialized",y=c.TypeError,m=c.WeakMap;if(a||v.state){var g=v.state||(v.state=new m),x=u(g.get),b=u(g.has),w=u(g.set);n=function(t,r){if(b(g,t))throw new y(d);return r.facade=t,w(g,t,r),r},o=function(t){return x(g,t)||{}},i=function(t){return b(g,t)}}else{var O=l("state");h[O]=!0,n=function(t,r){if(p(t,O))throw new y(d);return r.facade=t,f(t,O,r),r},o=function(t){return p(t,O)?t[O]:{}},i=function(t){return p(t,O)}}t.exports={set:n,get:o,has:i,enforce:function(t){return i(t)?o(t):n(t,{})},getterFor:function(t){return function(r){var e;if(!s(r)||(e=o(r)).type!==t)throw y("Incompatible receiver, "+t+" required");return e}}}},7659:(t,r,e)=>{var n=e(5112),o=e(7497),i=n("iterator"),a=Array.prototype;t.exports=function(t){return void 0!==t&&(o.Array===t||a[i]===t)}},614:t=>{t.exports=function(t){return"function"==typeof t}},4411:(t,r,e)=>{var n=e(1702),o=e(7293),i=e(614),a=e(648),c=e(5005),u=e(2788),s=function(){},f=[],p=c("Reflect","construct"),v=/^\s*(?:class|function)\b/,l=n(v.exec),h=!v.exec(s),d=function(t){if(!i(t))return!1;try{return p(s,f,t),!0}catch(t){return!1}},y=function(t){if(!i(t))return!1;switch(a(t)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return h||!!l(v,u(t))}catch(t){return!0}};y.sham=!0,t.exports=!p||o((function(){var t;return d(d.call)||!d(Object)||!d((function(){t=!0}))||t}))?y:d},4705:(t,r,e)=>{var n=e(7293),o=e(614),i=/#|\.prototype\./,a=function(t,r){var e=u[c(t)];return e==f||e!=s&&(o(r)?n(r):!!r)},c=a.normalize=function(t){return String(t).replace(i,".").toLowerCase()},u=a.data={},s=a.NATIVE="N",f=a.POLYFILL="P";t.exports=a},111:(t,r,e)=>{var n=e(614);t.exports=function(t){return"object"==typeof t?null!==t:n(t)}},1913:t=>{t.exports=!1},2190:(t,r,e)=>{var n=e(5005),o=e(614),i=e(7976),a=e(3307),c=Object;t.exports=a?function(t){return"symbol"==typeof t}:function(t){var r=n("Symbol");return o(r)&&i(r.prototype,c(t))}},408:(t,r,e)=>{var n=e(9974),o=e(6916),i=e(9670),a=e(6330),c=e(7659),u=e(6244),s=e(7976),f=e(8554),p=e(1246),v=e(9212),l=TypeError,h=function(t,r){this.stopped=t,this.result=r},d=h.prototype;t.exports=function(t,r,e){var y,m,g,x,b,w,O,j=e&&e.that,S=!(!e||!e.AS_ENTRIES),E=!(!e||!e.IS_ITERATOR),T=!(!e||!e.INTERRUPTED),P=n(r,j),C=function(t){return y&&v(y,"normal",t),new h(!0,t)},R=function(t){return S?(i(t),T?P(t[0],t[1],C):P(t[0],t[1])):T?P(t,C):P(t)};if(E)y=t;else{if(!(m=p(t)))throw l(a(t)+" is not iterable");if(c(m)){for(g=0,x=u(t);x>g;g++)if((b=R(t[g]))&&s(d,b))return b;return new h(!1)}y=f(t,m)}for(w=y.next;!(O=o(w,y)).done;){try{b=R(O.value)}catch(t){v(y,"throw",t)}if("object"==typeof b&&b&&s(d,b))return b}return new h(!1)}},9212:(t,r,e)=>{var n=e(6916),o=e(9670),i=e(8173);t.exports=function(t,r,e){var a,c;o(t);try{if(!(a=i(t,"return"))){if("throw"===r)throw e;return e}a=n(a,t)}catch(t){c=!0,a=t}if("throw"===r)throw e;if(c)throw a;return o(a),e}},7497:t=>{t.exports={}},6244:(t,r,e)=>{var n=e(7466);t.exports=function(t){return n(t.length)}},6339:(t,r,e)=>{var n=e(7293),o=e(614),i=e(2597),a=e(9781),c=e(6530).CONFIGURABLE,u=e(2788),s=e(9909),f=s.enforce,p=s.get,v=Object.defineProperty,l=a&&!n((function(){return 8!==v((function(){}),"length",{value:8}).length})),h=String(String).split("String"),d=t.exports=function(t,r,e){"Symbol("===String(r).slice(0,7)&&(r="["+String(r).replace(/^Symbol\(([^)]*)\)/,"$1")+"]"),e&&e.getter&&(r="get "+r),e&&e.setter&&(r="set "+r),(!i(t,"name")||c&&t.name!==r)&&v(t,"name",{value:r,configurable:!0}),l&&e&&i(e,"arity")&&t.length!==e.arity&&v(t,"length",{value:e.arity});try{e&&i(e,"constructor")&&e.constructor?a&&v(t,"prototype",{writable:!1}):t.prototype&&(t.prototype=void 0)}catch(t){}var n=f(t);return i(n,"source")||(n.source=h.join("string"==typeof r?r:"")),t};Function.prototype.toString=d((function(){return o(this)&&p(this).source||u(this)}),"toString")},4758:t=>{var r=Math.ceil,e=Math.floor;t.exports=Math.trunc||function(t){var n=+t;return(n>0?e:r)(n)}},5948:(t,r,e)=>{var n,o,i,a,c,u,s,f,p=e(7854),v=e(9974),l=e(1236).f,h=e(261).set,d=e(6833),y=e(1528),m=e(1036),g=e(5268),x=p.MutationObserver||p.WebKitMutationObserver,b=p.document,w=p.process,O=p.Promise,j=l(p,"queueMicrotask"),S=j&&j.value;S||(n=function(){var t,r;for(g&&(t=w.domain)&&t.exit();o;){r=o.fn,o=o.next;try{r()}catch(t){throw o?a():i=void 0,t}}i=void 0,t&&t.enter()},d||g||m||!x||!b?!y&&O&&O.resolve?((s=O.resolve(void 0)).constructor=O,f=v(s.then,s),a=function(){f(n)}):g?a=function(){w.nextTick(n)}:(h=v(h,p),a=function(){h(n)}):(c=!0,u=b.createTextNode(""),new x(n).observe(u,{characterData:!0}),a=function(){u.data=c=!c})),t.exports=S||function(t){var r={fn:t,next:void 0};i&&(i.next=r),o||(o=r,a()),i=r}},133:(t,r,e)=>{var n=e(7392),o=e(7293);t.exports=!!Object.getOwnPropertySymbols&&!o((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&n&&n<41}))},8536:(t,r,e)=>{var n=e(7854),o=e(614),i=e(2788),a=n.WeakMap;t.exports=o(a)&&/native code/.test(i(a))},8523:(t,r,e)=>{"use strict";var n=e(9662),o=function(t){var r,e;this.promise=new t((function(t,n){if(void 0!==r||void 0!==e)throw TypeError("Bad Promise constructor");r=t,e=n})),this.resolve=n(r),this.reject=n(e)};t.exports.f=function(t){return new o(t)}},3070:(t,r,e)=>{var n=e(9781),o=e(4664),i=e(3353),a=e(9670),c=e(4948),u=TypeError,s=Object.defineProperty,f=Object.getOwnPropertyDescriptor,p="enumerable",v="configurable",l="writable";r.f=n?i?function(t,r,e){if(a(t),r=c(r),a(e),"function"==typeof t&&"prototype"===r&&"value"in e&&l in e&&!e[l]){var n=f(t,r);n&&n[l]&&(t[r]=e.value,e={configurable:v in e?e[v]:n[v],enumerable:p in e?e[p]:n[p],writable:!1})}return s(t,r,e)}:s:function(t,r,e){if(a(t),r=c(r),a(e),o)try{return s(t,r,e)}catch(t){}if("get"in e||"set"in e)throw u("Accessors not supported");return"value"in e&&(t[r]=e.value),t}},1236:(t,r,e)=>{var n=e(9781),o=e(6916),i=e(5296),a=e(9114),c=e(5656),u=e(4948),s=e(2597),f=e(4664),p=Object.getOwnPropertyDescriptor;r.f=n?p:function(t,r){if(t=c(t),r=u(r),f)try{return p(t,r)}catch(t){}if(s(t,r))return a(!o(i.f,t,r),t[r])}},8006:(t,r,e)=>{var n=e(6324),o=e(748).concat("length","prototype");r.f=Object.getOwnPropertyNames||function(t){return n(t,o)}},5181:(t,r)=>{r.f=Object.getOwnPropertySymbols},7976:(t,r,e)=>{var n=e(1702);t.exports=n({}.isPrototypeOf)},6324:(t,r,e)=>{var n=e(1702),o=e(2597),i=e(5656),a=e(1318).indexOf,c=e(3501),u=n([].push);t.exports=function(t,r){var e,n=i(t),s=0,f=[];for(e in n)!o(c,e)&&o(n,e)&&u(f,e);for(;r.length>s;)o(n,e=r[s++])&&(~a(f,e)||u(f,e));return f}},5296:(t,r)=>{"use strict";var e={}.propertyIsEnumerable,n=Object.getOwnPropertyDescriptor,o=n&&!e.call({1:2},1);r.f=o?function(t){var r=n(this,t);return!!r&&r.enumerable}:e},7674:(t,r,e)=>{var n=e(1702),o=e(9670),i=e(6077);t.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var t,r=!1,e={};try{(t=n(Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set))(e,[]),r=e instanceof Array}catch(t){}return function(e,n){return o(e),i(n),r?t(e,n):e.__proto__=n,e}}():void 0)},2140:(t,r,e)=>{var n=e(6916),o=e(614),i=e(111),a=TypeError;t.exports=function(t,r){var e,c;if("string"===r&&o(e=t.toString)&&!i(c=n(e,t)))return c;if(o(e=t.valueOf)&&!i(c=n(e,t)))return c;if("string"!==r&&o(e=t.toString)&&!i(c=n(e,t)))return c;throw a("Can't convert object to primitive value")}},3887:(t,r,e)=>{var n=e(5005),o=e(1702),i=e(8006),a=e(5181),c=e(9670),u=o([].concat);t.exports=n("Reflect","ownKeys")||function(t){var r=i.f(c(t)),e=a.f;return e?u(r,e(t)):r}},2534:t=>{t.exports=function(t){try{return{error:!1,value:t()}}catch(t){return{error:!0,value:t}}}},3702:(t,r,e)=>{var n=e(7854),o=e(2492),i=e(614),a=e(4705),c=e(2788),u=e(5112),s=e(7871),f=e(1913),p=e(7392),v=o&&o.prototype,l=u("species"),h=!1,d=i(n.PromiseRejectionEvent),y=a("Promise",(function(){var t=c(o),r=t!==String(o);if(!r&&66===p)return!0;if(f&&(!v.catch||!v.finally))return!0;if(p>=51&&/native code/.test(t))return!1;var e=new o((function(t){t(1)})),n=function(t){t((function(){}),(function(){}))};return(e.constructor={})[l]=n,!(h=e.then((function(){}))instanceof n)||!r&&s&&!d}));t.exports={CONSTRUCTOR:y,REJECTION_EVENT:d,SUBCLASSING:h}},2492:(t,r,e)=>{var n=e(7854);t.exports=n.Promise},9478:(t,r,e)=>{var n=e(9670),o=e(111),i=e(8523);t.exports=function(t,r){if(n(t),o(r)&&r.constructor===t)return r;var e=i.f(t);return(0,e.resolve)(r),e.promise}},612:(t,r,e)=>{var n=e(2492),o=e(7072),i=e(3702).CONSTRUCTOR;t.exports=i||!o((function(t){n.all(t).then(void 0,(function(){}))}))},8572:t=>{var r=function(){this.head=null,this.tail=null};r.prototype={add:function(t){var r={item:t,next:null};this.head?this.tail.next=r:this.head=r,this.tail=r},get:function(){var t=this.head;if(t)return this.head=t.next,this.tail===t&&(this.tail=null),t.item}},t.exports=r},4488:t=>{var r=TypeError;t.exports=function(t){if(null==t)throw r("Can't call method on "+t);return t}},6340:(t,r,e)=>{"use strict";var n=e(5005),o=e(3070),i=e(5112),a=e(9781),c=i("species");t.exports=function(t){var r=n(t),e=o.f;a&&r&&!r[c]&&e(r,c,{configurable:!0,get:function(){return this}})}},8003:(t,r,e)=>{var n=e(3070).f,o=e(2597),i=e(5112)("toStringTag");t.exports=function(t,r,e){t&&!e&&(t=t.prototype),t&&!o(t,i)&&n(t,i,{configurable:!0,value:r})}},6200:(t,r,e)=>{var n=e(2309),o=e(9711),i=n("keys");t.exports=function(t){return i[t]||(i[t]=o(t))}},5465:(t,r,e)=>{var n=e(7854),o=e(3072),i="__core-js_shared__",a=n[i]||o(i,{});t.exports=a},2309:(t,r,e)=>{var n=e(1913),o=e(5465);(t.exports=function(t,r){return o[t]||(o[t]=void 0!==r?r:{})})("versions",[]).push({version:"3.22.8",mode:n?"pure":"global",copyright:"© 2014-2022 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.22.8/LICENSE",source:"https://github.com/zloirock/core-js"})},6707:(t,r,e)=>{var n=e(9670),o=e(9483),i=e(5112)("species");t.exports=function(t,r){var e,a=n(t).constructor;return void 0===a||null==(e=n(a)[i])?r:o(e)}},261:(t,r,e)=>{var n,o,i,a,c=e(7854),u=e(2104),s=e(9974),f=e(614),p=e(2597),v=e(7293),l=e(490),h=e(206),d=e(317),y=e(8053),m=e(6833),g=e(5268),x=c.setImmediate,b=c.clearImmediate,w=c.process,O=c.Dispatch,j=c.Function,S=c.MessageChannel,E=c.String,T=0,P={},C="onreadystatechange";try{n=c.location}catch(t){}var R=function(t){if(p(P,t)){var r=P[t];delete P[t],r()}},_=function(t){return function(){R(t)}},N=function(t){R(t.data)},I=function(t){c.postMessage(E(t),n.protocol+"//"+n.host)};x&&b||(x=function(t){y(arguments.length,1);var r=f(t)?t:j(t),e=h(arguments,1);return P[++T]=function(){u(r,void 0,e)},o(T),T},b=function(t){delete P[t]},g?o=function(t){w.nextTick(_(t))}:O&&O.now?o=function(t){O.now(_(t))}:S&&!m?(a=(i=new S).port2,i.port1.onmessage=N,o=s(a.postMessage,a)):c.addEventListener&&f(c.postMessage)&&!c.importScripts&&n&&"file:"!==n.protocol&&!v(I)?(o=I,c.addEventListener("message",N,!1)):o=C in d("script")?function(t){l.appendChild(d("script"))[C]=function(){l.removeChild(this),R(t)}}:function(t){setTimeout(_(t),0)}),t.exports={set:x,clear:b}},1400:(t,r,e)=>{var n=e(9303),o=Math.max,i=Math.min;t.exports=function(t,r){var e=n(t);return e<0?o(e+r,0):i(e,r)}},5656:(t,r,e)=>{var n=e(8361),o=e(4488);t.exports=function(t){return n(o(t))}},9303:(t,r,e)=>{var n=e(4758);t.exports=function(t){var r=+t;return r!=r||0===r?0:n(r)}},7466:(t,r,e)=>{var n=e(9303),o=Math.min;t.exports=function(t){return t>0?o(n(t),9007199254740991):0}},7908:(t,r,e)=>{var n=e(4488),o=Object;t.exports=function(t){return o(n(t))}},7593:(t,r,e)=>{var n=e(6916),o=e(111),i=e(2190),a=e(8173),c=e(2140),u=e(5112),s=TypeError,f=u("toPrimitive");t.exports=function(t,r){if(!o(t)||i(t))return t;var e,u=a(t,f);if(u){if(void 0===r&&(r="default"),e=n(u,t,r),!o(e)||i(e))return e;throw s("Can't convert object to primitive value")}return void 0===r&&(r="number"),c(t,r)}},4948:(t,r,e)=>{var n=e(7593),o=e(2190);t.exports=function(t){var r=n(t,"string");return o(r)?r:r+""}},1694:(t,r,e)=>{var n={};n[e(5112)("toStringTag")]="z",t.exports="[object z]"===String(n)},6330:t=>{var r=String;t.exports=function(t){try{return r(t)}catch(t){return"Object"}}},9711:(t,r,e)=>{var n=e(1702),o=0,i=Math.random(),a=n(1..toString);t.exports=function(t){return"Symbol("+(void 0===t?"":t)+")_"+a(++o+i,36)}},3307:(t,r,e)=>{var n=e(133);t.exports=n&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},3353:(t,r,e)=>{var n=e(9781),o=e(7293);t.exports=n&&o((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype}))},8053:t=>{var r=TypeError;t.exports=function(t,e){if(t{var n=e(7854),o=e(2309),i=e(2597),a=e(9711),c=e(133),u=e(3307),s=o("wks"),f=n.Symbol,p=f&&f.for,v=u?f:f&&f.withoutSetter||a;t.exports=function(t){if(!i(s,t)||!c&&"string"!=typeof s[t]){var r="Symbol."+t;c&&i(f,t)?s[t]=f[t]:s[t]=u&&p?p(r):v(r)}return s[t]}},821:(t,r,e)=>{"use strict";var n=e(2109),o=e(6916),i=e(9662),a=e(8523),c=e(2534),u=e(408);n({target:"Promise",stat:!0,forced:e(612)},{all:function(t){var r=this,e=a.f(r),n=e.resolve,s=e.reject,f=c((function(){var e=i(r.resolve),a=[],c=0,f=1;u(t,(function(t){var i=c++,u=!1;f++,o(e,r,t).then((function(t){u||(u=!0,a[i]=t,--f||n(a))}),s)})),--f||n(a)}));return f.error&&s(f.value),e.promise}})},4164:(t,r,e)=>{"use strict";var n=e(2109),o=e(1913),i=e(3702).CONSTRUCTOR,a=e(2492),c=e(5005),u=e(614),s=e(8052),f=a&&a.prototype;if(n({target:"Promise",proto:!0,forced:i,real:!0},{catch:function(t){return this.then(void 0,t)}}),!o&&u(a)){var p=c("Promise").prototype.catch;f.catch!==p&&s(f,"catch",p,{unsafe:!0})}},3401:(t,r,e)=>{"use strict";var n,o,i,a=e(2109),c=e(1913),u=e(5268),s=e(7854),f=e(6916),p=e(8052),v=e(7674),l=e(8003),h=e(6340),d=e(9662),y=e(614),m=e(111),g=e(5787),x=e(6707),b=e(261).set,w=e(5948),O=e(842),j=e(2534),S=e(8572),E=e(9909),T=e(2492),P=e(3702),C=e(8523),R="Promise",_=P.CONSTRUCTOR,N=P.REJECTION_EVENT,I=P.SUBCLASSING,M=E.getterFor(R),A=E.set,F=T&&T.prototype,U=T,k=F,L=s.TypeError,D=s.document,z=s.process,G=C.f,B=G,J=!!(D&&D.createEvent&&s.dispatchEvent),V="unhandledrejection",W=function(t){var r;return!(!m(t)||!y(r=t.then))&&r},q=function(t,r){var e,n,o,i=r.value,a=1==r.state,c=a?t.ok:t.fail,u=t.resolve,s=t.reject,p=t.domain;try{c?(a||(2===r.rejection&&$(r),r.rejection=1),!0===c?e=i:(p&&p.enter(),e=c(i),p&&(p.exit(),o=!0)),e===t.promise?s(L("Promise-chain cycle")):(n=W(e))?f(n,e,u,s):u(e)):s(i)}catch(t){p&&!o&&p.exit(),s(t)}},K=function(t,r){t.notified||(t.notified=!0,w((function(){for(var e,n=t.reactions;e=n.get();)q(e,t);t.notified=!1,r&&!t.rejection&&X(t)})))},H=function(t,r,e){var n,o;J?((n=D.createEvent("Event")).promise=r,n.reason=e,n.initEvent(t,!1,!0),s.dispatchEvent(n)):n={promise:r,reason:e},!N&&(o=s["on"+t])?o(n):t===V&&O("Unhandled promise rejection",e)},X=function(t){f(b,s,(function(){var r,e=t.facade,n=t.value;if(Y(t)&&(r=j((function(){u?z.emit("unhandledRejection",n,e):H(V,e,n)})),t.rejection=u||Y(t)?2:1,r.error))throw r.value}))},Y=function(t){return 1!==t.rejection&&!t.parent},$=function(t){f(b,s,(function(){var r=t.facade;u?z.emit("rejectionHandled",r):H("rejectionhandled",r,t.value)}))},Q=function(t,r,e){return function(n){t(r,n,e)}},Z=function(t,r,e){t.done||(t.done=!0,e&&(t=e),t.value=r,t.state=2,K(t,!0))},tt=function(t,r,e){if(!t.done){t.done=!0,e&&(t=e);try{if(t.facade===r)throw L("Promise can't be resolved itself");var n=W(r);n?w((function(){var e={done:!1};try{f(n,r,Q(tt,e,t),Q(Z,e,t))}catch(r){Z(e,r,t)}})):(t.value=r,t.state=1,K(t,!1))}catch(r){Z({done:!1},r,t)}}};if(_&&(k=(U=function(t){g(this,k),d(t),f(n,this);var r=M(this);try{t(Q(tt,r),Q(Z,r))}catch(t){Z(r,t)}}).prototype,(n=function(t){A(this,{type:R,done:!1,notified:!1,parent:!1,reactions:new S,rejection:!1,state:0,value:void 0})}).prototype=p(k,"then",(function(t,r){var e=M(this),n=G(x(this,U));return e.parent=!0,n.ok=!y(t)||t,n.fail=y(r)&&r,n.domain=u?z.domain:void 0,0==e.state?e.reactions.add(n):w((function(){q(n,e)})),n.promise})),o=function(){var t=new n,r=M(t);this.promise=t,this.resolve=Q(tt,r),this.reject=Q(Z,r)},C.f=G=function(t){return t===U||void 0===t?new o(t):B(t)},!c&&y(T)&&F!==Object.prototype)){i=F.then,I||p(F,"then",(function(t,r){var e=this;return new U((function(t,r){f(i,e,t,r)})).then(t,r)}),{unsafe:!0});try{delete F.constructor}catch(t){}v&&v(F,k)}a({global:!0,constructor:!0,wrap:!0,forced:_},{Promise:U}),l(U,R,!1,!0),h(R)},8674:(t,r,e)=>{e(3401),e(821),e(4164),e(6027),e(683),e(6294)},6027:(t,r,e)=>{"use strict";var n=e(2109),o=e(6916),i=e(9662),a=e(8523),c=e(2534),u=e(408);n({target:"Promise",stat:!0,forced:e(612)},{race:function(t){var r=this,e=a.f(r),n=e.reject,s=c((function(){var a=i(r.resolve);u(t,(function(t){o(a,r,t).then(e.resolve,n)}))}));return s.error&&n(s.value),e.promise}})},683:(t,r,e)=>{"use strict";var n=e(2109),o=e(6916),i=e(8523);n({target:"Promise",stat:!0,forced:e(3702).CONSTRUCTOR},{reject:function(t){var r=i.f(this);return o(r.reject,void 0,t),r.promise}})},6294:(t,r,e)=>{"use strict";var n=e(2109),o=e(5005),i=e(1913),a=e(2492),c=e(3702).CONSTRUCTOR,u=e(9478),s=o("Promise"),f=i&&!c;n({target:"Promise",stat:!0,forced:i||c},{resolve:function(t){return u(f&&this===s?a:this,t)}})}},r={};function e(n){var o=r[n];if(void 0!==o)return o.exports;var i=r[n]={exports:{}};return t[n](i,i.exports,e),i.exports}e.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),(()=>{"use strict";e(8674);const t=JSON.parse('\n{\n "id": "com.mattermost.plugin-gameStatusUpdate",\n "name": "game status update",\n "description": "This plugin serves as a starting point for writing a Mattermost plugin.",\n "homepage_url": "https://gitlab.peanutsmediaserver.com/aaron/gameStatusUpdate",\n "support_url": "https://gitlab.peanutsmediaserver.com/aaron/gameStatusUpdate/issues",\n "icon_path": "assets/starter-template-icon.svg",\n "version": "0.0.0+0560327",\n "min_server_version": "6.2.1",\n "server": {\n "executables": {\n "darwin-amd64": "server/dist/plugin-darwin-amd64",\n "darwin-arm64": "server/dist/plugin-darwin-arm64",\n "linux-amd64": "server/dist/plugin-linux-amd64",\n "linux-arm64": "server/dist/plugin-linux-arm64",\n "windows-amd64": "server/dist/plugin-windows-amd64.exe"\n },\n "executable": ""\n },\n "webapp": {\n "bundle_path": "webapp/dist/main.js"\n },\n "settings_schema": {\n "header": "",\n "footer": "",\n "settings": []\n }\n}\n');window.registerPlugin(t.id,new class{async initialize(t,r){}})})()})(); \ No newline at end of file diff --git a/node_modules/.bin/acorn b/node_modules/.bin/acorn new file mode 120000 index 0000000..cf76760 --- /dev/null +++ b/node_modules/.bin/acorn @@ -0,0 +1 @@ +../acorn/bin/acorn \ No newline at end of file diff --git a/node_modules/.bin/browserslist b/node_modules/.bin/browserslist new file mode 120000 index 0000000..3cd991b --- /dev/null +++ b/node_modules/.bin/browserslist @@ -0,0 +1 @@ +../browserslist/cli.js \ No newline at end of file diff --git a/node_modules/.bin/jsesc b/node_modules/.bin/jsesc new file mode 120000 index 0000000..7237604 --- /dev/null +++ b/node_modules/.bin/jsesc @@ -0,0 +1 @@ +../jsesc/bin/jsesc \ No newline at end of file diff --git a/node_modules/.bin/json5 b/node_modules/.bin/json5 new file mode 120000 index 0000000..217f379 --- /dev/null +++ b/node_modules/.bin/json5 @@ -0,0 +1 @@ +../json5/lib/cli.js \ No newline at end of file diff --git a/node_modules/.bin/parser b/node_modules/.bin/parser new file mode 120000 index 0000000..ce7bf97 --- /dev/null +++ b/node_modules/.bin/parser @@ -0,0 +1 @@ +../@babel/parser/bin/babel-parser.js \ No newline at end of file diff --git a/node_modules/.bin/semver b/node_modules/.bin/semver new file mode 120000 index 0000000..5aaadf4 --- /dev/null +++ b/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver.js \ No newline at end of file diff --git a/node_modules/.bin/terser b/node_modules/.bin/terser new file mode 120000 index 0000000..0792ff4 --- /dev/null +++ b/node_modules/.bin/terser @@ -0,0 +1 @@ +../terser/bin/terser \ No newline at end of file diff --git a/node_modules/.bin/update-browserslist-db b/node_modules/.bin/update-browserslist-db new file mode 120000 index 0000000..b11e16f --- /dev/null +++ b/node_modules/.bin/update-browserslist-db @@ -0,0 +1 @@ +../update-browserslist-db/cli.js \ No newline at end of file diff --git a/node_modules/.bin/webpack b/node_modules/.bin/webpack new file mode 120000 index 0000000..d462c1d --- /dev/null +++ b/node_modules/.bin/webpack @@ -0,0 +1 @@ +../webpack/bin/webpack.js \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..fc0d5b4 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,1657 @@ +{ + "name": "gameStatusUpdate", + "lockfileVersion": 2, + "requires": true, + "packages": { + "node_modules/@ampproject/remapping": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz", + "integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==", + "dev": true, + "peer": true, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.24.7.tgz", + "integrity": "sha512-BcYH1CVJBO9tvyIZ2jVeXgSIMvGZ2FDRvDdOIVQyuklNKSsx+eppDEBq/g47Ayw+RqNFE+URvOShmf+f/qwAlA==", + "dev": true, + "peer": true, + "dependencies": { + "@babel/highlight": "^7.24.7", + "picocolors": "^1.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.25.4", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.25.4.tgz", + "integrity": "sha512-+LGRog6RAsCJrrrg/IO6LGmpphNe5DiK30dGjCoxxeGv49B10/3XYGxPsAwrDlMFcFEvdAUavDT8r9k/hSyQqQ==", + "dev": true, + "peer": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.25.2", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.25.2.tgz", + "integrity": "sha512-BBt3opiCOxUr9euZ5/ro/Xv8/V7yJ5bjYMqG/C1YAo8MIKAnumZalCN+msbci3Pigy4lIQfPUpfMM27HMGaYEA==", + "dev": true, + "peer": true, + "dependencies": { + "@ampproject/remapping": "^2.2.0", + "@babel/code-frame": "^7.24.7", + "@babel/generator": "^7.25.0", + "@babel/helper-compilation-targets": "^7.25.2", + "@babel/helper-module-transforms": "^7.25.2", + "@babel/helpers": "^7.25.0", + "@babel/parser": "^7.25.0", + "@babel/template": "^7.25.0", + "@babel/traverse": "^7.25.2", + "@babel/types": "^7.25.2", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.25.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.25.6.tgz", + "integrity": "sha512-VPC82gr1seXOpkjAAKoLhP50vx4vGNlF4msF64dSFq1P8RfB+QAuJWGHPXXPc8QyfVWwwB/TNNU4+ayZmHNbZw==", + "dev": true, + "peer": true, + "dependencies": { + "@babel/types": "^7.25.6", + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.25", + "jsesc": "^2.5.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.25.2", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.25.2.tgz", + "integrity": "sha512-U2U5LsSaZ7TAt3cfaymQ8WHh0pxvdHoEk6HVpaexxixjyEquMh0L0YNJNM6CTGKMXV1iksi0iZkGw4AcFkPaaw==", + "dev": true, + "peer": true, + "dependencies": { + "@babel/compat-data": "^7.25.2", + "@babel/helper-validator-option": "^7.24.8", + "browserslist": "^4.23.1", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.24.7.tgz", + "integrity": "sha512-8AyH3C+74cgCVVXow/myrynrAGv+nTVg5vKu2nZph9x7RcRwzmh0VFallJuFTZ9mx6u4eSdXZfcOzSqTUm0HCA==", + "dev": true, + "peer": true, + "dependencies": { + "@babel/traverse": "^7.24.7", + "@babel/types": "^7.24.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.25.2", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.25.2.tgz", + "integrity": "sha512-BjyRAbix6j/wv83ftcVJmBt72QtHI56C7JXZoG2xATiLpmoC7dpd8WnkikExHDVPpi/3qCmO6WY1EaXOluiecQ==", + "dev": true, + "peer": true, + "dependencies": { + "@babel/helper-module-imports": "^7.24.7", + "@babel/helper-simple-access": "^7.24.7", + "@babel/helper-validator-identifier": "^7.24.7", + "@babel/traverse": "^7.25.2" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-simple-access": { + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.24.7.tgz", + "integrity": "sha512-zBAIvbCMh5Ts+b86r/CjU+4XGYIs+R1j951gxI3KmmxBMhCg4oQMsv6ZXQ64XOm/cvzfU1FmoCyt6+owc5QMYg==", + "dev": true, + "peer": true, + "dependencies": { + "@babel/traverse": "^7.24.7", + "@babel/types": "^7.24.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.24.8", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.24.8.tgz", + "integrity": "sha512-pO9KhhRcuUyGnJWwyEgnRJTSIZHiT+vMD0kPeD+so0l7mxkMT19g3pjY9GTnHySck/hDzq+dtW/4VgnMkippsQ==", + "dev": true, + "peer": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.24.7.tgz", + "integrity": "sha512-rR+PBcQ1SMQDDyF6X0wxtG8QyLCgUB0eRAGguqRLfkCA87l7yAP7ehq8SNj96OOGTO8OBV70KhuFYcIkHXOg0w==", + "dev": true, + "peer": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.24.8", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.24.8.tgz", + "integrity": "sha512-xb8t9tD1MHLungh/AIoWYN+gVHaB9kwlu8gffXGSt3FFEIT7RjS+xWbc2vUD1UTZdIpKj/ab3rdqJ7ufngyi2Q==", + "dev": true, + "peer": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.25.6", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.25.6.tgz", + "integrity": "sha512-Xg0tn4HcfTijTwfDwYlvVCl43V6h4KyVVX2aEm4qdO/PC6L2YvzLHFdmxhoeSA3eslcE6+ZVXHgWwopXYLNq4Q==", + "dev": true, + "peer": true, + "dependencies": { + "@babel/template": "^7.25.0", + "@babel/types": "^7.25.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight": { + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.24.7.tgz", + "integrity": "sha512-EStJpq4OuY8xYfhGVXngigBJRWxftKX9ksiGDnmlY3o7B/V7KIAc9X4oiK87uPJSc/vs5L869bem5fhZa8caZw==", + "dev": true, + "peer": true, + "dependencies": { + "@babel/helper-validator-identifier": "^7.24.7", + "chalk": "^2.4.2", + "js-tokens": "^4.0.0", + "picocolors": "^1.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.25.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.25.6.tgz", + "integrity": "sha512-trGdfBdbD0l1ZPmcJ83eNxB9rbEax4ALFTF7fN386TMYbeCQbyme5cOEXQhbGXKebwGaB/J52w1mrklMcbgy6Q==", + "dev": true, + "peer": true, + "dependencies": { + "@babel/types": "^7.25.6" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/template": { + "version": "7.25.0", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.25.0.tgz", + "integrity": "sha512-aOOgh1/5XzKvg1jvVz7AVrx2piJ2XBi227DHmbY6y+bM9H2FlN+IfecYu4Xl0cNiiVejlsCri89LUsbj8vJD9Q==", + "dev": true, + "peer": true, + "dependencies": { + "@babel/code-frame": "^7.24.7", + "@babel/parser": "^7.25.0", + "@babel/types": "^7.25.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.25.6", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.25.6.tgz", + "integrity": "sha512-9Vrcx5ZW6UwK5tvqsj0nGpp/XzqthkT0dqIc9g1AdtygFToNtTF67XzYS//dm+SAK9cp3B9R4ZO/46p63SCjlQ==", + "dev": true, + "peer": true, + "dependencies": { + "@babel/code-frame": "^7.24.7", + "@babel/generator": "^7.25.6", + "@babel/parser": "^7.25.6", + "@babel/template": "^7.25.0", + "@babel/types": "^7.25.6", + "debug": "^4.3.1", + "globals": "^11.1.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.25.6", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.25.6.tgz", + "integrity": "sha512-/l42B1qxpG6RdfYf343Uw1vmDjeNhneUXtzhojE7pDgfpEypmRhI6j1kr17XCVv4Cgl9HdAiQY2x0GwKm7rWCw==", + "dev": true, + "peer": true, + "dependencies": { + "@babel/helper-string-parser": "^7.24.8", + "@babel/helper-validator-identifier": "^7.24.7", + "to-fast-properties": "^2.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.5.tgz", + "integrity": "sha512-IzL8ZoEDIBRWEzlCcRhOaCupYyN5gdIK+Q6fbFdPDg6HqX6jpkItn7DFIpW9LQzXG6Df9sA7+OKnq0qlz/GaQg==", + "dev": true, + "peer": true, + "dependencies": { + "@jridgewell/set-array": "^1.2.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.24" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "peer": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.2.1.tgz", + "integrity": "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==", + "dev": true, + "peer": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/source-map": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.6.tgz", + "integrity": "sha512-1ZJTZebgqllO79ue2bm3rIGud/bOe0pP5BjSRCRxxYkEZS8STV7zN84UBbiYu7jy+eCKSnVIUgoWWE/tt+shMQ==", + "dev": true, + "peer": true, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.25" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz", + "integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==", + "dev": true, + "peer": true + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", + "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "dev": true, + "peer": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@types/estree": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", + "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==", + "dev": true, + "peer": true + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true + }, + "node_modules/@types/node": { + "version": "22.5.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.5.5.tgz", + "integrity": "sha512-Xjs4y5UPO/CLdzpgR6GirZJx36yScjh73+2NlLlkFRSoQN8B0DpfXPdZGnvVmLRLOsqDpOfTNv7D9trgGhmOIA==", + "dev": true, + "peer": true, + "dependencies": { + "undici-types": "~6.19.2" + } + }, + "node_modules/@webassemblyjs/ast": { + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.12.1.tgz", + "integrity": "sha512-EKfMUOPRRUTy5UII4qJDGPpqfwjOmZ5jeGFwid9mnoqIFK+e0vqoi1qH56JpmZSzEL53jKnNzScdmftJyG5xWg==", + "dev": true, + "peer": true, + "dependencies": { + "@webassemblyjs/helper-numbers": "1.11.6", + "@webassemblyjs/helper-wasm-bytecode": "1.11.6" + } + }, + "node_modules/@webassemblyjs/floating-point-hex-parser": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.11.6.tgz", + "integrity": "sha512-ejAj9hfRJ2XMsNHk/v6Fu2dGS+i4UaXBXGemOfQ/JfQ6mdQg/WXtwleQRLLS4OvfDhv8rYnVwH27YJLMyYsxhw==", + "dev": true, + "peer": true + }, + "node_modules/@webassemblyjs/helper-api-error": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.11.6.tgz", + "integrity": "sha512-o0YkoP4pVu4rN8aTJgAyj9hC2Sv5UlkzCHhxqWj8butaLvnpdc2jOwh4ewE6CX0txSfLn/UYaV/pheS2Txg//Q==", + "dev": true, + "peer": true + }, + "node_modules/@webassemblyjs/helper-buffer": { + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.12.1.tgz", + "integrity": "sha512-nzJwQw99DNDKr9BVCOZcLuJJUlqkJh+kVzVl6Fmq/tI5ZtEyWT1KZMyOXltXLZJmDtvLCDgwsyrkohEtopTXCw==", + "dev": true, + "peer": true + }, + "node_modules/@webassemblyjs/helper-numbers": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.11.6.tgz", + "integrity": "sha512-vUIhZ8LZoIWHBohiEObxVm6hwP034jwmc9kuq5GdHZH0wiLVLIPcMCdpJzG4C11cHoQ25TFIQj9kaVADVX7N3g==", + "dev": true, + "peer": true, + "dependencies": { + "@webassemblyjs/floating-point-hex-parser": "1.11.6", + "@webassemblyjs/helper-api-error": "1.11.6", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/helper-wasm-bytecode": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.11.6.tgz", + "integrity": "sha512-sFFHKwcmBprO9e7Icf0+gddyWYDViL8bpPjJJl0WHxCdETktXdmtWLGVzoHbqUcY4Be1LkNfwTmXOJUFZYSJdA==", + "dev": true, + "peer": true + }, + "node_modules/@webassemblyjs/helper-wasm-section": { + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.12.1.tgz", + "integrity": "sha512-Jif4vfB6FJlUlSbgEMHUyk1j234GTNG9dBJ4XJdOySoj518Xj0oGsNi59cUQF4RRMS9ouBUxDDdyBVfPTypa5g==", + "dev": true, + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.12.1", + "@webassemblyjs/helper-buffer": "1.12.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.6", + "@webassemblyjs/wasm-gen": "1.12.1" + } + }, + "node_modules/@webassemblyjs/ieee754": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.11.6.tgz", + "integrity": "sha512-LM4p2csPNvbij6U1f19v6WR56QZ8JcHg3QIJTlSwzFcmx6WSORicYj6I63f9yU1kEUtrpG+kjkiIAkevHpDXrg==", + "dev": true, + "peer": true, + "dependencies": { + "@xtuc/ieee754": "^1.2.0" + } + }, + "node_modules/@webassemblyjs/leb128": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.11.6.tgz", + "integrity": "sha512-m7a0FhE67DQXgouf1tbN5XQcdWoNgaAuoULHIfGFIEVKA6tu/edls6XnIlkmS6FrXAquJRPni3ZZKjw6FSPjPQ==", + "dev": true, + "peer": true, + "dependencies": { + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/utf8": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.11.6.tgz", + "integrity": "sha512-vtXf2wTQ3+up9Zsg8sa2yWiQpzSsMyXj0qViVP6xKGCUT8p8YJ6HqI7l5eCnWx1T/FYdsv07HQs2wTFbbof/RA==", + "dev": true, + "peer": true + }, + "node_modules/@webassemblyjs/wasm-edit": { + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.12.1.tgz", + "integrity": "sha512-1DuwbVvADvS5mGnXbE+c9NfA8QRcZ6iKquqjjmR10k6o+zzsRVesil54DKexiowcFCPdr/Q0qaMgB01+SQ1u6g==", + "dev": true, + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.12.1", + "@webassemblyjs/helper-buffer": "1.12.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.6", + "@webassemblyjs/helper-wasm-section": "1.12.1", + "@webassemblyjs/wasm-gen": "1.12.1", + "@webassemblyjs/wasm-opt": "1.12.1", + "@webassemblyjs/wasm-parser": "1.12.1", + "@webassemblyjs/wast-printer": "1.12.1" + } + }, + "node_modules/@webassemblyjs/wasm-gen": { + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.12.1.tgz", + "integrity": "sha512-TDq4Ojh9fcohAw6OIMXqiIcTq5KUXTGRkVxbSo1hQnSy6lAM5GSdfwWeSxpAo0YzgsgF182E/U0mDNhuA0tW7w==", + "dev": true, + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.12.1", + "@webassemblyjs/helper-wasm-bytecode": "1.11.6", + "@webassemblyjs/ieee754": "1.11.6", + "@webassemblyjs/leb128": "1.11.6", + "@webassemblyjs/utf8": "1.11.6" + } + }, + "node_modules/@webassemblyjs/wasm-opt": { + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.12.1.tgz", + "integrity": "sha512-Jg99j/2gG2iaz3hijw857AVYekZe2SAskcqlWIZXjji5WStnOpVoat3gQfT/Q5tb2djnCjBtMocY/Su1GfxPBg==", + "dev": true, + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.12.1", + "@webassemblyjs/helper-buffer": "1.12.1", + "@webassemblyjs/wasm-gen": "1.12.1", + "@webassemblyjs/wasm-parser": "1.12.1" + } + }, + "node_modules/@webassemblyjs/wasm-parser": { + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.12.1.tgz", + "integrity": "sha512-xikIi7c2FHXysxXe3COrVUPSheuBtpcfhbpFj4gmu7KRLYOzANztwUU0IbsqvMqzuNK2+glRGWCEqZo1WCLyAQ==", + "dev": true, + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.12.1", + "@webassemblyjs/helper-api-error": "1.11.6", + "@webassemblyjs/helper-wasm-bytecode": "1.11.6", + "@webassemblyjs/ieee754": "1.11.6", + "@webassemblyjs/leb128": "1.11.6", + "@webassemblyjs/utf8": "1.11.6" + } + }, + "node_modules/@webassemblyjs/wast-printer": { + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.12.1.tgz", + "integrity": "sha512-+X4WAlOisVWQMikjbcvY2e0rwPsKQ9F688lksZhBcPycBBuii3O7m8FACbDMWDojpAqvjIncrG8J0XHKyQfVeA==", + "dev": true, + "peer": true, + "dependencies": { + "@webassemblyjs/ast": "1.12.1", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@xtuc/ieee754": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", + "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", + "dev": true, + "peer": true + }, + "node_modules/@xtuc/long": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", + "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", + "dev": true, + "peer": true + }, + "node_modules/acorn": { + "version": "8.12.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.12.1.tgz", + "integrity": "sha512-tcpGyI9zbizT9JbV6oYE477V6mTlXvvi0T0G3SNIYE2apm/G5huBa1+K89VGeovbg+jycCrfhl3ADxErOuO6Jg==", + "dev": true, + "peer": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-import-attributes": { + "version": "1.9.5", + "resolved": "https://registry.npmjs.org/acorn-import-attributes/-/acorn-import-attributes-1.9.5.tgz", + "integrity": "sha512-n02Vykv5uA3eHGM/Z2dQrcD56kL8TyDb2p1+0P83PClMnC/nc+anbQRhIOWnSq4Ke/KvDPrY3C9hDtC/A3eHnQ==", + "dev": true, + "peer": true, + "peerDependencies": { + "acorn": "^8" + } + }, + "node_modules/ajv": { + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", + "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz", + "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==", + "dev": true, + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ajv-keywords": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz", + "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.3" + }, + "peerDependencies": { + "ajv": "^8.8.2" + } + }, + "node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "peer": true, + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/babel-loader": { + "version": "9.2.1", + "resolved": "https://registry.npmjs.org/babel-loader/-/babel-loader-9.2.1.tgz", + "integrity": "sha512-fqe8naHt46e0yIdkjUZYqddSXfej3AHajX+CSO5X7oy0EmPc6o5Xh+RClNoHjnieWz9AW4kZxW9yyFMhVB1QLA==", + "dev": true, + "dependencies": { + "find-cache-dir": "^4.0.0", + "schema-utils": "^4.0.0" + }, + "engines": { + "node": ">= 14.15.0" + }, + "peerDependencies": { + "@babel/core": "^7.12.0", + "webpack": ">=5" + } + }, + "node_modules/browserslist": { + "version": "4.23.3", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.23.3.tgz", + "integrity": "sha512-btwCFJVjI4YWDNfau8RhZ+B1Q/VLoUITrm3RlP6y1tYGWIOa+InuYiRGXUBXo8nA1qKmHMyLB/iVQg5TT4eFoA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "peer": true, + "dependencies": { + "caniuse-lite": "^1.0.30001646", + "electron-to-chromium": "^1.5.4", + "node-releases": "^2.0.18", + "update-browserslist-db": "^1.1.0" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true, + "peer": true + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001660", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001660.tgz", + "integrity": "sha512-GacvNTTuATm26qC74pt+ad1fW15mlQ/zuTzzY1ZoIzECTP8HURDfF43kNxPgf7H1jmelCBQTTbBNxdSXOA7Bqg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "peer": true + }, + "node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "peer": true, + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/chrome-trace-event": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.4.tgz", + "integrity": "sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ==", + "dev": true, + "peer": true, + "engines": { + "node": ">=6.0" + } + }, + "node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "peer": true, + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true, + "peer": true + }, + "node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true, + "peer": true + }, + "node_modules/common-path-prefix": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/common-path-prefix/-/common-path-prefix-3.0.0.tgz", + "integrity": "sha512-QE33hToZseCH3jS0qN96O/bSh3kaw/h+Tq7ngyY9eWDUnTlTNUyqfqvCXioLe5Na5jFsL78ra/wuBU4iuEgd4w==", + "dev": true + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "peer": true + }, + "node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "dev": true, + "peer": true, + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.25", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.25.tgz", + "integrity": "sha512-kMb204zvK3PsSlgvvwzI3wBIcAw15tRkYk+NQdsjdDtcQWTp2RABbMQ9rUBy8KNEOM+/E6ep+XC3AykiWZld4g==", + "dev": true, + "peer": true + }, + "node_modules/enhanced-resolve": { + "version": "5.17.1", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.17.1.tgz", + "integrity": "sha512-LMHl3dXhTcfv8gM4kEzIUeTQ+7fpdA0l2tUf34BddXPkz2A5xJ5L/Pchd5BL6rdccM9QGvu0sWZzK1Z1t4wwyg==", + "dev": true, + "peer": true, + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.2.0" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/es-module-lexer": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.5.4.tgz", + "integrity": "sha512-MVNK56NiMrOwitFB7cqDwq0CQutbw+0BvLshJSse0MUNU+y1FC3bUS/AQg7oUng+/wKrrki7JfmwtVHkVfPLlw==", + "dev": true, + "peer": true + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true, + "peer": true, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/eslint-scope": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", + "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", + "dev": true, + "peer": true, + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^4.1.1" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "peer": true, + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esrecurse/node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "dev": true, + "peer": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "dev": true, + "peer": true, + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "peer": true + }, + "node_modules/fast-uri": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.0.1.tgz", + "integrity": "sha512-MWipKbbYiYI0UC7cl8m/i/IWTqfC8YXsqjzybjddLsFjStroQzsHXkc73JutMvBiXmOvapk+axIl79ig5t55Bw==", + "dev": true + }, + "node_modules/find-cache-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-4.0.0.tgz", + "integrity": "sha512-9ZonPT4ZAK4a+1pUPVPZJapbi7O5qbbJPdYw/NOQWZZbVLdDTYM3A4R9z/DpAM08IDaFGsvPgiGZ82WEwUDWjg==", + "dev": true, + "dependencies": { + "common-path-prefix": "^3.0.0", + "pkg-dir": "^7.0.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/find-up": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-6.3.0.tgz", + "integrity": "sha512-v2ZsoEuVHYy8ZIlYqwPe/39Cy+cFDzp4dXPaxNvkEuouymu+2Jbz0PxpKarJHYJTmv2HWT3O382qY8l4jMWthw==", + "dev": true, + "dependencies": { + "locate-path": "^7.1.0", + "path-exists": "^5.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "peer": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/glob-to-regexp": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz", + "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", + "dev": true, + "peer": true + }, + "node_modules/globals": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "dev": true, + "peer": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true, + "peer": true + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "peer": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/jest-worker": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz", + "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==", + "dev": true, + "peer": true, + "dependencies": { + "@types/node": "*", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": ">= 10.13.0" + } + }, + "node_modules/jest-worker/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-worker/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "peer": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "peer": true + }, + "node_modules/jsesc": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", + "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "dev": true, + "peer": true, + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true, + "peer": true + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "peer": true, + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/loader-runner": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.0.tgz", + "integrity": "sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==", + "dev": true, + "peer": true, + "engines": { + "node": ">=6.11.5" + } + }, + "node_modules/locate-path": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-7.2.0.tgz", + "integrity": "sha512-gvVijfZvn7R+2qyPX8mAuKcFGDf6Nc61GdvGafQsHL0sBIxfKzA+usWn4GFC/bk+QdwPUD4kWFJLhElipq+0VA==", + "dev": true, + "dependencies": { + "p-locate": "^6.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "peer": true, + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true, + "peer": true + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true, + "peer": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "peer": true, + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "peer": true + }, + "node_modules/neo-async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", + "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", + "dev": true, + "peer": true + }, + "node_modules/node-releases": { + "version": "2.0.18", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.18.tgz", + "integrity": "sha512-d9VeXT4SJ7ZeOqGX6R5EM022wpL+eWPooLI+5UpWn2jCT1aosUQEhQP214x33Wkwx3JQMvIm+tIoVOdodFS40g==", + "dev": true, + "peer": true + }, + "node_modules/p-limit": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-4.0.0.tgz", + "integrity": "sha512-5b0R4txpzjPWVw/cXXUResoD4hb6U/x9BH08L7nw+GN1sezDzPdxeRvpc9c433fZhBan/wusjbCsqwqm4EIBIQ==", + "dev": true, + "dependencies": { + "yocto-queue": "^1.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-6.0.0.tgz", + "integrity": "sha512-wPrq66Llhl7/4AGC6I+cqxT07LhXvWL08LNXz1fENOw0Ap4sRZZ/gZpTTJ5jpurzzzfS2W/Ge9BY3LgLjCShcw==", + "dev": true, + "dependencies": { + "p-limit": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/path-exists": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-5.0.0.tgz", + "integrity": "sha512-RjhtfwJOxzcFmNOi6ltcbcu4Iu+FL3zEj83dk4kAS+fVpTxXLO1b38RvJgT/0QwvV/L3aY9TAnyv0EOqW4GoMQ==", + "dev": true, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/picocolors": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.0.tgz", + "integrity": "sha512-TQ92mBOW0l3LeMeyLV6mzy/kWr8lkd/hp3mTg7wYK7zJhuBStmGMBG0BdeDZS/dZx1IukaX6Bk11zcln25o1Aw==", + "dev": true, + "peer": true + }, + "node_modules/pkg-dir": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-7.0.0.tgz", + "integrity": "sha512-Ie9z/WINcxxLp27BKOCHGde4ITq9UklYKDzVo1nhk5sqGEXU3FpkwP5GM2voTGJkGd9B3Otl+Q4uwSOeSUtOBA==", + "dev": true, + "dependencies": { + "find-up": "^6.3.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "peer": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "dev": true, + "peer": true, + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "peer": true + }, + "node_modules/schema-utils": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.2.0.tgz", + "integrity": "sha512-L0jRsrPpjdckP3oPug3/VxNKt2trR8TcabrM6FOAAlvC/9Phcmm+cuAgTlxBqdBR1WJx7Naj9WHw+aOmheSVbw==", + "dev": true, + "dependencies": { + "@types/json-schema": "^7.0.9", + "ajv": "^8.9.0", + "ajv-formats": "^2.1.1", + "ajv-keywords": "^5.1.0" + }, + "engines": { + "node": ">= 12.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "peer": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/serialize-javascript": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz", + "integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==", + "dev": true, + "peer": true, + "dependencies": { + "randombytes": "^2.1.0" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "peer": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "peer": true, + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/tapable": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.2.1.tgz", + "integrity": "sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==", + "dev": true, + "peer": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/terser": { + "version": "5.33.0", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.33.0.tgz", + "integrity": "sha512-JuPVaB7s1gdFKPKTelwUyRq5Sid2A3Gko2S0PncwdBq7kN9Ti9HPWDQ06MPsEDGsZeVESjKEnyGy68quBk1w6g==", + "dev": true, + "peer": true, + "dependencies": { + "@jridgewell/source-map": "^0.3.3", + "acorn": "^8.8.2", + "commander": "^2.20.0", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/terser-webpack-plugin": { + "version": "5.3.10", + "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.3.10.tgz", + "integrity": "sha512-BKFPWlPDndPs+NGGCr1U59t0XScL5317Y0UReNrHaw9/FwhPENlq6bfgs+4yPfyP51vqC1bQ4rp1EfXW5ZSH9w==", + "dev": true, + "peer": true, + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.20", + "jest-worker": "^27.4.5", + "schema-utils": "^3.1.1", + "serialize-javascript": "^6.0.1", + "terser": "^5.26.0" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.1.0" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "uglify-js": { + "optional": true + } + } + }, + "node_modules/terser-webpack-plugin/node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "peer": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/terser-webpack-plugin/node_modules/ajv-keywords": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", + "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", + "dev": true, + "peer": true, + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/terser-webpack-plugin/node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "peer": true + }, + "node_modules/terser-webpack-plugin/node_modules/schema-utils": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.3.0.tgz", + "integrity": "sha512-pN/yOAvcC+5rQ5nERGuwrjLlYvLTbCibnZ1I7B1LaiAz9BRBlE9GMgE/eqV30P7aJQUf7Ddimy/RsbYO/GrVGg==", + "dev": true, + "peer": true, + "dependencies": { + "@types/json-schema": "^7.0.8", + "ajv": "^6.12.5", + "ajv-keywords": "^3.5.2" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", + "dev": true, + "peer": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/undici-types": { + "version": "6.19.8", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", + "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", + "dev": true, + "peer": true + }, + "node_modules/update-browserslist-db": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.0.tgz", + "integrity": "sha512-EdRAaAyk2cUE1wOf2DkEhzxqOQvFOoRJFNS6NeyJ01Gp2beMRpBAINjM2iDXE3KCuKhwnvHIQCJm6ThL2Z+HzQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "peer": true, + "dependencies": { + "escalade": "^3.1.2", + "picocolors": "^1.0.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "peer": true, + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/watchpack": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.4.2.tgz", + "integrity": "sha512-TnbFSbcOCcDgjZ4piURLCbJ3nJhznVh9kw6F6iokjiFPl8ONxe9A6nMDVXDiNbrSfLILs6vB07F7wLBrwPYzJw==", + "dev": true, + "peer": true, + "dependencies": { + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.1.2" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/webpack": { + "version": "5.94.0", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.94.0.tgz", + "integrity": "sha512-KcsGn50VT+06JH/iunZJedYGUJS5FGjow8wb9c0v5n1Om8O1g4L6LjtfxwlXIATopoQu+vOXXa7gYisWxCoPyg==", + "dev": true, + "peer": true, + "dependencies": { + "@types/estree": "^1.0.5", + "@webassemblyjs/ast": "^1.12.1", + "@webassemblyjs/wasm-edit": "^1.12.1", + "@webassemblyjs/wasm-parser": "^1.12.1", + "acorn": "^8.7.1", + "acorn-import-attributes": "^1.9.5", + "browserslist": "^4.21.10", + "chrome-trace-event": "^1.0.2", + "enhanced-resolve": "^5.17.1", + "es-module-lexer": "^1.2.1", + "eslint-scope": "5.1.1", + "events": "^3.2.0", + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.2.11", + "json-parse-even-better-errors": "^2.3.1", + "loader-runner": "^4.2.0", + "mime-types": "^2.1.27", + "neo-async": "^2.6.2", + "schema-utils": "^3.2.0", + "tapable": "^2.1.1", + "terser-webpack-plugin": "^5.3.10", + "watchpack": "^2.4.1", + "webpack-sources": "^3.2.3" + }, + "bin": { + "webpack": "bin/webpack.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependenciesMeta": { + "webpack-cli": { + "optional": true + } + } + }, + "node_modules/webpack-sources": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.2.3.tgz", + "integrity": "sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w==", + "dev": true, + "peer": true, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/webpack/node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "peer": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/webpack/node_modules/ajv-keywords": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", + "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", + "dev": true, + "peer": true, + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/webpack/node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "peer": true + }, + "node_modules/webpack/node_modules/schema-utils": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.3.0.tgz", + "integrity": "sha512-pN/yOAvcC+5rQ5nERGuwrjLlYvLTbCibnZ1I7B1LaiAz9BRBlE9GMgE/eqV30P7aJQUf7Ddimy/RsbYO/GrVGg==", + "dev": true, + "peer": true, + "dependencies": { + "@types/json-schema": "^7.0.8", + "ajv": "^6.12.5", + "ajv-keywords": "^3.5.2" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "peer": true + }, + "node_modules/yocto-queue": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.1.1.tgz", + "integrity": "sha512-b4JR1PFR10y1mKjhHY9LaGo6tmrgjit7hxVIeAmyMw3jegXR4dhYqLaQF5zMXZxY7tLpMyJeLjr1C4rLmkVe8g==", + "dev": true, + "engines": { + "node": ">=12.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/node_modules/@ampproject/remapping/LICENSE b/node_modules/@ampproject/remapping/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/@ampproject/remapping/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@ampproject/remapping/README.md b/node_modules/@ampproject/remapping/README.md new file mode 100644 index 0000000..1463c9f --- /dev/null +++ b/node_modules/@ampproject/remapping/README.md @@ -0,0 +1,218 @@ +# @ampproject/remapping + +> Remap sequential sourcemaps through transformations to point at the original source code + +Remapping allows you to take the sourcemaps generated through transforming your code and "remap" +them to the original source locations. Think "my minified code, transformed with babel and bundled +with webpack", all pointing to the correct location in your original source code. + +With remapping, none of your source code transformations need to be aware of the input's sourcemap, +they only need to generate an output sourcemap. This greatly simplifies building custom +transformations (think a find-and-replace). + +## Installation + +```sh +npm install @ampproject/remapping +``` + +## Usage + +```typescript +function remapping( + map: SourceMap | SourceMap[], + loader: (file: string, ctx: LoaderContext) => (SourceMap | null | undefined), + options?: { excludeContent: boolean, decodedMappings: boolean } +): SourceMap; + +// LoaderContext gives the loader the importing sourcemap, tree depth, the ability to override the +// "source" location (where child sources are resolved relative to, or the location of original +// source), and the ability to override the "content" of an original source for inclusion in the +// output sourcemap. +type LoaderContext = { + readonly importer: string; + readonly depth: number; + source: string; + content: string | null | undefined; +} +``` + +`remapping` takes the final output sourcemap, and a `loader` function. For every source file pointer +in the sourcemap, the `loader` will be called with the resolved path. If the path itself represents +a transformed file (it has a sourcmap associated with it), then the `loader` should return that +sourcemap. If not, the path will be treated as an original, untransformed source code. + +```js +// Babel transformed "helloworld.js" into "transformed.js" +const transformedMap = JSON.stringify({ + file: 'transformed.js', + // 1st column of 2nd line of output file translates into the 1st source + // file, line 3, column 2 + mappings: ';CAEE', + sources: ['helloworld.js'], + version: 3, +}); + +// Uglify minified "transformed.js" into "transformed.min.js" +const minifiedTransformedMap = JSON.stringify({ + file: 'transformed.min.js', + // 0th column of 1st line of output file translates into the 1st source + // file, line 2, column 1. + mappings: 'AACC', + names: [], + sources: ['transformed.js'], + version: 3, +}); + +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + // The "transformed.js" file is an transformed file. + if (file === 'transformed.js') { + // The root importer is empty. + console.assert(ctx.importer === ''); + // The depth in the sourcemap tree we're currently loading. + // The root `minifiedTransformedMap` is depth 0, and its source children are depth 1, etc. + console.assert(ctx.depth === 1); + + return transformedMap; + } + + // Loader will be called to load transformedMap's source file pointers as well. + console.assert(file === 'helloworld.js'); + // `transformed.js`'s sourcemap points into `helloworld.js`. + console.assert(ctx.importer === 'transformed.js'); + // This is a source child of `transformed`, which is a source child of `minifiedTransformedMap`. + console.assert(ctx.depth === 2); + return null; + } +); + +console.log(remapped); +// { +// file: 'transpiled.min.js', +// mappings: 'AAEE', +// sources: ['helloworld.js'], +// version: 3, +// }; +``` + +In this example, `loader` will be called twice: + +1. `"transformed.js"`, the first source file pointer in the `minifiedTransformedMap`. We return the + associated sourcemap for it (its a transformed file, after all) so that sourcemap locations can + be traced through it into the source files it represents. +2. `"helloworld.js"`, our original, unmodified source code. This file does not have a sourcemap, so + we return `null`. + +The `remapped` sourcemap now points from `transformed.min.js` into locations in `helloworld.js`. If +you were to read the `mappings`, it says "0th column of the first line output line points to the 1st +column of the 2nd line of the file `helloworld.js`". + +### Multiple transformations of a file + +As a convenience, if you have multiple single-source transformations of a file, you may pass an +array of sourcemap files in the order of most-recent transformation sourcemap first. Note that this +changes the `importer` and `depth` of each call to our loader. So our above example could have been +written as: + +```js +const remapped = remapping( + [minifiedTransformedMap, transformedMap], + () => null +); + +console.log(remapped); +// { +// file: 'transpiled.min.js', +// mappings: 'AAEE', +// sources: ['helloworld.js'], +// version: 3, +// }; +``` + +### Advanced control of the loading graph + +#### `source` + +The `source` property can overridden to any value to change the location of the current load. Eg, +for an original source file, it allows us to change the location to the original source regardless +of what the sourcemap source entry says. And for transformed files, it allows us to change the +relative resolving location for child sources of the loaded sourcemap. + +```js +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + if (file === 'transformed.js') { + // We pretend the transformed.js file actually exists in the 'src/' directory. When the nested + // source files are loaded, they will now be relative to `src/`. + ctx.source = 'src/transformed.js'; + return transformedMap; + } + + console.assert(file === 'src/helloworld.js'); + // We could futher change the source of this original file, eg, to be inside a nested directory + // itself. This will be reflected in the remapped sourcemap. + ctx.source = 'src/nested/transformed.js'; + return null; + } +); + +console.log(remapped); +// { +// …, +// sources: ['src/nested/helloworld.js'], +// }; +``` + + +#### `content` + +The `content` property can be overridden when we encounter an original source file. Eg, this allows +you to manually provide the source content of the original file regardless of whether the +`sourcesContent` field is present in the parent sourcemap. It can also be set to `null` to remove +the source content. + +```js +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + if (file === 'transformed.js') { + // transformedMap does not include a `sourcesContent` field, so usually the remapped sourcemap + // would not include any `sourcesContent` values. + return transformedMap; + } + + console.assert(file === 'helloworld.js'); + // We can read the file to provide the source content. + ctx.content = fs.readFileSync(file, 'utf8'); + return null; + } +); + +console.log(remapped); +// { +// …, +// sourcesContent: [ +// 'console.log("Hello world!")', +// ], +// }; +``` + +### Options + +#### excludeContent + +By default, `excludeContent` is `false`. Passing `{ excludeContent: true }` will exclude the +`sourcesContent` field from the returned sourcemap. This is mainly useful when you want to reduce +the size out the sourcemap. + +#### decodedMappings + +By default, `decodedMappings` is `false`. Passing `{ decodedMappings: true }` will leave the +`mappings` field in a [decoded state](https://github.com/rich-harris/sourcemap-codec) instead of +encoding into a VLQ string. diff --git a/node_modules/@ampproject/remapping/dist/remapping.mjs b/node_modules/@ampproject/remapping/dist/remapping.mjs new file mode 100644 index 0000000..f387599 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.mjs @@ -0,0 +1,197 @@ +import { decodedMappings, traceSegment, TraceMap } from '@jridgewell/trace-mapping'; +import { GenMapping, maybeAddSegment, setSourceContent, setIgnore, toDecodedMap, toEncodedMap } from '@jridgewell/gen-mapping'; + +const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null, false); +const EMPTY_SOURCES = []; +function SegmentObject(source, line, column, name, content, ignore) { + return { source, line, column, name, content, ignore }; +} +function Source(map, sources, source, content, ignore) { + return { + map, + sources, + source, + content, + ignore, + }; +} +/** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ +function MapSource(map, sources) { + return Source(map, sources, '', null, false); +} +/** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ +function OriginalSource(source, content, ignore) { + return Source(null, EMPTY_SOURCES, source, content, ignore); +} +/** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ +function traceMappings(tree) { + // TODO: Eventually support sourceRoot, which has to be removed because the sources are already + // fully resolved. We'll need to make sources relative to the sourceRoot before adding them. + const gen = new GenMapping({ file: tree.map.file }); + const { sources: rootSources, map } = tree; + const rootNames = map.names; + const rootMappings = decodedMappings(map); + for (let i = 0; i < rootMappings.length; i++) { + const segments = rootMappings[i]; + for (let j = 0; j < segments.length; j++) { + const segment = segments[j]; + const genCol = segment[0]; + let traced = SOURCELESS_MAPPING; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length !== 1) { + const source = rootSources[segment[1]]; + traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); + // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a + // respective segment into an original source. + if (traced == null) + continue; + } + const { column, line, name, content, source, ignore } = traced; + maybeAddSegment(gen, i, genCol, source, line, column, name); + if (source && content != null) + setSourceContent(gen, source, content); + if (ignore) + setIgnore(gen, source, true); + } + } + return gen; +} +/** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ +function originalPositionFor(source, line, column, name) { + if (!source.map) { + return SegmentObject(source.source, line, column, name, source.content, source.ignore); + } + const segment = traceSegment(source.map, line, column); + // If we couldn't find a segment, then this doesn't exist in the sourcemap. + if (segment == null) + return null; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length === 1) + return SOURCELESS_MAPPING; + return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name); +} + +function asArray(value) { + if (Array.isArray(value)) + return value; + return [value]; +} +/** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ +function buildSourceMapTree(input, loader) { + const maps = asArray(input).map((m) => new TraceMap(m, '')); + const map = maps.pop(); + for (let i = 0; i < maps.length; i++) { + if (maps[i].sources.length > 1) { + throw new Error(`Transformation map ${i} must have exactly one source file.\n` + + 'Did you specify these with the most recent transformation maps first?'); + } + } + let tree = build(map, loader, '', 0); + for (let i = maps.length - 1; i >= 0; i--) { + tree = MapSource(maps[i], [tree]); + } + return tree; +} +function build(map, loader, importer, importerDepth) { + const { resolvedSources, sourcesContent, ignoreList } = map; + const depth = importerDepth + 1; + const children = resolvedSources.map((sourceFile, i) => { + // The loading context gives the loader more information about why this file is being loaded + // (eg, from which importer). It also allows the loader to override the location of the loaded + // sourcemap/original source, or to override the content in the sourcesContent field if it's + // an unmodified source file. + const ctx = { + importer, + depth, + source: sourceFile || '', + content: undefined, + ignore: undefined, + }; + // Use the provided loader callback to retrieve the file's sourcemap. + // TODO: We should eventually support async loading of sourcemap files. + const sourceMap = loader(ctx.source, ctx); + const { source, content, ignore } = ctx; + // If there is a sourcemap, then we need to recurse into it to load its source files. + if (sourceMap) + return build(new TraceMap(sourceMap, source), loader, source, depth); + // Else, it's an unmodified source file. + // The contents of this unmodified source file can be overridden via the loader context, + // allowing it to be explicitly null or a string. If it remains undefined, we fall back to + // the importing sourcemap's `sourcesContent` field. + const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null; + const ignored = ignore !== undefined ? ignore : ignoreList ? ignoreList.includes(i) : false; + return OriginalSource(source, sourceContent, ignored); + }); + return MapSource(map, children); +} + +/** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ +class SourceMap { + constructor(map, options) { + const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map); + this.version = out.version; // SourceMap spec says this should be first. + this.file = out.file; + this.mappings = out.mappings; + this.names = out.names; + this.ignoreList = out.ignoreList; + this.sourceRoot = out.sourceRoot; + this.sources = out.sources; + if (!options.excludeContent) { + this.sourcesContent = out.sourcesContent; + } + } + toString() { + return JSON.stringify(this); + } +} + +/** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ +function remapping(input, loader, options) { + const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false }; + const tree = buildSourceMapTree(input, loader); + return new SourceMap(traceMappings(tree), opts); +} + +export { remapping as default }; +//# sourceMappingURL=remapping.mjs.map diff --git a/node_modules/@ampproject/remapping/dist/remapping.mjs.map b/node_modules/@ampproject/remapping/dist/remapping.mjs.map new file mode 100644 index 0000000..0eb007b --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"remapping.mjs","sources":["../src/source-map-tree.ts","../src/build-source-map-tree.ts","../src/source-map.ts","../src/remapping.ts"],"sourcesContent":["import { GenMapping, maybeAddSegment, setIgnore, setSourceContent } from '@jridgewell/gen-mapping';\nimport { traceSegment, decodedMappings } from '@jridgewell/trace-mapping';\n\nimport type { TraceMap } from '@jridgewell/trace-mapping';\n\nexport type SourceMapSegmentObject = {\n column: number;\n line: number;\n name: string;\n source: string;\n content: string | null;\n ignore: boolean;\n};\n\nexport type OriginalSource = {\n map: null;\n sources: Sources[];\n source: string;\n content: string | null;\n ignore: boolean;\n};\n\nexport type MapSource = {\n map: TraceMap;\n sources: Sources[];\n source: string;\n content: null;\n ignore: false;\n};\n\nexport type Sources = OriginalSource | MapSource;\n\nconst SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null, false);\nconst EMPTY_SOURCES: Sources[] = [];\n\nfunction SegmentObject(\n source: string,\n line: number,\n column: number,\n name: string,\n content: string | null,\n ignore: boolean\n): SourceMapSegmentObject {\n return { source, line, column, name, content, ignore };\n}\n\nfunction Source(\n map: TraceMap,\n sources: Sources[],\n source: '',\n content: null,\n ignore: false\n): MapSource;\nfunction Source(\n map: null,\n sources: Sources[],\n source: string,\n content: string | null,\n ignore: boolean\n): OriginalSource;\nfunction Source(\n map: TraceMap | null,\n sources: Sources[],\n source: string | '',\n content: string | null,\n ignore: boolean\n): Sources {\n return {\n map,\n sources,\n source,\n content,\n ignore,\n } as any;\n}\n\n/**\n * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes\n * (which may themselves be SourceMapTrees).\n */\nexport function MapSource(map: TraceMap, sources: Sources[]): MapSource {\n return Source(map, sources, '', null, false);\n}\n\n/**\n * A \"leaf\" node in the sourcemap tree, representing an original, unmodified source file. Recursive\n * segment tracing ends at the `OriginalSource`.\n */\nexport function OriginalSource(\n source: string,\n content: string | null,\n ignore: boolean\n): OriginalSource {\n return Source(null, EMPTY_SOURCES, source, content, ignore);\n}\n\n/**\n * traceMappings is only called on the root level SourceMapTree, and begins the process of\n * resolving each mapping in terms of the original source files.\n */\nexport function traceMappings(tree: MapSource): GenMapping {\n // TODO: Eventually support sourceRoot, which has to be removed because the sources are already\n // fully resolved. We'll need to make sources relative to the sourceRoot before adding them.\n const gen = new GenMapping({ file: tree.map.file });\n const { sources: rootSources, map } = tree;\n const rootNames = map.names;\n const rootMappings = decodedMappings(map);\n\n for (let i = 0; i < rootMappings.length; i++) {\n const segments = rootMappings[i];\n\n for (let j = 0; j < segments.length; j++) {\n const segment = segments[j];\n const genCol = segment[0];\n let traced: SourceMapSegmentObject | null = SOURCELESS_MAPPING;\n\n // 1-length segments only move the current generated column, there's no source information\n // to gather from it.\n if (segment.length !== 1) {\n const source = rootSources[segment[1]];\n traced = originalPositionFor(\n source,\n segment[2],\n segment[3],\n segment.length === 5 ? rootNames[segment[4]] : ''\n );\n\n // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a\n // respective segment into an original source.\n if (traced == null) continue;\n }\n\n const { column, line, name, content, source, ignore } = traced;\n\n maybeAddSegment(gen, i, genCol, source, line, column, name);\n if (source && content != null) setSourceContent(gen, source, content);\n if (ignore) setIgnore(gen, source, true);\n }\n }\n\n return gen;\n}\n\n/**\n * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own\n * child SourceMapTrees, until we find the original source map.\n */\nexport function originalPositionFor(\n source: Sources,\n line: number,\n column: number,\n name: string\n): SourceMapSegmentObject | null {\n if (!source.map) {\n return SegmentObject(source.source, line, column, name, source.content, source.ignore);\n }\n\n const segment = traceSegment(source.map, line, column);\n\n // If we couldn't find a segment, then this doesn't exist in the sourcemap.\n if (segment == null) return null;\n // 1-length segments only move the current generated column, there's no source information\n // to gather from it.\n if (segment.length === 1) return SOURCELESS_MAPPING;\n\n return originalPositionFor(\n source.sources[segment[1]],\n segment[2],\n segment[3],\n segment.length === 5 ? source.map.names[segment[4]] : name\n );\n}\n","import { TraceMap } from '@jridgewell/trace-mapping';\n\nimport { OriginalSource, MapSource } from './source-map-tree';\n\nimport type { Sources, MapSource as MapSourceType } from './source-map-tree';\nimport type { SourceMapInput, SourceMapLoader, LoaderContext } from './types';\n\nfunction asArray(value: T | T[]): T[] {\n if (Array.isArray(value)) return value;\n return [value];\n}\n\n/**\n * Recursively builds a tree structure out of sourcemap files, with each node\n * being either an `OriginalSource` \"leaf\" or a `SourceMapTree` composed of\n * `OriginalSource`s and `SourceMapTree`s.\n *\n * Every sourcemap is composed of a collection of source files and mappings\n * into locations of those source files. When we generate a `SourceMapTree` for\n * the sourcemap, we attempt to load each source file's own sourcemap. If it\n * does not have an associated sourcemap, it is considered an original,\n * unmodified source file.\n */\nexport default function buildSourceMapTree(\n input: SourceMapInput | SourceMapInput[],\n loader: SourceMapLoader\n): MapSourceType {\n const maps = asArray(input).map((m) => new TraceMap(m, ''));\n const map = maps.pop()!;\n\n for (let i = 0; i < maps.length; i++) {\n if (maps[i].sources.length > 1) {\n throw new Error(\n `Transformation map ${i} must have exactly one source file.\\n` +\n 'Did you specify these with the most recent transformation maps first?'\n );\n }\n }\n\n let tree = build(map, loader, '', 0);\n for (let i = maps.length - 1; i >= 0; i--) {\n tree = MapSource(maps[i], [tree]);\n }\n return tree;\n}\n\nfunction build(\n map: TraceMap,\n loader: SourceMapLoader,\n importer: string,\n importerDepth: number\n): MapSourceType {\n const { resolvedSources, sourcesContent, ignoreList } = map;\n\n const depth = importerDepth + 1;\n const children = resolvedSources.map((sourceFile: string | null, i: number): Sources => {\n // The loading context gives the loader more information about why this file is being loaded\n // (eg, from which importer). It also allows the loader to override the location of the loaded\n // sourcemap/original source, or to override the content in the sourcesContent field if it's\n // an unmodified source file.\n const ctx: LoaderContext = {\n importer,\n depth,\n source: sourceFile || '',\n content: undefined,\n ignore: undefined,\n };\n\n // Use the provided loader callback to retrieve the file's sourcemap.\n // TODO: We should eventually support async loading of sourcemap files.\n const sourceMap = loader(ctx.source, ctx);\n\n const { source, content, ignore } = ctx;\n\n // If there is a sourcemap, then we need to recurse into it to load its source files.\n if (sourceMap) return build(new TraceMap(sourceMap, source), loader, source, depth);\n\n // Else, it's an unmodified source file.\n // The contents of this unmodified source file can be overridden via the loader context,\n // allowing it to be explicitly null or a string. If it remains undefined, we fall back to\n // the importing sourcemap's `sourcesContent` field.\n const sourceContent =\n content !== undefined ? content : sourcesContent ? sourcesContent[i] : null;\n const ignored = ignore !== undefined ? ignore : ignoreList ? ignoreList.includes(i) : false;\n return OriginalSource(source, sourceContent, ignored);\n });\n\n return MapSource(map, children);\n}\n","import { toDecodedMap, toEncodedMap } from '@jridgewell/gen-mapping';\n\nimport type { GenMapping } from '@jridgewell/gen-mapping';\nimport type { DecodedSourceMap, EncodedSourceMap, Options } from './types';\n\n/**\n * A SourceMap v3 compatible sourcemap, which only includes fields that were\n * provided to it.\n */\nexport default class SourceMap {\n declare file?: string | null;\n declare mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings'];\n declare sourceRoot?: string;\n declare names: string[];\n declare sources: (string | null)[];\n declare sourcesContent?: (string | null)[];\n declare version: 3;\n declare ignoreList: number[] | undefined;\n\n constructor(map: GenMapping, options: Options) {\n const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);\n this.version = out.version; // SourceMap spec says this should be first.\n this.file = out.file;\n this.mappings = out.mappings as SourceMap['mappings'];\n this.names = out.names as SourceMap['names'];\n this.ignoreList = out.ignoreList as SourceMap['ignoreList'];\n this.sourceRoot = out.sourceRoot;\n\n this.sources = out.sources as SourceMap['sources'];\n if (!options.excludeContent) {\n this.sourcesContent = out.sourcesContent as SourceMap['sourcesContent'];\n }\n }\n\n toString(): string {\n return JSON.stringify(this);\n }\n}\n","import buildSourceMapTree from './build-source-map-tree';\nimport { traceMappings } from './source-map-tree';\nimport SourceMap from './source-map';\n\nimport type { SourceMapInput, SourceMapLoader, Options } from './types';\nexport type {\n SourceMapSegment,\n EncodedSourceMap,\n EncodedSourceMap as RawSourceMap,\n DecodedSourceMap,\n SourceMapInput,\n SourceMapLoader,\n LoaderContext,\n Options,\n} from './types';\nexport type { SourceMap };\n\n/**\n * Traces through all the mappings in the root sourcemap, through the sources\n * (and their sourcemaps), all the way back to the original source location.\n *\n * `loader` will be called every time we encounter a source file. If it returns\n * a sourcemap, we will recurse into that sourcemap to continue the trace. If\n * it returns a falsey value, that source file is treated as an original,\n * unmodified source file.\n *\n * Pass `excludeContent` to exclude any self-containing source file content\n * from the output sourcemap.\n *\n * Pass `decodedMappings` to receive a SourceMap with decoded (instead of\n * VLQ encoded) mappings.\n */\nexport default function remapping(\n input: SourceMapInput | SourceMapInput[],\n loader: SourceMapLoader,\n options?: boolean | Options\n): SourceMap {\n const opts =\n typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false };\n const tree = buildSourceMapTree(input, loader);\n return new SourceMap(traceMappings(tree), opts);\n}\n"],"names":[],"mappings":";;;AAgCA,MAAM,kBAAkB,mBAAmB,aAAa,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;AACtF,MAAM,aAAa,GAAc,EAAE,CAAC;AAEpC,SAAS,aAAa,CACpB,MAAc,EACd,IAAY,EACZ,MAAc,EACd,IAAY,EACZ,OAAsB,EACtB,MAAe,EAAA;AAEf,IAAA,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;AACzD,CAAC;AAgBD,SAAS,MAAM,CACb,GAAoB,EACpB,OAAkB,EAClB,MAAmB,EACnB,OAAsB,EACtB,MAAe,EAAA;IAEf,OAAO;QACL,GAAG;QACH,OAAO;QACP,MAAM;QACN,OAAO;QACP,MAAM;KACA,CAAC;AACX,CAAC;AAED;;;AAGG;AACa,SAAA,SAAS,CAAC,GAAa,EAAE,OAAkB,EAAA;AACzD,IAAA,OAAO,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;AAC/C,CAAC;AAED;;;AAGG;SACa,cAAc,CAC5B,MAAc,EACd,OAAsB,EACtB,MAAe,EAAA;AAEf,IAAA,OAAO,MAAM,CAAC,IAAI,EAAE,aAAa,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;AAC9D,CAAC;AAED;;;AAGG;AACG,SAAU,aAAa,CAAC,IAAe,EAAA;;;AAG3C,IAAA,MAAM,GAAG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,OAAO,GAAG,GAAG,CAAC,OAAO,CAAC;AAC3B,QAAA,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC;AACrB,QAAA,IAAI,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAiC,CAAC;AACtD,QAAA,IAAI,CAAC,KAAK,GAAG,GAAG,CAAC,KAA2B,CAAC;AAC7C,QAAA,IAAI,CAAC,UAAU,GAAG,GAAG,CAAC,UAAqC,CAAC;AAC5D,QAAA,IAAI,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,CAAC;AAEjC,QAAA,IAAI,CAAC,OAAO,GAAG,GAAG,CAAC,OAA+B,CAAC;AACnD,QAAA,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE;AAC3B,YAAA,IAAI,CAAC,cAAc,GAAG,GAAG,CAAC,cAA6C,CAAC;AACzE,SAAA;KACF;IAED,QAAQ,GAAA;AACN,QAAA,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;KAC7B;AACF;;ACpBD;;;;;;;;;;;;;;AAcG;AACqB,SAAA,SAAS,CAC/B,KAAwC,EACxC,MAAuB,EACvB,OAA2B,EAAA;IAE3B,MAAM,IAAI,GACR,OAAO,OAAO,KAAK,QAAQ,GAAG,OAAO,GAAG,EAAE,cAAc,EAAE,CAAC,CAAC,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,CAAC;IAChG,MAAM,IAAI,GAAG,kBAAkB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC/C,OAAO,IAAI,SAAS,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;AAClD;;;;"} \ No newline at end of file diff --git a/node_modules/@ampproject/remapping/dist/remapping.umd.js b/node_modules/@ampproject/remapping/dist/remapping.umd.js new file mode 100644 index 0000000..6b7b3bb --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.umd.js @@ -0,0 +1,202 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('@jridgewell/trace-mapping'), require('@jridgewell/gen-mapping')) : + typeof define === 'function' && define.amd ? define(['@jridgewell/trace-mapping', '@jridgewell/gen-mapping'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.remapping = factory(global.traceMapping, global.genMapping)); +})(this, (function (traceMapping, genMapping) { 'use strict'; + + const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null, false); + const EMPTY_SOURCES = []; + function SegmentObject(source, line, column, name, content, ignore) { + return { source, line, column, name, content, ignore }; + } + function Source(map, sources, source, content, ignore) { + return { + map, + sources, + source, + content, + ignore, + }; + } + /** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ + function MapSource(map, sources) { + return Source(map, sources, '', null, false); + } + /** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ + function OriginalSource(source, content, ignore) { + return Source(null, EMPTY_SOURCES, source, content, ignore); + } + /** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ + function traceMappings(tree) { + // TODO: Eventually support sourceRoot, which has to be removed because the sources are already + // fully resolved. We'll need to make sources relative to the sourceRoot before adding them. + const gen = new genMapping.GenMapping({ file: tree.map.file }); + const { sources: rootSources, map } = tree; + const rootNames = map.names; + const rootMappings = traceMapping.decodedMappings(map); + for (let i = 0; i < rootMappings.length; i++) { + const segments = rootMappings[i]; + for (let j = 0; j < segments.length; j++) { + const segment = segments[j]; + const genCol = segment[0]; + let traced = SOURCELESS_MAPPING; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length !== 1) { + const source = rootSources[segment[1]]; + traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); + // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a + // respective segment into an original source. + if (traced == null) + continue; + } + const { column, line, name, content, source, ignore } = traced; + genMapping.maybeAddSegment(gen, i, genCol, source, line, column, name); + if (source && content != null) + genMapping.setSourceContent(gen, source, content); + if (ignore) + genMapping.setIgnore(gen, source, true); + } + } + return gen; + } + /** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ + function originalPositionFor(source, line, column, name) { + if (!source.map) { + return SegmentObject(source.source, line, column, name, source.content, source.ignore); + } + const segment = traceMapping.traceSegment(source.map, line, column); + // If we couldn't find a segment, then this doesn't exist in the sourcemap. + if (segment == null) + return null; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length === 1) + return SOURCELESS_MAPPING; + return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name); + } + + function asArray(value) { + if (Array.isArray(value)) + return value; + return [value]; + } + /** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ + function buildSourceMapTree(input, loader) { + const maps = asArray(input).map((m) => new traceMapping.TraceMap(m, '')); + const map = maps.pop(); + for (let i = 0; i < maps.length; i++) { + if (maps[i].sources.length > 1) { + throw new Error(`Transformation map ${i} must have exactly one source file.\n` + + 'Did you specify these with the most recent transformation maps first?'); + } + } + let tree = build(map, loader, '', 0); + for (let i = maps.length - 1; i >= 0; i--) { + tree = MapSource(maps[i], [tree]); + } + return tree; + } + function build(map, loader, importer, importerDepth) { + const { resolvedSources, sourcesContent, ignoreList } = map; + const depth = importerDepth + 1; + const children = resolvedSources.map((sourceFile, i) => { + // The loading context gives the loader more information about why this file is being loaded + // (eg, from which importer). It also allows the loader to override the location of the loaded + // sourcemap/original source, or to override the content in the sourcesContent field if it's + // an unmodified source file. + const ctx = { + importer, + depth, + source: sourceFile || '', + content: undefined, + ignore: undefined, + }; + // Use the provided loader callback to retrieve the file's sourcemap. + // TODO: We should eventually support async loading of sourcemap files. + const sourceMap = loader(ctx.source, ctx); + const { source, content, ignore } = ctx; + // If there is a sourcemap, then we need to recurse into it to load its source files. + if (sourceMap) + return build(new traceMapping.TraceMap(sourceMap, source), loader, source, depth); + // Else, it's an unmodified source file. + // The contents of this unmodified source file can be overridden via the loader context, + // allowing it to be explicitly null or a string. If it remains undefined, we fall back to + // the importing sourcemap's `sourcesContent` field. + const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null; + const ignored = ignore !== undefined ? ignore : ignoreList ? ignoreList.includes(i) : false; + return OriginalSource(source, sourceContent, ignored); + }); + return MapSource(map, children); + } + + /** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ + class SourceMap { + constructor(map, options) { + const out = options.decodedMappings ? genMapping.toDecodedMap(map) : genMapping.toEncodedMap(map); + this.version = out.version; // SourceMap spec says this should be first. + this.file = out.file; + this.mappings = out.mappings; + this.names = out.names; + this.ignoreList = out.ignoreList; + this.sourceRoot = out.sourceRoot; + this.sources = out.sources; + if (!options.excludeContent) { + this.sourcesContent = out.sourcesContent; + } + } + toString() { + return JSON.stringify(this); + } + } + + /** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ + function remapping(input, loader, options) { + const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false }; + const tree = buildSourceMapTree(input, loader); + return new SourceMap(traceMappings(tree), opts); + } + + return remapping; + +})); +//# sourceMappingURL=remapping.umd.js.map diff --git a/node_modules/@ampproject/remapping/dist/remapping.umd.js.map b/node_modules/@ampproject/remapping/dist/remapping.umd.js.map new file mode 100644 index 0000000..d3f0f87 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"remapping.umd.js","sources":["../src/source-map-tree.ts","../src/build-source-map-tree.ts","../src/source-map.ts","../src/remapping.ts"],"sourcesContent":["import { GenMapping, maybeAddSegment, setIgnore, setSourceContent } from '@jridgewell/gen-mapping';\nimport { traceSegment, decodedMappings } from '@jridgewell/trace-mapping';\n\nimport type { TraceMap } from '@jridgewell/trace-mapping';\n\nexport type SourceMapSegmentObject = {\n column: number;\n line: number;\n name: string;\n source: string;\n content: string | null;\n ignore: boolean;\n};\n\nexport type OriginalSource = {\n map: null;\n sources: Sources[];\n source: string;\n content: string | null;\n ignore: boolean;\n};\n\nexport type MapSource = {\n map: TraceMap;\n sources: Sources[];\n source: string;\n content: null;\n ignore: false;\n};\n\nexport type Sources = OriginalSource | MapSource;\n\nconst SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null, false);\nconst EMPTY_SOURCES: Sources[] = [];\n\nfunction SegmentObject(\n source: string,\n line: number,\n column: number,\n name: string,\n content: string | null,\n ignore: boolean\n): SourceMapSegmentObject {\n return { source, line, column, name, content, ignore };\n}\n\nfunction Source(\n map: TraceMap,\n sources: Sources[],\n source: '',\n content: null,\n ignore: false\n): MapSource;\nfunction Source(\n map: null,\n sources: Sources[],\n source: string,\n content: string | null,\n ignore: boolean\n): OriginalSource;\nfunction Source(\n map: TraceMap | null,\n sources: Sources[],\n source: string | '',\n content: string | null,\n ignore: boolean\n): Sources {\n return {\n map,\n sources,\n source,\n content,\n ignore,\n } as any;\n}\n\n/**\n * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes\n * (which may themselves be SourceMapTrees).\n */\nexport function MapSource(map: TraceMap, sources: Sources[]): MapSource {\n return Source(map, sources, '', null, false);\n}\n\n/**\n * A \"leaf\" node in the sourcemap tree, representing an original, unmodified source file. Recursive\n * segment tracing ends at the `OriginalSource`.\n */\nexport function OriginalSource(\n source: string,\n content: string | null,\n ignore: boolean\n): OriginalSource {\n return Source(null, EMPTY_SOURCES, source, content, ignore);\n}\n\n/**\n * traceMappings is only called on the root level SourceMapTree, and begins the process of\n * resolving each mapping in terms of the original source files.\n */\nexport function traceMappings(tree: MapSource): GenMapping {\n // TODO: Eventually support sourceRoot, which has to be removed because the sources are already\n // fully resolved. We'll need to make sources relative to the sourceRoot before adding them.\n const gen = new GenMapping({ file: tree.map.file });\n const { sources: rootSources, map } = tree;\n const rootNames = map.names;\n const rootMappings = decodedMappings(map);\n\n for (let i = 0; i < rootMappings.length; i++) {\n const segments = rootMappings[i];\n\n for (let j = 0; j < segments.length; j++) {\n const segment = segments[j];\n const genCol = segment[0];\n let traced: SourceMapSegmentObject | null = SOURCELESS_MAPPING;\n\n // 1-length segments only move the current generated column, there's no source information\n // to gather from it.\n if (segment.length !== 1) {\n const source = rootSources[segment[1]];\n traced = originalPositionFor(\n source,\n segment[2],\n segment[3],\n segment.length === 5 ? rootNames[segment[4]] : ''\n );\n\n // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a\n // respective segment into an original source.\n if (traced == null) continue;\n }\n\n const { column, line, name, content, source, ignore } = traced;\n\n maybeAddSegment(gen, i, genCol, source, line, column, name);\n if (source && content != null) setSourceContent(gen, source, content);\n if (ignore) setIgnore(gen, source, true);\n }\n }\n\n return gen;\n}\n\n/**\n * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own\n * child SourceMapTrees, until we find the original source map.\n */\nexport function originalPositionFor(\n source: Sources,\n line: number,\n column: number,\n name: string\n): SourceMapSegmentObject | null {\n if (!source.map) {\n return SegmentObject(source.source, line, column, name, source.content, source.ignore);\n }\n\n const segment = traceSegment(source.map, line, column);\n\n // If we couldn't find a segment, then this doesn't exist in the sourcemap.\n if (segment == null) return null;\n // 1-length segments only move the current generated column, there's no source information\n // to gather from it.\n if (segment.length === 1) return SOURCELESS_MAPPING;\n\n return originalPositionFor(\n source.sources[segment[1]],\n segment[2],\n segment[3],\n segment.length === 5 ? source.map.names[segment[4]] : name\n );\n}\n","import { TraceMap } from '@jridgewell/trace-mapping';\n\nimport { OriginalSource, MapSource } from './source-map-tree';\n\nimport type { Sources, MapSource as MapSourceType } from './source-map-tree';\nimport type { SourceMapInput, SourceMapLoader, LoaderContext } from './types';\n\nfunction asArray(value: T | T[]): T[] {\n if (Array.isArray(value)) return value;\n return [value];\n}\n\n/**\n * Recursively builds a tree structure out of sourcemap files, with each node\n * being either an `OriginalSource` \"leaf\" or a `SourceMapTree` composed of\n * `OriginalSource`s and `SourceMapTree`s.\n *\n * Every sourcemap is composed of a collection of source files and mappings\n * into locations of those source files. When we generate a `SourceMapTree` for\n * the sourcemap, we attempt to load each source file's own sourcemap. If it\n * does not have an associated sourcemap, it is considered an original,\n * unmodified source file.\n */\nexport default function buildSourceMapTree(\n input: SourceMapInput | SourceMapInput[],\n loader: SourceMapLoader\n): MapSourceType {\n const maps = asArray(input).map((m) => new TraceMap(m, ''));\n const map = maps.pop()!;\n\n for (let i = 0; i < maps.length; i++) {\n if (maps[i].sources.length > 1) {\n throw new Error(\n `Transformation map ${i} must have exactly one source file.\\n` +\n 'Did you specify these with the most recent transformation maps first?'\n );\n }\n }\n\n let tree = build(map, loader, '', 0);\n for (let i = maps.length - 1; i >= 0; i--) {\n tree = MapSource(maps[i], [tree]);\n }\n return tree;\n}\n\nfunction build(\n map: TraceMap,\n loader: SourceMapLoader,\n importer: string,\n importerDepth: number\n): MapSourceType {\n const { resolvedSources, sourcesContent, ignoreList } = map;\n\n const depth = importerDepth + 1;\n const children = resolvedSources.map((sourceFile: string | null, i: number): Sources => {\n // The loading context gives the loader more information about why this file is being loaded\n // (eg, from which importer). It also allows the loader to override the location of the loaded\n // sourcemap/original source, or to override the content in the sourcesContent field if it's\n // an unmodified source file.\n const ctx: LoaderContext = {\n importer,\n depth,\n source: sourceFile || '',\n content: undefined,\n ignore: undefined,\n };\n\n // Use the provided loader callback to retrieve the file's sourcemap.\n // TODO: We should eventually support async loading of sourcemap files.\n const sourceMap = loader(ctx.source, ctx);\n\n const { source, content, ignore } = ctx;\n\n // If there is a sourcemap, then we need to recurse into it to load its source files.\n if (sourceMap) return build(new TraceMap(sourceMap, source), loader, source, depth);\n\n // Else, it's an unmodified source file.\n // The contents of this unmodified source file can be overridden via the loader context,\n // allowing it to be explicitly null or a string. If it remains undefined, we fall back to\n // the importing sourcemap's `sourcesContent` field.\n const sourceContent =\n content !== undefined ? content : sourcesContent ? sourcesContent[i] : null;\n const ignored = ignore !== undefined ? ignore : ignoreList ? ignoreList.includes(i) : false;\n return OriginalSource(source, sourceContent, ignored);\n });\n\n return MapSource(map, children);\n}\n","import { toDecodedMap, toEncodedMap } from '@jridgewell/gen-mapping';\n\nimport type { GenMapping } from '@jridgewell/gen-mapping';\nimport type { DecodedSourceMap, EncodedSourceMap, Options } from './types';\n\n/**\n * A SourceMap v3 compatible sourcemap, which only includes fields that were\n * provided to it.\n */\nexport default class SourceMap {\n declare file?: string | null;\n declare mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings'];\n declare sourceRoot?: string;\n declare names: string[];\n declare sources: (string | null)[];\n declare sourcesContent?: (string | null)[];\n declare version: 3;\n declare ignoreList: number[] | undefined;\n\n constructor(map: GenMapping, options: Options) {\n const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);\n this.version = out.version; // SourceMap spec says this should be first.\n this.file = out.file;\n this.mappings = out.mappings as SourceMap['mappings'];\n this.names = out.names as SourceMap['names'];\n this.ignoreList = out.ignoreList as SourceMap['ignoreList'];\n this.sourceRoot = out.sourceRoot;\n\n this.sources = out.sources as SourceMap['sources'];\n if (!options.excludeContent) {\n this.sourcesContent = out.sourcesContent as SourceMap['sourcesContent'];\n }\n }\n\n toString(): string {\n return JSON.stringify(this);\n }\n}\n","import buildSourceMapTree from './build-source-map-tree';\nimport { traceMappings } from './source-map-tree';\nimport SourceMap from './source-map';\n\nimport type { SourceMapInput, SourceMapLoader, Options } from './types';\nexport type {\n SourceMapSegment,\n EncodedSourceMap,\n EncodedSourceMap as RawSourceMap,\n DecodedSourceMap,\n SourceMapInput,\n SourceMapLoader,\n LoaderContext,\n Options,\n} from './types';\nexport type { SourceMap };\n\n/**\n * Traces through all the mappings in the root sourcemap, through the sources\n * (and their sourcemaps), all the way back to the original source location.\n *\n * `loader` will be called every time we encounter a source file. If it returns\n * a sourcemap, we will recurse into that sourcemap to continue the trace. If\n * it returns a falsey value, that source file is treated as an original,\n * unmodified source file.\n *\n * Pass `excludeContent` to exclude any self-containing source file content\n * from the output sourcemap.\n *\n * Pass `decodedMappings` to receive a SourceMap with decoded (instead of\n * VLQ encoded) mappings.\n */\nexport default function remapping(\n input: SourceMapInput | SourceMapInput[],\n loader: SourceMapLoader,\n options?: boolean | Options\n): SourceMap {\n const opts =\n typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false };\n const tree = buildSourceMapTree(input, loader);\n return new SourceMap(traceMappings(tree), opts);\n}\n"],"names":["GenMapping","decodedMappings","maybeAddSegment","setSourceContent","setIgnore","traceSegment","TraceMap","toDecodedMap","toEncodedMap"],"mappings":";;;;;;IAgCA,MAAM,kBAAkB,mBAAmB,aAAa,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;IACtF,MAAM,aAAa,GAAc,EAAE,CAAC;IAEpC,SAAS,aAAa,CACpB,MAAc,EACd,IAAY,EACZ,MAAc,EACd,IAAY,EACZ,OAAsB,EACtB,MAAe,EAAA;IAEf,IAAA,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;IACzD,CAAC;IAgBD,SAAS,MAAM,CACb,GAAoB,EACpB,OAAkB,EAClB,MAAmB,EACnB,OAAsB,EACtB,MAAe,EA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xC,MAAuB,EACvB,OAA2B,EAAA;QAE3B,MAAM,IAAI,GACR,OAAO,OAAO,KAAK,QAAQ,GAAG,OAAO,GAAG,EAAE,cAAc,EAAE,CAAC,CAAC,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,CAAC;QAChG,MAAM,IAAI,GAAG,kBAAkB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAC/C,OAAO,IAAI,SAAS,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;IAClD;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts b/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts new file mode 100644 index 0000000..f87fcea --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts @@ -0,0 +1,14 @@ +import type { MapSource as MapSourceType } from './source-map-tree'; +import type { SourceMapInput, SourceMapLoader } from './types'; +/** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ +export default function buildSourceMapTree(input: SourceMapInput | SourceMapInput[], loader: SourceMapLoader): MapSourceType; diff --git a/node_modules/@ampproject/remapping/dist/types/remapping.d.ts b/node_modules/@ampproject/remapping/dist/types/remapping.d.ts new file mode 100644 index 0000000..771fe30 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/remapping.d.ts @@ -0,0 +1,20 @@ +import SourceMap from './source-map'; +import type { SourceMapInput, SourceMapLoader, Options } from './types'; +export type { SourceMapSegment, EncodedSourceMap, EncodedSourceMap as RawSourceMap, DecodedSourceMap, SourceMapInput, SourceMapLoader, LoaderContext, Options, } from './types'; +export type { SourceMap }; +/** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ +export default function remapping(input: SourceMapInput | SourceMapInput[], loader: SourceMapLoader, options?: boolean | Options): SourceMap; diff --git a/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts b/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts new file mode 100644 index 0000000..935bc69 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts @@ -0,0 +1,45 @@ +import { GenMapping } from '@jridgewell/gen-mapping'; +import type { TraceMap } from '@jridgewell/trace-mapping'; +export declare type SourceMapSegmentObject = { + column: number; + line: number; + name: string; + source: string; + content: string | null; + ignore: boolean; +}; +export declare type OriginalSource = { + map: null; + sources: Sources[]; + source: string; + content: string | null; + ignore: boolean; +}; +export declare type MapSource = { + map: TraceMap; + sources: Sources[]; + source: string; + content: null; + ignore: false; +}; +export declare type Sources = OriginalSource | MapSource; +/** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ +export declare function MapSource(map: TraceMap, sources: Sources[]): MapSource; +/** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ +export declare function OriginalSource(source: string, content: string | null, ignore: boolean): OriginalSource; +/** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ +export declare function traceMappings(tree: MapSource): GenMapping; +/** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ +export declare function originalPositionFor(source: Sources, line: number, column: number, name: string): SourceMapSegmentObject | null; diff --git a/node_modules/@ampproject/remapping/dist/types/source-map.d.ts b/node_modules/@ampproject/remapping/dist/types/source-map.d.ts new file mode 100644 index 0000000..cbd7f0a --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/source-map.d.ts @@ -0,0 +1,18 @@ +import type { GenMapping } from '@jridgewell/gen-mapping'; +import type { DecodedSourceMap, EncodedSourceMap, Options } from './types'; +/** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ +export default class SourceMap { + file?: string | null; + mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings']; + sourceRoot?: string; + names: string[]; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; + ignoreList: number[] | undefined; + constructor(map: GenMapping, options: Options); + toString(): string; +} diff --git a/node_modules/@ampproject/remapping/dist/types/types.d.ts b/node_modules/@ampproject/remapping/dist/types/types.d.ts new file mode 100644 index 0000000..4d78c4b --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/types.d.ts @@ -0,0 +1,15 @@ +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +export type { SourceMapSegment, DecodedSourceMap, EncodedSourceMap, } from '@jridgewell/trace-mapping'; +export type { SourceMapInput }; +export declare type LoaderContext = { + readonly importer: string; + readonly depth: number; + source: string; + content: string | null | undefined; + ignore: boolean | undefined; +}; +export declare type SourceMapLoader = (file: string, ctx: LoaderContext) => SourceMapInput | null | undefined | void; +export declare type Options = { + excludeContent?: boolean; + decodedMappings?: boolean; +}; diff --git a/node_modules/@ampproject/remapping/package.json b/node_modules/@ampproject/remapping/package.json new file mode 100644 index 0000000..091224c --- /dev/null +++ b/node_modules/@ampproject/remapping/package.json @@ -0,0 +1,75 @@ +{ + "name": "@ampproject/remapping", + "version": "2.3.0", + "description": "Remap sequential sourcemaps through transformations to point at the original source code", + "keywords": [ + "source", + "map", + "remap" + ], + "main": "dist/remapping.umd.js", + "module": "dist/remapping.mjs", + "types": "dist/types/remapping.d.ts", + "exports": { + ".": [ + { + "types": "./dist/types/remapping.d.ts", + "browser": "./dist/remapping.umd.js", + "require": "./dist/remapping.umd.js", + "import": "./dist/remapping.mjs" + }, + "./dist/remapping.umd.js" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "author": "Justin Ridgewell ", + "repository": { + "type": "git", + "url": "git+https://github.com/ampproject/remapping.git" + }, + "license": "Apache-2.0", + "engines": { + "node": ">=6.0.0" + }, + "scripts": { + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build", + "test": "run-s -n test:lint test:only", + "test:debug": "node --inspect-brk node_modules/.bin/jest --runInBand", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "jest --coverage", + "test:watch": "jest --coverage --watch" + }, + "devDependencies": { + "@rollup/plugin-typescript": "8.3.2", + "@types/jest": "27.4.1", + "@typescript-eslint/eslint-plugin": "5.20.0", + "@typescript-eslint/parser": "5.20.0", + "eslint": "8.14.0", + "eslint-config-prettier": "8.5.0", + "jest": "27.5.1", + "jest-config": "27.5.1", + "npm-run-all": "4.1.5", + "prettier": "2.6.2", + "rollup": "2.70.2", + "ts-jest": "27.1.4", + "tslib": "2.4.0", + "typescript": "4.6.3" + }, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } +} diff --git a/node_modules/@babel/code-frame/LICENSE b/node_modules/@babel/code-frame/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/code-frame/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/code-frame/README.md b/node_modules/@babel/code-frame/README.md new file mode 100644 index 0000000..7160755 --- /dev/null +++ b/node_modules/@babel/code-frame/README.md @@ -0,0 +1,19 @@ +# @babel/code-frame + +> Generate errors that contain a code frame that point to source locations. + +See our website [@babel/code-frame](https://babeljs.io/docs/babel-code-frame) for more information. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/code-frame +``` + +or using yarn: + +```sh +yarn add @babel/code-frame --dev +``` diff --git a/node_modules/@babel/code-frame/lib/index.js b/node_modules/@babel/code-frame/lib/index.js new file mode 100644 index 0000000..53461aa --- /dev/null +++ b/node_modules/@babel/code-frame/lib/index.js @@ -0,0 +1,156 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.codeFrameColumns = codeFrameColumns; +exports.default = _default; +var _highlight = require("@babel/highlight"); +var _picocolors = _interopRequireWildcard(require("picocolors"), true); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +const colors = typeof process === "object" && (process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false") ? (0, _picocolors.createColors)(false) : _picocolors.default; +const compose = (f, g) => v => f(g(v)); +let pcWithForcedColor = undefined; +function getColors(forceColor) { + if (forceColor) { + var _pcWithForcedColor; + (_pcWithForcedColor = pcWithForcedColor) != null ? _pcWithForcedColor : pcWithForcedColor = (0, _picocolors.createColors)(true); + return pcWithForcedColor; + } + return colors; +} +let deprecationWarningShown = false; +function getDefs(colors) { + return { + gutter: colors.gray, + marker: compose(colors.red, colors.bold), + message: compose(colors.red, colors.bold) + }; +} +const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; +function getMarkerLines(loc, source, opts) { + const startLoc = Object.assign({ + column: 0, + line: -1 + }, loc.start); + const endLoc = Object.assign({}, startLoc, loc.end); + const { + linesAbove = 2, + linesBelow = 3 + } = opts || {}; + const startLine = startLoc.line; + const startColumn = startLoc.column; + const endLine = endLoc.line; + const endColumn = endLoc.column; + let start = Math.max(startLine - (linesAbove + 1), 0); + let end = Math.min(source.length, endLine + linesBelow); + if (startLine === -1) { + start = 0; + } + if (endLine === -1) { + end = source.length; + } + const lineDiff = endLine - startLine; + const markerLines = {}; + if (lineDiff) { + for (let i = 0; i <= lineDiff; i++) { + const lineNumber = i + startLine; + if (!startColumn) { + markerLines[lineNumber] = true; + } else if (i === 0) { + const sourceLength = source[lineNumber - 1].length; + markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]; + } else if (i === lineDiff) { + markerLines[lineNumber] = [0, endColumn]; + } else { + const sourceLength = source[lineNumber - i].length; + markerLines[lineNumber] = [0, sourceLength]; + } + } + } else { + if (startColumn === endColumn) { + if (startColumn) { + markerLines[startLine] = [startColumn, 0]; + } else { + markerLines[startLine] = true; + } + } else { + markerLines[startLine] = [startColumn, endColumn - startColumn]; + } + } + return { + start, + end, + markerLines + }; +} +function codeFrameColumns(rawLines, loc, opts = {}) { + const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts); + const colors = getColors(opts.forceColor); + const defs = getDefs(colors); + const maybeHighlight = (fmt, string) => { + return highlighted ? fmt(string) : string; + }; + const lines = rawLines.split(NEWLINE); + const { + start, + end, + markerLines + } = getMarkerLines(loc, lines, opts); + const hasColumns = loc.start && typeof loc.start.column === "number"; + const numberMaxWidth = String(end).length; + const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines; + let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index) => { + const number = start + 1 + index; + const paddedNumber = ` ${number}`.slice(-numberMaxWidth); + const gutter = ` ${paddedNumber} |`; + const hasMarker = markerLines[number]; + const lastMarkerLine = !markerLines[number + 1]; + if (hasMarker) { + let markerLine = ""; + if (Array.isArray(hasMarker)) { + const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); + const numberOfMarkers = hasMarker[1] || 1; + markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), " ", markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join(""); + if (lastMarkerLine && opts.message) { + markerLine += " " + maybeHighlight(defs.message, opts.message); + } + } + return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line.length > 0 ? ` ${line}` : "", markerLine].join(""); + } else { + return ` ${maybeHighlight(defs.gutter, gutter)}${line.length > 0 ? ` ${line}` : ""}`; + } + }).join("\n"); + if (opts.message && !hasColumns) { + frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`; + } + if (highlighted) { + return colors.reset(frame); + } else { + return frame; + } +} +function _default(rawLines, lineNumber, colNumber, opts = {}) { + if (!deprecationWarningShown) { + deprecationWarningShown = true; + const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; + if (process.emitWarning) { + process.emitWarning(message, "DeprecationWarning"); + } else { + const deprecationError = new Error(message); + deprecationError.name = "DeprecationWarning"; + console.warn(new Error(message)); + } + } + colNumber = Math.max(colNumber, 0); + const location = { + start: { + column: colNumber, + line: lineNumber + } + }; + return codeFrameColumns(rawLines, location, opts); +} + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/code-frame/lib/index.js.map b/node_modules/@babel/code-frame/lib/index.js.map new file mode 100644 index 0000000..268f2c5 --- /dev/null +++ b/node_modules/@babel/code-frame/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_highlight","require","_picocolors","_interopRequireWildcard","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","hasOwnProperty","call","i","set","colors","process","env","FORCE_COLOR","createColors","_colors","compose","f","g","v","pcWithForcedColor","undefined","getColors","forceColor","_pcWithForcedColor","deprecationWarningShown","getDefs","gutter","gray","marker","red","bold","message","NEWLINE","getMarkerLines","loc","source","opts","startLoc","assign","column","line","start","endLoc","end","linesAbove","linesBelow","startLine","startColumn","endLine","endColumn","Math","max","min","length","lineDiff","markerLines","lineNumber","sourceLength","codeFrameColumns","rawLines","highlighted","highlightCode","shouldHighlight","defs","maybeHighlight","fmt","string","lines","split","hasColumns","numberMaxWidth","String","highlightedLines","highlight","frame","slice","map","index","number","paddedNumber","hasMarker","lastMarkerLine","markerLine","Array","isArray","markerSpacing","replace","numberOfMarkers","repeat","join","reset","_default","colNumber","emitWarning","deprecationError","Error","name","console","warn","location"],"sources":["../src/index.ts"],"sourcesContent":["import highlight, { shouldHighlight } from \"@babel/highlight\";\n\nimport _colors, { createColors } from \"picocolors\";\nimport type { Colors, Formatter } from \"picocolors/types\";\n// See https://github.com/alexeyraspopov/picocolors/issues/62\nconst colors =\n typeof process === \"object\" &&\n (process.env.FORCE_COLOR === \"0\" || process.env.FORCE_COLOR === \"false\")\n ? createColors(false)\n : _colors;\n\nconst compose: (f: (gv: U) => V, g: (v: T) => U) => (v: T) => V =\n (f, g) => v =>\n f(g(v));\n\nlet pcWithForcedColor: Colors = undefined;\nfunction getColors(forceColor: boolean) {\n if (forceColor) {\n pcWithForcedColor ??= createColors(true);\n return pcWithForcedColor;\n }\n return colors;\n}\n\nlet deprecationWarningShown = false;\n\ntype Location = {\n column: number;\n line: number;\n};\n\ntype NodeLocation = {\n end?: Location;\n start: Location;\n};\n\nexport interface Options {\n /** Syntax highlight the code as JavaScript for terminals. default: false */\n highlightCode?: boolean;\n /** The number of lines to show above the error. default: 2 */\n linesAbove?: number;\n /** The number of lines to show below the error. default: 3 */\n linesBelow?: number;\n /**\n * Forcibly syntax highlight the code as JavaScript (for non-terminals);\n * overrides highlightCode.\n * default: false\n */\n forceColor?: boolean;\n /**\n * Pass in a string to be displayed inline (if possible) next to the\n * highlighted location in the code. If it can't be positioned inline,\n * it will be placed above the code frame.\n * default: nothing\n */\n message?: string;\n}\n\n/**\n * Styles for code frame token types.\n */\nfunction getDefs(colors: Colors) {\n return {\n gutter: colors.gray,\n marker: compose(colors.red, colors.bold),\n message: compose(colors.red, colors.bold),\n };\n}\n\n/**\n * RegExp to test for newlines in terminal.\n */\n\nconst NEWLINE = /\\r\\n|[\\n\\r\\u2028\\u2029]/;\n\n/**\n * Extract what lines should be marked and highlighted.\n */\n\ntype MarkerLines = Record;\n\nfunction getMarkerLines(\n loc: NodeLocation,\n source: Array,\n opts: Options,\n): {\n start: number;\n end: number;\n markerLines: MarkerLines;\n} {\n const startLoc: Location = {\n column: 0,\n line: -1,\n ...loc.start,\n };\n const endLoc: Location = {\n ...startLoc,\n ...loc.end,\n };\n const { linesAbove = 2, linesBelow = 3 } = opts || {};\n const startLine = startLoc.line;\n const startColumn = startLoc.column;\n const endLine = endLoc.line;\n const endColumn = endLoc.column;\n\n let start = Math.max(startLine - (linesAbove + 1), 0);\n let end = Math.min(source.length, endLine + linesBelow);\n\n if (startLine === -1) {\n start = 0;\n }\n\n if (endLine === -1) {\n end = source.length;\n }\n\n const lineDiff = endLine - startLine;\n const markerLines: MarkerLines = {};\n\n if (lineDiff) {\n for (let i = 0; i <= lineDiff; i++) {\n const lineNumber = i + startLine;\n\n if (!startColumn) {\n markerLines[lineNumber] = true;\n } else if (i === 0) {\n const sourceLength = source[lineNumber - 1].length;\n\n markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];\n } else if (i === lineDiff) {\n markerLines[lineNumber] = [0, endColumn];\n } else {\n const sourceLength = source[lineNumber - i].length;\n\n markerLines[lineNumber] = [0, sourceLength];\n }\n }\n } else {\n if (startColumn === endColumn) {\n if (startColumn) {\n markerLines[startLine] = [startColumn, 0];\n } else {\n markerLines[startLine] = true;\n }\n } else {\n markerLines[startLine] = [startColumn, endColumn - startColumn];\n }\n }\n\n return { start, end, markerLines };\n}\n\nexport function codeFrameColumns(\n rawLines: string,\n loc: NodeLocation,\n opts: Options = {},\n): string {\n const highlighted =\n (opts.highlightCode || opts.forceColor) && shouldHighlight(opts);\n const colors = getColors(opts.forceColor);\n const defs = getDefs(colors);\n const maybeHighlight = (fmt: Formatter, string: string) => {\n return highlighted ? fmt(string) : string;\n };\n const lines = rawLines.split(NEWLINE);\n const { start, end, markerLines } = getMarkerLines(loc, lines, opts);\n const hasColumns = loc.start && typeof loc.start.column === \"number\";\n\n const numberMaxWidth = String(end).length;\n\n const highlightedLines = highlighted ? highlight(rawLines, opts) : rawLines;\n\n let frame = highlightedLines\n .split(NEWLINE, end)\n .slice(start, end)\n .map((line, index) => {\n const number = start + 1 + index;\n const paddedNumber = ` ${number}`.slice(-numberMaxWidth);\n const gutter = ` ${paddedNumber} |`;\n const hasMarker = markerLines[number];\n const lastMarkerLine = !markerLines[number + 1];\n if (hasMarker) {\n let markerLine = \"\";\n if (Array.isArray(hasMarker)) {\n const markerSpacing = line\n .slice(0, Math.max(hasMarker[0] - 1, 0))\n .replace(/[^\\t]/g, \" \");\n const numberOfMarkers = hasMarker[1] || 1;\n\n markerLine = [\n \"\\n \",\n maybeHighlight(defs.gutter, gutter.replace(/\\d/g, \" \")),\n \" \",\n markerSpacing,\n maybeHighlight(defs.marker, \"^\").repeat(numberOfMarkers),\n ].join(\"\");\n\n if (lastMarkerLine && opts.message) {\n markerLine += \" \" + maybeHighlight(defs.message, opts.message);\n }\n }\n return [\n maybeHighlight(defs.marker, \">\"),\n maybeHighlight(defs.gutter, gutter),\n line.length > 0 ? ` ${line}` : \"\",\n markerLine,\n ].join(\"\");\n } else {\n return ` ${maybeHighlight(defs.gutter, gutter)}${\n line.length > 0 ? ` ${line}` : \"\"\n }`;\n }\n })\n .join(\"\\n\");\n\n if (opts.message && !hasColumns) {\n frame = `${\" \".repeat(numberMaxWidth + 1)}${opts.message}\\n${frame}`;\n }\n\n if (highlighted) {\n return colors.reset(frame);\n } else {\n return frame;\n }\n}\n\n/**\n * Create a code frame, adding line numbers, code highlighting, and pointing to a given position.\n */\n\nexport default function (\n rawLines: string,\n lineNumber: number,\n colNumber?: number | null,\n opts: Options = {},\n): string {\n if (!deprecationWarningShown) {\n deprecationWarningShown = true;\n\n const message =\n \"Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.\";\n\n if (process.emitWarning) {\n // A string is directly supplied to emitWarning, because when supplying an\n // Error object node throws in the tests because of different contexts\n process.emitWarning(message, \"DeprecationWarning\");\n } else {\n const deprecationError = new Error(message);\n deprecationError.name = \"DeprecationWarning\";\n console.warn(new Error(message));\n }\n }\n\n colNumber = Math.max(colNumber, 0);\n\n const location: NodeLocation = {\n start: { column: colNumber, line: lineNumber },\n };\n\n return codeFrameColumns(rawLines, location, opts);\n}\n"],"mappings":";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IAAa,GAAG,CAAC,CAAC,EACV;EACR,IAAI,CAACZ,uBAAuB,EAAE;IAC5BA,uBAAuB,GAAG,IAAI;IAE9B,MAAMO,OAAO,GACX,qGAAqG;IAEvG,IAAIrB,OAAO,CAACmF,WAAW,EAAE;MAGvBnF,OAAO,CAACmF,WAAW,CAAC9D,OAAO,EAAE,oBAAoB,CAAC;IACpD,CAAC,MAAM;MACL,MAAM+D,gBAAgB,GAAG,IAAIC,KAAK,CAAChE,OAAO,CAAC;MAC3C+D,gBAAgB,CAACE,IAAI,GAAG,oBAAoB;MAC5CC,OAAO,CAACC,IAAI,CAAC,IAAIH,KAAK,CAAChE,OAAO,CAAC,CAAC;IAClC;EACF;EAEA6D,SAAS,GAAG1C,IAAI,CAACC,GAAG,CAACyC,SAAS,EAAE,CAAC,CAAC;EAElC,MAAMO,QAAsB,GAAG;IAC7B1D,KAAK,EAAE;MAAEF,MAAM,EAAEqD,SAAS;MAAEpD,IAAI,EAAEgB;IAAW;EAC/C,CAAC;EAED,OAAOE,gBAAgB,CAACC,QAAQ,EAAEwC,QAAQ,EAAE/D,IAAI,CAAC;AACnD","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/code-frame/package.json b/node_modules/@babel/code-frame/package.json new file mode 100644 index 0000000..9e672b7 --- /dev/null +++ b/node_modules/@babel/code-frame/package.json @@ -0,0 +1,30 @@ +{ + "name": "@babel/code-frame", + "version": "7.24.7", + "description": "Generate errors that contain a code frame that point to source locations.", + "author": "The Babel Team (https://babel.dev/team)", + "homepage": "https://babel.dev/docs/en/next/babel-code-frame", + "bugs": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen", + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "https://github.com/babel/babel.git", + "directory": "packages/babel-code-frame" + }, + "main": "./lib/index.js", + "dependencies": { + "@babel/highlight": "^7.24.7", + "picocolors": "^1.0.0" + }, + "devDependencies": { + "import-meta-resolve": "^4.1.0", + "strip-ansi": "^4.0.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "type": "commonjs" +} \ No newline at end of file diff --git a/node_modules/@babel/compat-data/LICENSE b/node_modules/@babel/compat-data/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/compat-data/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/compat-data/README.md b/node_modules/@babel/compat-data/README.md new file mode 100644 index 0000000..381f3de --- /dev/null +++ b/node_modules/@babel/compat-data/README.md @@ -0,0 +1,19 @@ +# @babel/compat-data + +> + +See our website [@babel/compat-data](https://babeljs.io/docs/babel-compat-data) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/compat-data +``` + +or using yarn: + +```sh +yarn add @babel/compat-data +``` diff --git a/node_modules/@babel/compat-data/corejs2-built-ins.js b/node_modules/@babel/compat-data/corejs2-built-ins.js new file mode 100644 index 0000000..ed19e0b --- /dev/null +++ b/node_modules/@babel/compat-data/corejs2-built-ins.js @@ -0,0 +1,2 @@ +// Todo (Babel 8): remove this file as Babel 8 drop support of core-js 2 +module.exports = require("./data/corejs2-built-ins.json"); diff --git a/node_modules/@babel/compat-data/corejs3-shipped-proposals.js b/node_modules/@babel/compat-data/corejs3-shipped-proposals.js new file mode 100644 index 0000000..7909b8c --- /dev/null +++ b/node_modules/@babel/compat-data/corejs3-shipped-proposals.js @@ -0,0 +1,2 @@ +// Todo (Babel 8): remove this file now that it is included in babel-plugin-polyfill-corejs3 +module.exports = require("./data/corejs3-shipped-proposals.json"); diff --git a/node_modules/@babel/compat-data/data/corejs2-built-ins.json b/node_modules/@babel/compat-data/data/corejs2-built-ins.json new file mode 100644 index 0000000..5fe8ca8 --- /dev/null +++ b/node_modules/@babel/compat-data/data/corejs2-built-ins.json @@ -0,0 +1,2090 @@ +{ + "es6.array.copy-within": { + "chrome": "45", + "opera": "32", + "edge": "12", + "firefox": "32", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "5", + "rhino": "1.7.13", + "opera_mobile": "32", + "electron": "0.31" + }, + "es6.array.every": { + "chrome": "5", + "opera": "10.10", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.4", + "deno": "1", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "10.1", + "electron": "0.20" + }, + "es6.array.fill": { + "chrome": "45", + "opera": "32", + "edge": "12", + "firefox": "31", + "safari": "7.1", + "node": "4", + "deno": "1", + "ios": "8", + "samsung": "5", + "rhino": "1.7.13", + "opera_mobile": "32", + "electron": "0.31" + }, + "es6.array.filter": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "es6.array.find": { + "chrome": "45", + "opera": "32", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "4", + "deno": "1", + "ios": "8", + "samsung": "5", + "rhino": "1.7.13", + "opera_mobile": "32", + "electron": "0.31" + }, + "es6.array.find-index": { + "chrome": "45", + "opera": "32", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "4", + "deno": "1", + "ios": "8", + "samsung": "5", + "rhino": "1.7.13", + "opera_mobile": "32", + "electron": "0.31" + }, + "es7.array.flat-map": { + "chrome": "69", + "opera": "56", + "edge": "79", + "firefox": "62", + "safari": "12", + "node": "11", + "deno": "1", + "ios": "12", + "samsung": "10", + "rhino": "1.7.15", + "opera_mobile": "48", + "electron": "4.0" + }, + "es6.array.for-each": { + "chrome": "5", + "opera": "10.10", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.4", + "deno": "1", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "10.1", + "electron": "0.20" + }, + "es6.array.from": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "36", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "rhino": "1.7.15", + "opera_mobile": "41", + "electron": "1.2" + }, + "es7.array.includes": { + "chrome": "47", + "opera": "34", + "edge": "14", + "firefox": "102", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "34", + "electron": "0.36" + }, + "es6.array.index-of": { + "chrome": "5", + "opera": "10.10", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.4", + "deno": "1", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "10.1", + "electron": "0.20" + }, + "es6.array.is-array": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "4", + "safari": "4", + "node": "0.4", + "deno": "1", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "10.1", + "electron": "0.20" + }, + "es6.array.iterator": { + "chrome": "66", + "opera": "53", + "edge": "12", + "firefox": "60", + "safari": "9", + "node": "10", + "deno": "1", + "ios": "9", + "samsung": "9", + "rhino": "1.7.13", + "opera_mobile": "47", + "electron": "3.0" + }, + "es6.array.last-index-of": { + "chrome": "5", + "opera": "10.10", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.4", + "deno": "1", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "10.1", + "electron": "0.20" + }, + "es6.array.map": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "es6.array.of": { + "chrome": "45", + "opera": "32", + "edge": "12", + "firefox": "25", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "5", + "rhino": "1.7.13", + "opera_mobile": "32", + "electron": "0.31" + }, + "es6.array.reduce": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "3", + "safari": "4", + "node": "0.4", + "deno": "1", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "10.1", + "electron": "0.20" + }, + "es6.array.reduce-right": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "3", + "safari": "4", + "node": "0.4", + "deno": "1", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "10.1", + "electron": "0.20" + }, + "es6.array.slice": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "es6.array.some": { + "chrome": "5", + "opera": "10.10", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.4", + "deno": "1", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "10.1", + "electron": "0.20" + }, + "es6.array.sort": { + "chrome": "63", + "opera": "50", + "edge": "12", + "firefox": "5", + "safari": "12", + "node": "10", + "deno": "1", + "ie": "9", + "ios": "12", + "samsung": "8", + "rhino": "1.7.13", + "opera_mobile": "46", + "electron": "3.0" + }, + "es6.array.species": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "rhino": "1.7.15", + "opera_mobile": "41", + "electron": "1.2" + }, + "es6.date.now": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "2", + "safari": "4", + "node": "0.4", + "deno": "1", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "10.1", + "electron": "0.20" + }, + "es6.date.to-iso-string": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "3.5", + "safari": "4", + "node": "0.4", + "deno": "1", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "10.1", + "electron": "0.20" + }, + "es6.date.to-json": { + "chrome": "5", + "opera": "12.10", + "edge": "12", + "firefox": "4", + "safari": "10", + "node": "0.4", + "deno": "1", + "ie": "9", + "android": "4", + "ios": "10", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "12.1", + "electron": "0.20" + }, + "es6.date.to-primitive": { + "chrome": "47", + "opera": "34", + "edge": "15", + "firefox": "44", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "34", + "electron": "0.36" + }, + "es6.date.to-string": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.4", + "deno": "1", + "ie": "10", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "10.1", + "electron": "0.20" + }, + "es6.function.bind": { + "chrome": "7", + "opera": "12", + "edge": "12", + "firefox": "4", + "safari": "5.1", + "node": "0.4", + "deno": "1", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "12", + "electron": "0.20" + }, + "es6.function.has-instance": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "50", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "es6.function.name": { + "chrome": "5", + "opera": "10.50", + "edge": "14", + "firefox": "2", + "safari": "4", + "node": "0.4", + "deno": "1", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "10.1", + "electron": "0.20" + }, + "es6.map": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "53", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "es6.math.acosh": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "deno": "1", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "opera_mobile": "25", + "electron": "0.20" + }, + "es6.math.asinh": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "deno": "1", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "opera_mobile": "25", + "electron": "0.20" + }, + "es6.math.atanh": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "deno": "1", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "opera_mobile": "25", + "electron": "0.20" + }, + "es6.math.cbrt": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "deno": "1", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "opera_mobile": "25", + "electron": "0.20" + }, + "es6.math.clz32": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "31", + "safari": "9", + "node": "0.12", + "deno": "1", + "ios": "9", + "samsung": "3", + "rhino": "1.7.13", + "opera_mobile": "25", + "electron": "0.20" + }, + "es6.math.cosh": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "deno": "1", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "opera_mobile": "25", + "electron": "0.20" + }, + "es6.math.expm1": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "deno": "1", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "opera_mobile": "25", + "electron": "0.20" + }, + "es6.math.fround": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "26", + "safari": "7.1", + "node": "0.12", + "deno": "1", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "opera_mobile": "25", + "electron": "0.20" + }, + "es6.math.hypot": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "27", + "safari": "7.1", + "node": "0.12", + "deno": "1", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "opera_mobile": "25", + "electron": "0.20" + }, + "es6.math.imul": { + "chrome": "30", + "opera": "17", + "edge": "12", + "firefox": "23", + "safari": "7", + "node": "0.12", + "deno": "1", + "android": "4.4", + "ios": "7", + "samsung": "2", + "rhino": "1.7.13", + "opera_mobile": "18", + "electron": "0.20" + }, + "es6.math.log1p": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "deno": "1", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "opera_mobile": "25", + "electron": "0.20" + }, + "es6.math.log10": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "deno": "1", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "opera_mobile": "25", + "electron": "0.20" + }, + "es6.math.log2": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "deno": "1", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "opera_mobile": "25", + "electron": "0.20" + }, + "es6.math.sign": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "9", + "node": "0.12", + "deno": "1", + "ios": "9", + "samsung": "3", + "rhino": "1.7.13", + "opera_mobile": "25", + "electron": "0.20" + }, + "es6.math.sinh": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "deno": "1", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "opera_mobile": "25", + "electron": "0.20" + }, + "es6.math.tanh": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "deno": "1", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "opera_mobile": "25", + "electron": "0.20" + }, + "es6.math.trunc": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "deno": "1", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "opera_mobile": "25", + "electron": "0.20" + }, + "es6.number.constructor": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "36", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "opera_mobile": "28", + "electron": "0.21" + }, + "es6.number.epsilon": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "25", + "safari": "9", + "node": "0.12", + "deno": "1", + "ios": "9", + "samsung": "2", + "rhino": "1.7.14", + "opera_mobile": "21", + "electron": "0.20" + }, + "es6.number.is-finite": { + "chrome": "19", + "opera": "15", + "edge": "12", + "firefox": "16", + "safari": "9", + "node": "0.8", + "deno": "1", + "android": "4.1", + "ios": "9", + "samsung": "1.5", + "rhino": "1.7.13", + "opera_mobile": "14", + "electron": "0.20" + }, + "es6.number.is-integer": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "16", + "safari": "9", + "node": "0.12", + "deno": "1", + "ios": "9", + "samsung": "2", + "rhino": "1.7.13", + "opera_mobile": "21", + "electron": "0.20" + }, + "es6.number.is-nan": { + "chrome": "19", + "opera": "15", + "edge": "12", + "firefox": "15", + "safari": "9", + "node": "0.8", + "deno": "1", + "android": "4.1", + "ios": "9", + "samsung": "1.5", + "rhino": "1.7.13", + "opera_mobile": "14", + "electron": "0.20" + }, + "es6.number.is-safe-integer": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "32", + "safari": "9", + "node": "0.12", + "deno": "1", + "ios": "9", + "samsung": "2", + "rhino": "1.7.13", + "opera_mobile": "21", + "electron": "0.20" + }, + "es6.number.max-safe-integer": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "31", + "safari": "9", + "node": "0.12", + "deno": "1", + "ios": "9", + "samsung": "2", + "rhino": "1.7.13", + "opera_mobile": "21", + "electron": "0.20" + }, + "es6.number.min-safe-integer": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "31", + "safari": "9", + "node": "0.12", + "deno": "1", + "ios": "9", + "samsung": "2", + "rhino": "1.7.13", + "opera_mobile": "21", + "electron": "0.20" + }, + "es6.number.parse-float": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "25", + "safari": "9", + "node": "0.12", + "deno": "1", + "ios": "9", + "samsung": "2", + "rhino": "1.7.14", + "opera_mobile": "21", + "electron": "0.20" + }, + "es6.number.parse-int": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "25", + "safari": "9", + "node": "0.12", + "deno": "1", + "ios": "9", + "samsung": "2", + "rhino": "1.7.14", + "opera_mobile": "21", + "electron": "0.20" + }, + "es6.object.assign": { + "chrome": "49", + "opera": "36", + "edge": "13", + "firefox": "36", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "36", + "electron": "0.37" + }, + "es6.object.create": { + "chrome": "5", + "opera": "12", + "edge": "12", + "firefox": "4", + "safari": "4", + "node": "0.4", + "deno": "1", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "12", + "electron": "0.20" + }, + "es7.object.define-getter": { + "chrome": "62", + "opera": "49", + "edge": "16", + "firefox": "48", + "safari": "9", + "node": "8.10", + "deno": "1", + "ios": "9", + "samsung": "8", + "opera_mobile": "46", + "electron": "3.0" + }, + "es7.object.define-setter": { + "chrome": "62", + "opera": "49", + "edge": "16", + "firefox": "48", + "safari": "9", + "node": "8.10", + "deno": "1", + "ios": "9", + "samsung": "8", + "opera_mobile": "46", + "electron": "3.0" + }, + "es6.object.define-property": { + "chrome": "5", + "opera": "12", + "edge": "12", + "firefox": "4", + "safari": "5.1", + "node": "0.4", + "deno": "1", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "12", + "electron": "0.20" + }, + "es6.object.define-properties": { + "chrome": "5", + "opera": "12", + "edge": "12", + "firefox": "4", + "safari": "4", + "node": "0.4", + "deno": "1", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "12", + "electron": "0.20" + }, + "es7.object.entries": { + "chrome": "54", + "opera": "41", + "edge": "14", + "firefox": "47", + "safari": "10.1", + "node": "7", + "deno": "1", + "ios": "10.3", + "samsung": "6", + "rhino": "1.7.14", + "opera_mobile": "41", + "electron": "1.4" + }, + "es6.object.freeze": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "opera_mobile": "32", + "electron": "0.30" + }, + "es6.object.get-own-property-descriptor": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "opera_mobile": "32", + "electron": "0.30" + }, + "es7.object.get-own-property-descriptors": { + "chrome": "54", + "opera": "41", + "edge": "15", + "firefox": "50", + "safari": "10.1", + "node": "7", + "deno": "1", + "ios": "10.3", + "samsung": "6", + "opera_mobile": "41", + "electron": "1.4" + }, + "es6.object.get-own-property-names": { + "chrome": "40", + "opera": "27", + "edge": "12", + "firefox": "33", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "opera_mobile": "27", + "electron": "0.21" + }, + "es6.object.get-prototype-of": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "opera_mobile": "32", + "electron": "0.30" + }, + "es7.object.lookup-getter": { + "chrome": "62", + "opera": "49", + "edge": "79", + "firefox": "36", + "safari": "9", + "node": "8.10", + "deno": "1", + "ios": "9", + "samsung": "8", + "opera_mobile": "46", + "electron": "3.0" + }, + "es7.object.lookup-setter": { + "chrome": "62", + "opera": "49", + "edge": "79", + "firefox": "36", + "safari": "9", + "node": "8.10", + "deno": "1", + "ios": "9", + "samsung": "8", + "opera_mobile": "46", + "electron": "3.0" + }, + "es6.object.prevent-extensions": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "opera_mobile": "32", + "electron": "0.30" + }, + "es6.object.to-string": { + "chrome": "57", + "opera": "44", + "edge": "15", + "firefox": "51", + "safari": "10", + "node": "8", + "deno": "1", + "ios": "10", + "samsung": "7", + "opera_mobile": "43", + "electron": "1.7" + }, + "es6.object.is": { + "chrome": "19", + "opera": "15", + "edge": "12", + "firefox": "22", + "safari": "9", + "node": "0.8", + "deno": "1", + "android": "4.1", + "ios": "9", + "samsung": "1.5", + "rhino": "1.7.13", + "opera_mobile": "14", + "electron": "0.20" + }, + "es6.object.is-frozen": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "opera_mobile": "32", + "electron": "0.30" + }, + "es6.object.is-sealed": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "opera_mobile": "32", + "electron": "0.30" + }, + "es6.object.is-extensible": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "opera_mobile": "32", + "electron": "0.30" + }, + "es6.object.keys": { + "chrome": "40", + "opera": "27", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "opera_mobile": "27", + "electron": "0.21" + }, + "es6.object.seal": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "opera_mobile": "32", + "electron": "0.30" + }, + "es6.object.set-prototype-of": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "31", + "safari": "9", + "node": "0.12", + "deno": "1", + "ie": "11", + "ios": "9", + "samsung": "2", + "rhino": "1.7.13", + "opera_mobile": "21", + "electron": "0.20" + }, + "es7.object.values": { + "chrome": "54", + "opera": "41", + "edge": "14", + "firefox": "47", + "safari": "10.1", + "node": "7", + "deno": "1", + "ios": "10.3", + "samsung": "6", + "rhino": "1.7.14", + "opera_mobile": "41", + "electron": "1.4" + }, + "es6.promise": { + "chrome": "51", + "opera": "38", + "edge": "14", + "firefox": "45", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "rhino": "1.7.15", + "opera_mobile": "41", + "electron": "1.2" + }, + "es7.promise.finally": { + "chrome": "63", + "opera": "50", + "edge": "18", + "firefox": "58", + "safari": "11.1", + "node": "10", + "deno": "1", + "ios": "11.3", + "samsung": "8", + "rhino": "1.7.15", + "opera_mobile": "46", + "electron": "3.0" + }, + "es6.reflect.apply": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "36", + "electron": "0.37" + }, + "es6.reflect.construct": { + "chrome": "49", + "opera": "36", + "edge": "13", + "firefox": "49", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "36", + "electron": "0.37" + }, + "es6.reflect.define-property": { + "chrome": "49", + "opera": "36", + "edge": "13", + "firefox": "42", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "36", + "electron": "0.37" + }, + "es6.reflect.delete-property": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "36", + "electron": "0.37" + }, + "es6.reflect.get": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "36", + "electron": "0.37" + }, + "es6.reflect.get-own-property-descriptor": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "36", + "electron": "0.37" + }, + "es6.reflect.get-prototype-of": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "36", + "electron": "0.37" + }, + "es6.reflect.has": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "36", + "electron": "0.37" + }, + "es6.reflect.is-extensible": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "36", + "electron": "0.37" + }, + "es6.reflect.own-keys": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "36", + "electron": "0.37" + }, + "es6.reflect.prevent-extensions": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "36", + "electron": "0.37" + }, + "es6.reflect.set": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "36", + "electron": "0.37" + }, + "es6.reflect.set-prototype-of": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "36", + "electron": "0.37" + }, + "es6.regexp.constructor": { + "chrome": "50", + "opera": "37", + "edge": "79", + "firefox": "40", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "37", + "electron": "1.1" + }, + "es6.regexp.flags": { + "chrome": "49", + "opera": "36", + "edge": "79", + "firefox": "37", + "safari": "9", + "node": "6", + "deno": "1", + "ios": "9", + "samsung": "5", + "rhino": "1.7.15", + "opera_mobile": "36", + "electron": "0.37" + }, + "es6.regexp.match": { + "chrome": "50", + "opera": "37", + "edge": "79", + "firefox": "49", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "rhino": "1.7.13", + "opera_mobile": "37", + "electron": "1.1" + }, + "es6.regexp.replace": { + "chrome": "50", + "opera": "37", + "edge": "79", + "firefox": "49", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "37", + "electron": "1.1" + }, + "es6.regexp.split": { + "chrome": "50", + "opera": "37", + "edge": "79", + "firefox": "49", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "37", + "electron": "1.1" + }, + "es6.regexp.search": { + "chrome": "50", + "opera": "37", + "edge": "79", + "firefox": "49", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "rhino": "1.7.13", + "opera_mobile": "37", + "electron": "1.1" + }, + "es6.regexp.to-string": { + "chrome": "50", + "opera": "37", + "edge": "79", + "firefox": "39", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "rhino": "1.7.15", + "opera_mobile": "37", + "electron": "1.1" + }, + "es6.set": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "53", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "es6.symbol": { + "chrome": "51", + "opera": "38", + "edge": "79", + "firefox": "51", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "es7.symbol.async-iterator": { + "chrome": "63", + "opera": "50", + "edge": "79", + "firefox": "57", + "safari": "12", + "node": "10", + "deno": "1", + "ios": "12", + "samsung": "8", + "opera_mobile": "46", + "electron": "3.0" + }, + "es6.string.anchor": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "deno": "1", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "opera_mobile": "14", + "electron": "0.20" + }, + "es6.string.big": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "deno": "1", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "opera_mobile": "14", + "electron": "0.20" + }, + "es6.string.blink": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "deno": "1", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "opera_mobile": "14", + "electron": "0.20" + }, + "es6.string.bold": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "deno": "1", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "opera_mobile": "14", + "electron": "0.20" + }, + "es6.string.code-point-at": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "29", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "opera_mobile": "28", + "electron": "0.21" + }, + "es6.string.ends-with": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "29", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "opera_mobile": "28", + "electron": "0.21" + }, + "es6.string.fixed": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "deno": "1", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "opera_mobile": "14", + "electron": "0.20" + }, + "es6.string.fontcolor": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "deno": "1", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "opera_mobile": "14", + "electron": "0.20" + }, + "es6.string.fontsize": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "deno": "1", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "opera_mobile": "14", + "electron": "0.20" + }, + "es6.string.from-code-point": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "29", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "opera_mobile": "28", + "electron": "0.21" + }, + "es6.string.includes": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "40", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "opera_mobile": "28", + "electron": "0.21" + }, + "es6.string.italics": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "deno": "1", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "opera_mobile": "14", + "electron": "0.20" + }, + "es6.string.iterator": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "36", + "safari": "9", + "node": "0.12", + "deno": "1", + "ios": "9", + "samsung": "3", + "rhino": "1.7.13", + "opera_mobile": "25", + "electron": "0.20" + }, + "es6.string.link": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "deno": "1", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "opera_mobile": "14", + "electron": "0.20" + }, + "es7.string.pad-start": { + "chrome": "57", + "opera": "44", + "edge": "15", + "firefox": "48", + "safari": "10", + "node": "8", + "deno": "1", + "ios": "10", + "samsung": "7", + "rhino": "1.7.13", + "opera_mobile": "43", + "electron": "1.7" + }, + "es7.string.pad-end": { + "chrome": "57", + "opera": "44", + "edge": "15", + "firefox": "48", + "safari": "10", + "node": "8", + "deno": "1", + "ios": "10", + "samsung": "7", + "rhino": "1.7.13", + "opera_mobile": "43", + "electron": "1.7" + }, + "es6.string.raw": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "34", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.14", + "opera_mobile": "28", + "electron": "0.21" + }, + "es6.string.repeat": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "24", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "opera_mobile": "28", + "electron": "0.21" + }, + "es6.string.small": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "deno": "1", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "opera_mobile": "14", + "electron": "0.20" + }, + "es6.string.starts-with": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "29", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "opera_mobile": "28", + "electron": "0.21" + }, + "es6.string.strike": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "deno": "1", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "opera_mobile": "14", + "electron": "0.20" + }, + "es6.string.sub": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "deno": "1", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "opera_mobile": "14", + "electron": "0.20" + }, + "es6.string.sup": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "deno": "1", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "opera_mobile": "14", + "electron": "0.20" + }, + "es6.string.trim": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "3.5", + "safari": "4", + "node": "0.4", + "deno": "1", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "10.1", + "electron": "0.20" + }, + "es7.string.trim-left": { + "chrome": "66", + "opera": "53", + "edge": "79", + "firefox": "61", + "safari": "12", + "node": "10", + "deno": "1", + "ios": "12", + "samsung": "9", + "rhino": "1.7.13", + "opera_mobile": "47", + "electron": "3.0" + }, + "es7.string.trim-right": { + "chrome": "66", + "opera": "53", + "edge": "79", + "firefox": "61", + "safari": "12", + "node": "10", + "deno": "1", + "ios": "12", + "samsung": "9", + "rhino": "1.7.13", + "opera_mobile": "47", + "electron": "3.0" + }, + "es6.typed.array-buffer": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "es6.typed.data-view": { + "chrome": "5", + "opera": "12", + "edge": "12", + "firefox": "15", + "safari": "5.1", + "node": "0.4", + "deno": "1", + "ie": "10", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "12", + "electron": "0.20" + }, + "es6.typed.int8-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "es6.typed.uint8-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "es6.typed.uint8-clamped-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "es6.typed.int16-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "es6.typed.uint16-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "es6.typed.int32-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "es6.typed.uint32-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "es6.typed.float32-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "es6.typed.float64-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "es6.weak-map": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "53", + "safari": "9", + "node": "6.5", + "deno": "1", + "ios": "9", + "samsung": "5", + "rhino": "1.7.15", + "opera_mobile": "41", + "electron": "1.2" + }, + "es6.weak-set": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "53", + "safari": "9", + "node": "6.5", + "deno": "1", + "ios": "9", + "samsung": "5", + "rhino": "1.7.15", + "opera_mobile": "41", + "electron": "1.2" + } +} diff --git a/node_modules/@babel/compat-data/data/corejs3-shipped-proposals.json b/node_modules/@babel/compat-data/data/corejs3-shipped-proposals.json new file mode 100644 index 0000000..d03b698 --- /dev/null +++ b/node_modules/@babel/compat-data/data/corejs3-shipped-proposals.json @@ -0,0 +1,5 @@ +[ + "esnext.promise.all-settled", + "esnext.string.match-all", + "esnext.global-this" +] diff --git a/node_modules/@babel/compat-data/data/native-modules.json b/node_modules/@babel/compat-data/data/native-modules.json new file mode 100644 index 0000000..2328d21 --- /dev/null +++ b/node_modules/@babel/compat-data/data/native-modules.json @@ -0,0 +1,18 @@ +{ + "es6.module": { + "chrome": "61", + "and_chr": "61", + "edge": "16", + "firefox": "60", + "and_ff": "60", + "node": "13.2.0", + "opera": "48", + "op_mob": "45", + "safari": "10.1", + "ios": "10.3", + "samsung": "8.2", + "android": "61", + "electron": "2.0", + "ios_saf": "10.3" + } +} diff --git a/node_modules/@babel/compat-data/data/overlapping-plugins.json b/node_modules/@babel/compat-data/data/overlapping-plugins.json new file mode 100644 index 0000000..9b884bd --- /dev/null +++ b/node_modules/@babel/compat-data/data/overlapping-plugins.json @@ -0,0 +1,35 @@ +{ + "transform-async-to-generator": [ + "bugfix/transform-async-arrows-in-class" + ], + "transform-parameters": [ + "bugfix/transform-edge-default-parameters", + "bugfix/transform-safari-id-destructuring-collision-in-function-expression" + ], + "transform-function-name": [ + "bugfix/transform-edge-function-name" + ], + "transform-block-scoping": [ + "bugfix/transform-safari-block-shadowing", + "bugfix/transform-safari-for-shadowing" + ], + "transform-template-literals": [ + "bugfix/transform-tagged-template-caching" + ], + "transform-optional-chaining": [ + "bugfix/transform-v8-spread-parameters-in-optional-chaining" + ], + "proposal-optional-chaining": [ + "bugfix/transform-v8-spread-parameters-in-optional-chaining" + ], + "transform-class-properties": [ + "bugfix/transform-v8-static-class-fields-redefine-readonly", + "bugfix/transform-firefox-class-in-computed-class-key", + "bugfix/transform-safari-class-field-initializer-scope" + ], + "proposal-class-properties": [ + "bugfix/transform-v8-static-class-fields-redefine-readonly", + "bugfix/transform-firefox-class-in-computed-class-key", + "bugfix/transform-safari-class-field-initializer-scope" + ] +} diff --git a/node_modules/@babel/compat-data/data/plugin-bugfixes.json b/node_modules/@babel/compat-data/data/plugin-bugfixes.json new file mode 100644 index 0000000..82e4e21 --- /dev/null +++ b/node_modules/@babel/compat-data/data/plugin-bugfixes.json @@ -0,0 +1,213 @@ +{ + "bugfix/transform-async-arrows-in-class": { + "chrome": "55", + "opera": "42", + "edge": "15", + "firefox": "52", + "safari": "11", + "node": "7.6", + "deno": "1", + "ios": "11", + "samsung": "6", + "opera_mobile": "42", + "electron": "1.6" + }, + "bugfix/transform-edge-default-parameters": { + "chrome": "49", + "opera": "36", + "edge": "18", + "firefox": "52", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "36", + "electron": "0.37" + }, + "bugfix/transform-edge-function-name": { + "chrome": "51", + "opera": "38", + "edge": "79", + "firefox": "53", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "bugfix/transform-safari-block-shadowing": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "44", + "safari": "11", + "node": "6", + "deno": "1", + "ie": "11", + "ios": "11", + "samsung": "5", + "opera_mobile": "36", + "electron": "0.37" + }, + "bugfix/transform-safari-for-shadowing": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "4", + "safari": "11", + "node": "6", + "deno": "1", + "ie": "11", + "ios": "11", + "samsung": "5", + "rhino": "1.7.13", + "opera_mobile": "36", + "electron": "0.37" + }, + "bugfix/transform-safari-id-destructuring-collision-in-function-expression": { + "chrome": "49", + "opera": "36", + "edge": "14", + "firefox": "2", + "safari": "16.3", + "node": "6", + "deno": "1", + "ios": "16.3", + "samsung": "5", + "opera_mobile": "36", + "electron": "0.37" + }, + "bugfix/transform-tagged-template-caching": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "34", + "safari": "13", + "node": "4", + "deno": "1", + "ios": "13", + "samsung": "3.4", + "rhino": "1.7.14", + "opera_mobile": "28", + "electron": "0.21" + }, + "bugfix/transform-v8-spread-parameters-in-optional-chaining": { + "chrome": "91", + "opera": "77", + "edge": "91", + "firefox": "74", + "safari": "13.1", + "node": "16.9", + "deno": "1.9", + "ios": "13.4", + "samsung": "16", + "opera_mobile": "64", + "electron": "13.0" + }, + "bugfix/transform-firefox-class-in-computed-class-key": { + "chrome": "74", + "opera": "62", + "edge": "79", + "safari": "16", + "node": "12", + "deno": "1", + "ios": "16", + "samsung": "11", + "opera_mobile": "53", + "electron": "6.0" + }, + "transform-optional-chaining": { + "chrome": "80", + "opera": "67", + "edge": "80", + "firefox": "74", + "safari": "13.1", + "node": "14", + "deno": "1", + "ios": "13.4", + "samsung": "13", + "opera_mobile": "57", + "electron": "8.0" + }, + "proposal-optional-chaining": { + "chrome": "80", + "opera": "67", + "edge": "80", + "firefox": "74", + "safari": "13.1", + "node": "14", + "deno": "1", + "ios": "13.4", + "samsung": "13", + "opera_mobile": "57", + "electron": "8.0" + }, + "transform-parameters": { + "chrome": "49", + "opera": "36", + "edge": "15", + "firefox": "53", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "36", + "electron": "0.37" + }, + "transform-async-to-generator": { + "chrome": "55", + "opera": "42", + "edge": "15", + "firefox": "52", + "safari": "10.1", + "node": "7.6", + "deno": "1", + "ios": "10.3", + "samsung": "6", + "opera_mobile": "42", + "electron": "1.6" + }, + "transform-template-literals": { + "chrome": "41", + "opera": "28", + "edge": "13", + "firefox": "34", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "3.4", + "opera_mobile": "28", + "electron": "0.21" + }, + "transform-function-name": { + "chrome": "51", + "opera": "38", + "edge": "14", + "firefox": "53", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "transform-block-scoping": { + "chrome": "50", + "opera": "37", + "edge": "14", + "firefox": "53", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "37", + "electron": "1.1" + } +} diff --git a/node_modules/@babel/compat-data/data/plugins.json b/node_modules/@babel/compat-data/data/plugins.json new file mode 100644 index 0000000..50fe80e --- /dev/null +++ b/node_modules/@babel/compat-data/data/plugins.json @@ -0,0 +1,815 @@ +{ + "transform-duplicate-named-capturing-groups-regex": { + "chrome": "126", + "opera": "112", + "edge": "126", + "firefox": "129", + "safari": "17.4", + "electron": "31.0" + }, + "transform-unicode-sets-regex": { + "chrome": "112", + "opera": "98", + "edge": "112", + "firefox": "116", + "safari": "17", + "node": "20", + "deno": "1.32", + "ios": "17", + "opera_mobile": "75", + "electron": "24.0" + }, + "bugfix/transform-v8-static-class-fields-redefine-readonly": { + "chrome": "98", + "opera": "84", + "edge": "98", + "firefox": "75", + "safari": "15", + "node": "12", + "deno": "1.18", + "ios": "15", + "samsung": "11", + "opera_mobile": "52", + "electron": "17.0" + }, + "bugfix/transform-firefox-class-in-computed-class-key": { + "chrome": "74", + "opera": "62", + "edge": "79", + "safari": "16", + "node": "12", + "deno": "1", + "ios": "16", + "samsung": "11", + "opera_mobile": "53", + "electron": "6.0" + }, + "bugfix/transform-safari-class-field-initializer-scope": { + "chrome": "74", + "opera": "62", + "edge": "79", + "firefox": "69", + "safari": "16", + "node": "12", + "deno": "1", + "ios": "16", + "samsung": "11", + "opera_mobile": "53", + "electron": "6.0" + }, + "transform-class-static-block": { + "chrome": "94", + "opera": "80", + "edge": "94", + "firefox": "93", + "safari": "16.4", + "node": "16.11", + "deno": "1.14", + "ios": "16.4", + "samsung": "17", + "opera_mobile": "66", + "electron": "15.0" + }, + "proposal-class-static-block": { + "chrome": "94", + "opera": "80", + "edge": "94", + "firefox": "93", + "safari": "16.4", + "node": "16.11", + "deno": "1.14", + "ios": "16.4", + "samsung": "17", + "opera_mobile": "66", + "electron": "15.0" + }, + "transform-private-property-in-object": { + "chrome": "91", + "opera": "77", + "edge": "91", + "firefox": "90", + "safari": "15", + "node": "16.9", + "deno": "1.9", + "ios": "15", + "samsung": "16", + "opera_mobile": "64", + "electron": "13.0" + }, + "proposal-private-property-in-object": { + "chrome": "91", + "opera": "77", + "edge": "91", + "firefox": "90", + "safari": "15", + "node": "16.9", + "deno": "1.9", + "ios": "15", + "samsung": "16", + "opera_mobile": "64", + "electron": "13.0" + }, + "transform-class-properties": { + "chrome": "74", + "opera": "62", + "edge": "79", + "firefox": "90", + "safari": "14.1", + "node": "12", + "deno": "1", + "ios": "14.5", + "samsung": "11", + "opera_mobile": "53", + "electron": "6.0" + }, + "proposal-class-properties": { + "chrome": "74", + "opera": "62", + "edge": "79", + "firefox": "90", + "safari": "14.1", + "node": "12", + "deno": "1", + "ios": "14.5", + "samsung": "11", + "opera_mobile": "53", + "electron": "6.0" + }, + "transform-private-methods": { + "chrome": "84", + "opera": "70", + "edge": "84", + "firefox": "90", + "safari": "15", + "node": "14.6", + "deno": "1", + "ios": "15", + "samsung": "14", + "opera_mobile": "60", + "electron": "10.0" + }, + "proposal-private-methods": { + "chrome": "84", + "opera": "70", + "edge": "84", + "firefox": "90", + "safari": "15", + "node": "14.6", + "deno": "1", + "ios": "15", + "samsung": "14", + "opera_mobile": "60", + "electron": "10.0" + }, + "transform-numeric-separator": { + "chrome": "75", + "opera": "62", + "edge": "79", + "firefox": "70", + "safari": "13", + "node": "12.5", + "deno": "1", + "ios": "13", + "samsung": "11", + "rhino": "1.7.14", + "opera_mobile": "54", + "electron": "6.0" + }, + "proposal-numeric-separator": { + "chrome": "75", + "opera": "62", + "edge": "79", + "firefox": "70", + "safari": "13", + "node": "12.5", + "deno": "1", + "ios": "13", + "samsung": "11", + "rhino": "1.7.14", + "opera_mobile": "54", + "electron": "6.0" + }, + "transform-logical-assignment-operators": { + "chrome": "85", + "opera": "71", + "edge": "85", + "firefox": "79", + "safari": "14", + "node": "15", + "deno": "1.2", + "ios": "14", + "samsung": "14", + "opera_mobile": "60", + "electron": "10.0" + }, + "proposal-logical-assignment-operators": { + "chrome": "85", + "opera": "71", + "edge": "85", + "firefox": "79", + "safari": "14", + "node": "15", + "deno": "1.2", + "ios": "14", + "samsung": "14", + "opera_mobile": "60", + "electron": "10.0" + }, + "transform-nullish-coalescing-operator": { + "chrome": "80", + "opera": "67", + "edge": "80", + "firefox": "72", + "safari": "13.1", + "node": "14", + "deno": "1", + "ios": "13.4", + "samsung": "13", + "opera_mobile": "57", + "electron": "8.0" + }, + "proposal-nullish-coalescing-operator": { + "chrome": "80", + "opera": "67", + "edge": "80", + "firefox": "72", + "safari": "13.1", + "node": "14", + "deno": "1", + "ios": "13.4", + "samsung": "13", + "opera_mobile": "57", + "electron": "8.0" + }, + "transform-optional-chaining": { + "chrome": "91", + "opera": "77", + "edge": "91", + "firefox": "74", + "safari": "13.1", + "node": "16.9", + "deno": "1.9", + "ios": "13.4", + "samsung": "16", + "opera_mobile": "64", + "electron": "13.0" + }, + "proposal-optional-chaining": { + "chrome": "91", + "opera": "77", + "edge": "91", + "firefox": "74", + "safari": "13.1", + "node": "16.9", + "deno": "1.9", + "ios": "13.4", + "samsung": "16", + "opera_mobile": "64", + "electron": "13.0" + }, + "transform-json-strings": { + "chrome": "66", + "opera": "53", + "edge": "79", + "firefox": "62", + "safari": "12", + "node": "10", + "deno": "1", + "ios": "12", + "samsung": "9", + "rhino": "1.7.14", + "opera_mobile": "47", + "electron": "3.0" + }, + "proposal-json-strings": { + "chrome": "66", + "opera": "53", + "edge": "79", + "firefox": "62", + "safari": "12", + "node": "10", + "deno": "1", + "ios": "12", + "samsung": "9", + "rhino": "1.7.14", + "opera_mobile": "47", + "electron": "3.0" + }, + "transform-optional-catch-binding": { + "chrome": "66", + "opera": "53", + "edge": "79", + "firefox": "58", + "safari": "11.1", + "node": "10", + "deno": "1", + "ios": "11.3", + "samsung": "9", + "opera_mobile": "47", + "electron": "3.0" + }, + "proposal-optional-catch-binding": { + "chrome": "66", + "opera": "53", + "edge": "79", + "firefox": "58", + "safari": "11.1", + "node": "10", + "deno": "1", + "ios": "11.3", + "samsung": "9", + "opera_mobile": "47", + "electron": "3.0" + }, + "transform-parameters": { + "chrome": "49", + "opera": "36", + "edge": "18", + "firefox": "53", + "safari": "16.3", + "node": "6", + "deno": "1", + "ios": "16.3", + "samsung": "5", + "opera_mobile": "36", + "electron": "0.37" + }, + "transform-async-generator-functions": { + "chrome": "63", + "opera": "50", + "edge": "79", + "firefox": "57", + "safari": "12", + "node": "10", + "deno": "1", + "ios": "12", + "samsung": "8", + "opera_mobile": "46", + "electron": "3.0" + }, + "proposal-async-generator-functions": { + "chrome": "63", + "opera": "50", + "edge": "79", + "firefox": "57", + "safari": "12", + "node": "10", + "deno": "1", + "ios": "12", + "samsung": "8", + "opera_mobile": "46", + "electron": "3.0" + }, + "transform-object-rest-spread": { + "chrome": "60", + "opera": "47", + "edge": "79", + "firefox": "55", + "safari": "11.1", + "node": "8.3", + "deno": "1", + "ios": "11.3", + "samsung": "8", + "opera_mobile": "44", + "electron": "2.0" + }, + "proposal-object-rest-spread": { + "chrome": "60", + "opera": "47", + "edge": "79", + "firefox": "55", + "safari": "11.1", + "node": "8.3", + "deno": "1", + "ios": "11.3", + "samsung": "8", + "opera_mobile": "44", + "electron": "2.0" + }, + "transform-dotall-regex": { + "chrome": "62", + "opera": "49", + "edge": "79", + "firefox": "78", + "safari": "11.1", + "node": "8.10", + "deno": "1", + "ios": "11.3", + "samsung": "8", + "rhino": "1.7.15", + "opera_mobile": "46", + "electron": "3.0" + }, + "transform-unicode-property-regex": { + "chrome": "64", + "opera": "51", + "edge": "79", + "firefox": "78", + "safari": "11.1", + "node": "10", + "deno": "1", + "ios": "11.3", + "samsung": "9", + "opera_mobile": "47", + "electron": "3.0" + }, + "proposal-unicode-property-regex": { + "chrome": "64", + "opera": "51", + "edge": "79", + "firefox": "78", + "safari": "11.1", + "node": "10", + "deno": "1", + "ios": "11.3", + "samsung": "9", + "opera_mobile": "47", + "electron": "3.0" + }, + "transform-named-capturing-groups-regex": { + "chrome": "64", + "opera": "51", + "edge": "79", + "firefox": "78", + "safari": "11.1", + "node": "10", + "deno": "1", + "ios": "11.3", + "samsung": "9", + "opera_mobile": "47", + "electron": "3.0" + }, + "transform-async-to-generator": { + "chrome": "55", + "opera": "42", + "edge": "15", + "firefox": "52", + "safari": "11", + "node": "7.6", + "deno": "1", + "ios": "11", + "samsung": "6", + "opera_mobile": "42", + "electron": "1.6" + }, + "transform-exponentiation-operator": { + "chrome": "52", + "opera": "39", + "edge": "14", + "firefox": "52", + "safari": "10.1", + "node": "7", + "deno": "1", + "ios": "10.3", + "samsung": "6", + "rhino": "1.7.14", + "opera_mobile": "41", + "electron": "1.3" + }, + "transform-template-literals": { + "chrome": "41", + "opera": "28", + "edge": "13", + "firefox": "34", + "safari": "13", + "node": "4", + "deno": "1", + "ios": "13", + "samsung": "3.4", + "opera_mobile": "28", + "electron": "0.21" + }, + "transform-literals": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "53", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "4", + "rhino": "1.7.15", + "opera_mobile": "32", + "electron": "0.30" + }, + "transform-function-name": { + "chrome": "51", + "opera": "38", + "edge": "79", + "firefox": "53", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "transform-arrow-functions": { + "chrome": "47", + "opera": "34", + "edge": "13", + "firefox": "43", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "rhino": "1.7.13", + "opera_mobile": "34", + "electron": "0.36" + }, + "transform-block-scoped-functions": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "46", + "safari": "10", + "node": "4", + "deno": "1", + "ie": "11", + "ios": "10", + "samsung": "3.4", + "opera_mobile": "28", + "electron": "0.21" + }, + "transform-classes": { + "chrome": "46", + "opera": "33", + "edge": "13", + "firefox": "45", + "safari": "10", + "node": "5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "33", + "electron": "0.36" + }, + "transform-object-super": { + "chrome": "46", + "opera": "33", + "edge": "13", + "firefox": "45", + "safari": "10", + "node": "5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "33", + "electron": "0.36" + }, + "transform-shorthand-properties": { + "chrome": "43", + "opera": "30", + "edge": "12", + "firefox": "33", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "4", + "rhino": "1.7.14", + "opera_mobile": "30", + "electron": "0.27" + }, + "transform-duplicate-keys": { + "chrome": "42", + "opera": "29", + "edge": "12", + "firefox": "34", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "3.4", + "opera_mobile": "29", + "electron": "0.25" + }, + "transform-computed-properties": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "34", + "safari": "7.1", + "node": "4", + "deno": "1", + "ios": "8", + "samsung": "4", + "opera_mobile": "32", + "electron": "0.30" + }, + "transform-for-of": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "53", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "transform-sticky-regex": { + "chrome": "49", + "opera": "36", + "edge": "13", + "firefox": "3", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "rhino": "1.7.15", + "opera_mobile": "36", + "electron": "0.37" + }, + "transform-unicode-escapes": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "53", + "safari": "9", + "node": "4", + "deno": "1", + "ios": "9", + "samsung": "4", + "rhino": "1.7.15", + "opera_mobile": "32", + "electron": "0.30" + }, + "transform-unicode-regex": { + "chrome": "50", + "opera": "37", + "edge": "13", + "firefox": "46", + "safari": "12", + "node": "6", + "deno": "1", + "ios": "12", + "samsung": "5", + "opera_mobile": "37", + "electron": "1.1" + }, + "transform-spread": { + "chrome": "46", + "opera": "33", + "edge": "13", + "firefox": "45", + "safari": "10", + "node": "5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "33", + "electron": "0.36" + }, + "transform-destructuring": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "53", + "safari": "10", + "node": "6.5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "41", + "electron": "1.2" + }, + "transform-block-scoping": { + "chrome": "50", + "opera": "37", + "edge": "14", + "firefox": "53", + "safari": "11", + "node": "6", + "deno": "1", + "ios": "11", + "samsung": "5", + "opera_mobile": "37", + "electron": "1.1" + }, + "transform-typeof-symbol": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "36", + "safari": "9", + "node": "0.12", + "deno": "1", + "ios": "9", + "samsung": "3", + "rhino": "1.7.13", + "opera_mobile": "25", + "electron": "0.20" + }, + "transform-new-target": { + "chrome": "46", + "opera": "33", + "edge": "14", + "firefox": "41", + "safari": "10", + "node": "5", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "33", + "electron": "0.36" + }, + "transform-regenerator": { + "chrome": "50", + "opera": "37", + "edge": "13", + "firefox": "53", + "safari": "10", + "node": "6", + "deno": "1", + "ios": "10", + "samsung": "5", + "opera_mobile": "37", + "electron": "1.1" + }, + "transform-member-expression-literals": { + "chrome": "7", + "opera": "12", + "edge": "12", + "firefox": "2", + "safari": "5.1", + "node": "0.4", + "deno": "1", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "12", + "electron": "0.20" + }, + "transform-property-literals": { + "chrome": "7", + "opera": "12", + "edge": "12", + "firefox": "2", + "safari": "5.1", + "node": "0.4", + "deno": "1", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "12", + "electron": "0.20" + }, + "transform-reserved-words": { + "chrome": "13", + "opera": "10.50", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.6", + "deno": "1", + "ie": "9", + "android": "4.4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "opera_mobile": "10.1", + "electron": "0.20" + }, + "transform-export-namespace-from": { + "chrome": "72", + "deno": "1.0", + "edge": "79", + "firefox": "80", + "node": "13.2", + "opera": "60", + "opera_mobile": "51", + "safari": "14.1", + "ios": "14.5", + "samsung": "11.0", + "android": "72", + "electron": "5.0" + }, + "proposal-export-namespace-from": { + "chrome": "72", + "deno": "1.0", + "edge": "79", + "firefox": "80", + "node": "13.2", + "opera": "60", + "opera_mobile": "51", + "safari": "14.1", + "ios": "14.5", + "samsung": "11.0", + "android": "72", + "electron": "5.0" + } +} diff --git a/node_modules/@babel/compat-data/native-modules.js b/node_modules/@babel/compat-data/native-modules.js new file mode 100644 index 0000000..8e97da4 --- /dev/null +++ b/node_modules/@babel/compat-data/native-modules.js @@ -0,0 +1 @@ +module.exports = require("./data/native-modules.json"); diff --git a/node_modules/@babel/compat-data/overlapping-plugins.js b/node_modules/@babel/compat-data/overlapping-plugins.js new file mode 100644 index 0000000..88242e4 --- /dev/null +++ b/node_modules/@babel/compat-data/overlapping-plugins.js @@ -0,0 +1 @@ +module.exports = require("./data/overlapping-plugins.json"); diff --git a/node_modules/@babel/compat-data/package.json b/node_modules/@babel/compat-data/package.json new file mode 100644 index 0000000..b06ba68 --- /dev/null +++ b/node_modules/@babel/compat-data/package.json @@ -0,0 +1,40 @@ +{ + "name": "@babel/compat-data", + "version": "7.25.4", + "author": "The Babel Team (https://babel.dev/team)", + "license": "MIT", + "description": "", + "repository": { + "type": "git", + "url": "https://github.com/babel/babel.git", + "directory": "packages/babel-compat-data" + }, + "publishConfig": { + "access": "public" + }, + "exports": { + "./plugins": "./plugins.js", + "./native-modules": "./native-modules.js", + "./corejs2-built-ins": "./corejs2-built-ins.js", + "./corejs3-shipped-proposals": "./corejs3-shipped-proposals.js", + "./overlapping-plugins": "./overlapping-plugins.js", + "./plugin-bugfixes": "./plugin-bugfixes.js" + }, + "scripts": { + "build-data": "./scripts/download-compat-table.sh && node ./scripts/build-data.js && node ./scripts/build-modules-support.js && node ./scripts/build-bugfixes-targets.js" + }, + "keywords": [ + "babel", + "compat-table", + "compat-data" + ], + "devDependencies": { + "@mdn/browser-compat-data": "^5.5.36", + "core-js-compat": "^3.37.1", + "electron-to-chromium": "^1.4.816" + }, + "engines": { + "node": ">=6.9.0" + }, + "type": "commonjs" +} \ No newline at end of file diff --git a/node_modules/@babel/compat-data/plugin-bugfixes.js b/node_modules/@babel/compat-data/plugin-bugfixes.js new file mode 100644 index 0000000..f390181 --- /dev/null +++ b/node_modules/@babel/compat-data/plugin-bugfixes.js @@ -0,0 +1 @@ +module.exports = require("./data/plugin-bugfixes.json"); diff --git a/node_modules/@babel/compat-data/plugins.js b/node_modules/@babel/compat-data/plugins.js new file mode 100644 index 0000000..42646ed --- /dev/null +++ b/node_modules/@babel/compat-data/plugins.js @@ -0,0 +1 @@ +module.exports = require("./data/plugins.json"); diff --git a/node_modules/@babel/compat-data/tsconfig.json b/node_modules/@babel/compat-data/tsconfig.json new file mode 100644 index 0000000..e51e763 --- /dev/null +++ b/node_modules/@babel/compat-data/tsconfig.json @@ -0,0 +1,13 @@ +/* This file is automatically generated by scripts/generators/tsconfig.js */ +{ + "extends": [ + "../../tsconfig.base.json", + "../../tsconfig.paths.json" + ], + "include": [ + "../../packages/babel-compat-data/src/**/*.ts", + "../../lib/globals.d.ts", + "../../scripts/repo-utils/*.d.ts" + ], + "references": [] +} \ No newline at end of file diff --git a/node_modules/@babel/compat-data/tsconfig.tsbuildinfo b/node_modules/@babel/compat-data/tsconfig.tsbuildinfo new file mode 100644 index 0000000..3eb8be3 --- /dev/null +++ b/node_modules/@babel/compat-data/tsconfig.tsbuildinfo @@ -0,0 +1 @@ +{"program":{"fileNames":["../../node_modules/typescript/lib/lib.es5.d.ts","../../node_modules/typescript/lib/lib.es2015.d.ts","../../node_modules/typescript/lib/lib.es2016.d.ts","../../node_modules/typescript/lib/lib.es2017.d.ts","../../node_modules/typescript/lib/lib.es2018.d.ts","../../node_modules/typescript/lib/lib.es2019.d.ts","../../node_modules/typescript/lib/lib.es2020.d.ts","../../node_modules/typescript/lib/lib.es2021.d.ts","../../node_modules/typescript/lib/lib.es2022.d.ts","../../node_modules/typescript/lib/lib.es2023.d.ts","../../node_modules/typescript/lib/lib.esnext.d.ts","../../node_modules/typescript/lib/lib.es2015.core.d.ts","../../node_modules/typescript/lib/lib.es2015.collection.d.ts","../../node_modules/typescript/lib/lib.es2015.generator.d.ts","../../node_modules/typescript/lib/lib.es2015.iterable.d.ts","../../node_modules/typescript/lib/lib.es2015.promise.d.ts","../../node_modules/typescript/lib/lib.es2015.proxy.d.ts","../../node_modules/typescript/lib/lib.es2015.reflect.d.ts","../../node_modules/typescript/lib/lib.es2015.symbol.d.ts","../../node_modules/typescript/lib/lib.es2015.symbol.wellknown.d.ts","../../node_modules/typescript/lib/lib.es2016.array.include.d.ts","../../node_modules/typescript/lib/lib.es2016.intl.d.ts","../../node_modules/typescript/lib/lib.es2017.date.d.ts","../../node_modules/typescript/lib/lib.es2017.object.d.ts","../../node_modules/typescript/lib/lib.es2017.sharedmemory.d.ts","../../node_modules/typescript/lib/lib.es2017.string.d.ts","../../node_modules/typescript/lib/lib.es2017.intl.d.ts","../../node_modules/typescript/lib/lib.es2017.typedarrays.d.ts","../../node_modules/typescript/lib/lib.es2018.asyncgenerator.d.ts","../../node_modules/typescript/lib/lib.es2018.asynciterable.d.ts","../../node_modules/typescript/lib/lib.es2018.intl.d.ts","../../node_modules/typescript/lib/lib.es2018.promise.d.ts","../../node_modules/typescript/lib/lib.es2018.regexp.d.ts","../../node_modules/typescript/lib/lib.es2019.array.d.ts","../../node_modules/typescript/lib/lib.es2019.object.d.ts","../../node_modules/typescript/lib/lib.es2019.string.d.ts","../../node_modules/typescript/lib/lib.es2019.symbol.d.ts","../../node_modules/typescript/lib/lib.es2019.intl.d.ts","../../node_modules/typescript/lib/lib.es2020.bigint.d.ts","../../node_modules/typescript/lib/lib.es2020.date.d.ts","../../node_modules/typescript/lib/lib.es2020.promise.d.ts","../../node_modules/typescript/lib/lib.es2020.sharedmemory.d.ts","../../node_modules/typescript/lib/lib.es2020.string.d.ts","../../node_modules/typescript/lib/lib.es2020.symbol.wellknown.d.ts","../../node_modules/typescript/lib/lib.es2020.intl.d.ts","../../node_modules/typescript/lib/lib.es2020.number.d.ts","../../node_modules/typescript/lib/lib.es2021.promise.d.ts","../../node_modules/typescript/lib/lib.es2021.string.d.ts","../../node_modules/typescript/lib/lib.es2021.weakref.d.ts","../../node_modules/typescript/lib/lib.es2021.intl.d.ts","../../node_modules/typescript/lib/lib.es2022.array.d.ts","../../node_modules/typescript/lib/lib.es2022.error.d.ts","../../node_modules/typescript/lib/lib.es2022.intl.d.ts","../../node_modules/typescript/lib/lib.es2022.object.d.ts","../../node_modules/typescript/lib/lib.es2022.sharedmemory.d.ts","../../node_modules/typescript/lib/lib.es2022.string.d.ts","../../node_modules/typescript/lib/lib.es2022.regexp.d.ts","../../node_modules/typescript/lib/lib.es2023.array.d.ts","../../node_modules/typescript/lib/lib.es2023.collection.d.ts","../../node_modules/typescript/lib/lib.es2023.intl.d.ts","../../node_modules/typescript/lib/lib.esnext.array.d.ts","../../node_modules/typescript/lib/lib.esnext.collection.d.ts","../../node_modules/typescript/lib/lib.esnext.intl.d.ts","../../node_modules/typescript/lib/lib.esnext.disposable.d.ts","../../node_modules/typescript/lib/lib.esnext.string.d.ts","../../node_modules/typescript/lib/lib.esnext.promise.d.ts","../../node_modules/typescript/lib/lib.esnext.decorators.d.ts","../../node_modules/typescript/lib/lib.esnext.object.d.ts","../../node_modules/typescript/lib/lib.esnext.regexp.d.ts","../../node_modules/typescript/lib/lib.decorators.d.ts","../../node_modules/typescript/lib/lib.decorators.legacy.d.ts","../../lib/globals.d.ts","../../node_modules/@types/charcodes/index.d.ts","../../node_modules/@types/color-name/index.d.ts","../../node_modules/@types/convert-source-map/index.d.ts","../../node_modules/@types/debug/index.d.ts","../../node_modules/@types/eslint/helpers.d.ts","../../node_modules/@types/estree/index.d.ts","../../node_modules/@types/json-schema/index.d.ts","../../node_modules/@types/eslint/index.d.ts","../../node_modules/@types/eslint-scope/index.d.ts","../../node_modules/@types/fs-readdir-recursive/index.d.ts","../../node_modules/@types/gensync/index.d.ts","../../node_modules/@types/node/assert.d.ts","../../node_modules/@types/node/assert/strict.d.ts","../../node_modules/buffer/index.d.ts","../../node_modules/undici-types/header.d.ts","../../node_modules/undici-types/readable.d.ts","../../node_modules/undici-types/file.d.ts","../../node_modules/undici-types/fetch.d.ts","../../node_modules/undici-types/formdata.d.ts","../../node_modules/undici-types/connector.d.ts","../../node_modules/undici-types/client.d.ts","../../node_modules/undici-types/errors.d.ts","../../node_modules/undici-types/dispatcher.d.ts","../../node_modules/undici-types/global-dispatcher.d.ts","../../node_modules/undici-types/global-origin.d.ts","../../node_modules/undici-types/pool-stats.d.ts","../../node_modules/undici-types/pool.d.ts","../../node_modules/undici-types/handlers.d.ts","../../node_modules/undici-types/balanced-pool.d.ts","../../node_modules/undici-types/agent.d.ts","../../node_modules/undici-types/mock-interceptor.d.ts","../../node_modules/undici-types/mock-agent.d.ts","../../node_modules/undici-types/mock-client.d.ts","../../node_modules/undici-types/mock-pool.d.ts","../../node_modules/undici-types/mock-errors.d.ts","../../node_modules/undici-types/proxy-agent.d.ts","../../node_modules/undici-types/api.d.ts","../../node_modules/undici-types/cookies.d.ts","../../node_modules/undici-types/patch.d.ts","../../node_modules/undici-types/filereader.d.ts","../../node_modules/undici-types/diagnostics-channel.d.ts","../../node_modules/undici-types/websocket.d.ts","../../node_modules/undici-types/content-type.d.ts","../../node_modules/undici-types/cache.d.ts","../../node_modules/undici-types/interceptors.d.ts","../../node_modules/undici-types/index.d.ts","../../node_modules/@types/node/globals.d.ts","../../node_modules/@types/node/async_hooks.d.ts","../../node_modules/@types/node/buffer.d.ts","../../node_modules/@types/node/child_process.d.ts","../../node_modules/@types/node/cluster.d.ts","../../node_modules/@types/node/console.d.ts","../../node_modules/@types/node/constants.d.ts","../../node_modules/@types/node/crypto.d.ts","../../node_modules/@types/node/dgram.d.ts","../../node_modules/@types/node/diagnostics_channel.d.ts","../../node_modules/@types/node/dns.d.ts","../../node_modules/@types/node/dns/promises.d.ts","../../node_modules/@types/node/domain.d.ts","../../node_modules/@types/node/dom-events.d.ts","../../node_modules/@types/node/events.d.ts","../../node_modules/@types/node/fs.d.ts","../../node_modules/@types/node/fs/promises.d.ts","../../node_modules/@types/node/http.d.ts","../../node_modules/@types/node/http2.d.ts","../../node_modules/@types/node/https.d.ts","../../node_modules/@types/node/inspector.d.ts","../../node_modules/@types/node/module.d.ts","../../node_modules/@types/node/net.d.ts","../../node_modules/@types/node/os.d.ts","../../node_modules/@types/node/path.d.ts","../../node_modules/@types/node/perf_hooks.d.ts","../../node_modules/@types/node/process.d.ts","../../node_modules/@types/node/punycode.d.ts","../../node_modules/@types/node/querystring.d.ts","../../node_modules/@types/node/readline.d.ts","../../node_modules/@types/node/readline/promises.d.ts","../../node_modules/@types/node/repl.d.ts","../../node_modules/@types/node/sea.d.ts","../../node_modules/@types/node/stream.d.ts","../../node_modules/@types/node/stream/promises.d.ts","../../node_modules/@types/node/stream/consumers.d.ts","../../node_modules/@types/node/stream/web.d.ts","../../node_modules/@types/node/string_decoder.d.ts","../../node_modules/@types/node/test.d.ts","../../node_modules/@types/node/timers.d.ts","../../node_modules/@types/node/timers/promises.d.ts","../../node_modules/@types/node/tls.d.ts","../../node_modules/@types/node/trace_events.d.ts","../../node_modules/@types/node/tty.d.ts","../../node_modules/@types/node/url.d.ts","../../node_modules/@types/node/util.d.ts","../../node_modules/@types/node/v8.d.ts","../../node_modules/@types/node/vm.d.ts","../../node_modules/@types/node/wasi.d.ts","../../node_modules/@types/node/worker_threads.d.ts","../../node_modules/@types/node/zlib.d.ts","../../node_modules/@types/node/globals.global.d.ts","../../node_modules/@types/node/index.d.ts","../../node_modules/@types/minimatch/index.d.ts","../../node_modules/@types/glob/index.d.ts","../../node_modules/@types/istanbul-lib-coverage/index.d.ts","../../node_modules/@types/istanbul-lib-report/index.d.ts","../../node_modules/@types/istanbul-reports/index.d.ts","../../node_modules/@types/jest/node_modules/@jest/expect-utils/build/index.d.ts","../../node_modules/@types/jest/node_modules/chalk/index.d.ts","../../node_modules/@sinclair/typebox/typebox.d.ts","../../node_modules/@jest/schemas/build/index.d.ts","../../node_modules/jest-diff/node_modules/pretty-format/build/index.d.ts","../../node_modules/jest-diff/build/index.d.ts","../../node_modules/@types/jest/node_modules/jest-matcher-utils/build/index.d.ts","../../node_modules/@types/jest/node_modules/expect/build/index.d.ts","../../node_modules/@types/jest/node_modules/pretty-format/build/index.d.ts","../../node_modules/@types/jest/index.d.ts","../../node_modules/@types/jsesc/index.d.ts","../../node_modules/@types/json5/index.d.ts","../../node_modules/@types/lru-cache/index.d.ts","../../node_modules/@types/resolve/index.d.ts","../../node_modules/@types/semver/classes/semver.d.ts","../../node_modules/@types/semver/functions/parse.d.ts","../../node_modules/@types/semver/functions/valid.d.ts","../../node_modules/@types/semver/functions/clean.d.ts","../../node_modules/@types/semver/functions/inc.d.ts","../../node_modules/@types/semver/functions/diff.d.ts","../../node_modules/@types/semver/functions/major.d.ts","../../node_modules/@types/semver/functions/minor.d.ts","../../node_modules/@types/semver/functions/patch.d.ts","../../node_modules/@types/semver/functions/prerelease.d.ts","../../node_modules/@types/semver/functions/compare.d.ts","../../node_modules/@types/semver/functions/rcompare.d.ts","../../node_modules/@types/semver/functions/compare-loose.d.ts","../../node_modules/@types/semver/functions/compare-build.d.ts","../../node_modules/@types/semver/functions/sort.d.ts","../../node_modules/@types/semver/functions/rsort.d.ts","../../node_modules/@types/semver/functions/gt.d.ts","../../node_modules/@types/semver/functions/lt.d.ts","../../node_modules/@types/semver/functions/eq.d.ts","../../node_modules/@types/semver/functions/neq.d.ts","../../node_modules/@types/semver/functions/gte.d.ts","../../node_modules/@types/semver/functions/lte.d.ts","../../node_modules/@types/semver/functions/cmp.d.ts","../../node_modules/@types/semver/functions/coerce.d.ts","../../node_modules/@types/semver/classes/comparator.d.ts","../../node_modules/@types/semver/classes/range.d.ts","../../node_modules/@types/semver/functions/satisfies.d.ts","../../node_modules/@types/semver/ranges/max-satisfying.d.ts","../../node_modules/@types/semver/ranges/min-satisfying.d.ts","../../node_modules/@types/semver/ranges/to-comparators.d.ts","../../node_modules/@types/semver/ranges/min-version.d.ts","../../node_modules/@types/semver/ranges/valid.d.ts","../../node_modules/@types/semver/ranges/outside.d.ts","../../node_modules/@types/semver/ranges/gtr.d.ts","../../node_modules/@types/semver/ranges/ltr.d.ts","../../node_modules/@types/semver/ranges/intersects.d.ts","../../node_modules/@types/semver/ranges/simplify.d.ts","../../node_modules/@types/semver/ranges/subset.d.ts","../../node_modules/@types/semver/internals/identifiers.d.ts","../../node_modules/@types/semver/index.d.ts","../../node_modules/@types/stack-utils/index.d.ts","../../node_modules/@types/v8flags/index.d.ts","../../node_modules/@types/yargs-parser/index.d.ts","../../node_modules/@types/yargs/index.d.ts"],"fileInfos":[{"version":"44e584d4f6444f58791784f1d530875970993129442a847597db702a073ca68c","affectsGlobalScope":true},"45b7ab580deca34ae9729e97c13cfd999df04416a79116c3bfb483804f85ded4","3facaf05f0c5fc569c5649dd359892c98a85557e3e0c847964caeb67076f4d75","9a68c0c07ae2fa71b44384a839b7b8d81662a236d4b9ac30916718f7510b1b2d","5e1c4c362065a6b95ff952c0eab010f04dcd2c3494e813b493ecfd4fcb9fc0d8","68d73b4a11549f9c0b7d352d10e91e5dca8faa3322bfb77b661839c42b1ddec7","5efce4fc3c29ea84e8928f97adec086e3dc876365e0982cc8479a07954a3efd4","feecb1be483ed332fad555aff858affd90a48ab19ba7272ee084704eb7167569","5514e54f17d6d74ecefedc73c504eadffdeda79c7ea205cf9febead32d45c4bc","27bdc30a0e32783366a5abeda841bc22757c1797de8681bbe81fbc735eeb1c10","17edc026abf73c5c2dd508652d63f68ec4efd9d4856e3469890d27598209feb5",{"version":"6920e1448680767498a0b77c6a00a8e77d14d62c3da8967b171f1ddffa3c18e4","affectsGlobalScope":true},{"version":"dc2df20b1bcdc8c2d34af4926e2c3ab15ffe1160a63e58b7e09833f616efff44","affectsGlobalScope":true},{"version":"4443e68b35f3332f753eacc66a04ac1d2053b8b035a0e0ac1d455392b5e243b3","affectsGlobalScope":true},{"version":"bc47685641087c015972a3f072480889f0d6c65515f12bd85222f49a98952ed7","affectsGlobalScope":true},{"version":"0dc1e7ceda9b8b9b455c3a2d67b0412feab00bd2f66656cd8850e8831b08b537","affectsGlobalScope":true},{"version":"ce691fb9e5c64efb9547083e4a34091bcbe5bdb41027e310ebba8f7d96a98671","affectsGlobalScope":true},{"version":"8d697a2a929a5fcb38b7a65594020fcef05ec1630804a33748829c5ff53640d0","affectsGlobalScope":true},{"version":"4ff2a353abf8a80ee399af572debb8faab2d33ad38c4b4474cff7f26e7653b8d","affectsGlobalScope":true},{"version":"93495ff27b8746f55d19fcbcdbaccc99fd95f19d057aed1bd2c0cafe1335fbf0","affectsGlobalScope":true},{"version":"6fc23bb8c3965964be8c597310a2878b53a0306edb71d4b5a4dfe760186bcc01","affectsGlobalScope":true},{"version":"ea011c76963fb15ef1cdd7ce6a6808b46322c527de2077b6cfdf23ae6f5f9ec7","affectsGlobalScope":true},{"version":"38f0219c9e23c915ef9790ab1d680440d95419ad264816fa15009a8851e79119","affectsGlobalScope":true},{"version":"bb42a7797d996412ecdc5b2787720de477103a0b2e53058569069a0e2bae6c7e","affectsGlobalScope":true},{"version":"4738f2420687fd85629c9efb470793bb753709c2379e5f85bc1815d875ceadcd","affectsGlobalScope":true},{"version":"2f11ff796926e0832f9ae148008138ad583bd181899ab7dd768a2666700b1893","affectsGlobalScope":true},{"version":"4de680d5bb41c17f7f68e0419412ca23c98d5749dcaaea1896172f06435891fc","affectsGlobalScope":true},{"version":"9fc46429fbe091ac5ad2608c657201eb68b6f1b8341bd6d670047d32ed0a88fa","affectsGlobalScope":true},{"version":"61c37c1de663cf4171e1192466e52c7a382afa58da01b1dc75058f032ddf0839","affectsGlobalScope":true},{"version":"b541a838a13f9234aba650a825393ffc2292dc0fc87681a5d81ef0c96d281e7a","affectsGlobalScope":true},{"version":"9e9fbd7030c440b33d021da145d3232984c8bb7916f277e8ffd3dc2e3eae2bdb","affectsGlobalScope":true},{"version":"811ec78f7fefcabbda4bfa93b3eb67d9ae166ef95f9bff989d964061cbf81a0c","affectsGlobalScope":true},{"version":"717937616a17072082152a2ef351cb51f98802fb4b2fdabd32399843875974ca","affectsGlobalScope":true},{"version":"d7e7d9b7b50e5f22c915b525acc5a49a7a6584cf8f62d0569e557c5cfc4b2ac2","affectsGlobalScope":true},{"version":"71c37f4c9543f31dfced6c7840e068c5a5aacb7b89111a4364b1d5276b852557","affectsGlobalScope":true},{"version":"576711e016cf4f1804676043e6a0a5414252560eb57de9faceee34d79798c850","affectsGlobalScope":true},{"version":"89c1b1281ba7b8a96efc676b11b264de7a8374c5ea1e6617f11880a13fc56dc6","affectsGlobalScope":true},{"version":"74f7fa2d027d5b33eb0471c8e82a6c87216223181ec31247c357a3e8e2fddc5b","affectsGlobalScope":true},{"version":"ae37d6ccd1560b0203ab88d46987393adaaa78c919e51acf32fb82c86502e98c","affectsGlobalScope":true},{"version":"063600664504610fe3e99b717a1223f8b1900087fab0b4cad1496a114744f8df","affectsGlobalScope":true},{"version":"934019d7e3c81950f9a8426d093458b65d5aff2c7c1511233c0fd5b941e608ab","affectsGlobalScope":true},{"version":"bf14a426dbbf1022d11bd08d6b8e709a2e9d246f0c6c1032f3b2edb9a902adbe","affectsGlobalScope":true},{"version":"5e07ed3809d48205d5b985642a59f2eba47c402374a7cf8006b686f79efadcbd","affectsGlobalScope":true},{"version":"2b72d528b2e2fe3c57889ca7baef5e13a56c957b946906d03767c642f386bbc3","affectsGlobalScope":true},{"version":"479553e3779be7d4f68e9f40cdb82d038e5ef7592010100410723ceced22a0f7","affectsGlobalScope":true},{"version":"368af93f74c9c932edd84c58883e736c9e3d53cec1fe24c0b0ff451f529ceab1","affectsGlobalScope":true},{"version":"af3dd424cf267428f30ccfc376f47a2c0114546b55c44d8c0f1d57d841e28d74","affectsGlobalScope":true},{"version":"995c005ab91a498455ea8dfb63aa9f83fa2ea793c3d8aa344be4a1678d06d399","affectsGlobalScope":true},{"version":"d3d7b04b45033f57351c8434f60b6be1ea71a2dfec2d0a0c3c83badbb0e3e693","affectsGlobalScope":true},{"version":"956d27abdea9652e8368ce029bb1e0b9174e9678a273529f426df4b3d90abd60","affectsGlobalScope":true},{"version":"4fa6ed14e98aa80b91f61b9805c653ee82af3502dc21c9da5268d3857772ca05","affectsGlobalScope":true},{"version":"e6633e05da3ff36e6da2ec170d0d03ccf33de50ca4dc6f5aeecb572cedd162fb","affectsGlobalScope":true},{"version":"d8670852241d4c6e03f2b89d67497a4bbefe29ecaa5a444e2c11a9b05e6fccc6","affectsGlobalScope":true},{"version":"8444af78980e3b20b49324f4a16ba35024fef3ee069a0eb67616ea6ca821c47a","affectsGlobalScope":true},{"version":"caccc56c72713969e1cfe5c3d44e5bab151544d9d2b373d7dbe5a1e4166652be","affectsGlobalScope":true},{"version":"3287d9d085fbd618c3971944b65b4be57859f5415f495b33a6adc994edd2f004","affectsGlobalScope":true},{"version":"b4b67b1a91182421f5df999988c690f14d813b9850b40acd06ed44691f6727ad","affectsGlobalScope":true},{"version":"08a58483392df5fcc1db57d782e87734f77ae9eab42516028acbfe46f29a3ef7","affectsGlobalScope":true},{"version":"436aaf437562f276ec2ddbee2f2cdedac7664c1e4c1d2c36839ddd582eeb3d0a","affectsGlobalScope":true},{"version":"8e3c06ea092138bf9fa5e874a1fdbc9d54805d074bee1de31b99a11e2fec239d","affectsGlobalScope":true},{"version":"0b11f3ca66aa33124202c80b70cd203219c3d4460cfc165e0707aa9ec710fc53","affectsGlobalScope":true},{"version":"6a3f5a0129cc80cf439ab71164334d649b47059a4f5afca90282362407d0c87f","affectsGlobalScope":true},{"version":"811c71eee4aa0ac5f7adf713323a5c41b0cf6c4e17367a34fbce379e12bbf0a4","affectsGlobalScope":true},{"version":"15b98a533864d324e5f57cd3cfc0579b231df58c1c0f6063ea0fcb13c3c74ff9","affectsGlobalScope":true},{"version":"0a6282c8827e4b9a95f4bf4f5c205673ada31b982f50572d27103df8ceb8013c","affectsGlobalScope":true},{"version":"ac77cb3e8c6d3565793eb90a8373ee8033146315a3dbead3bde8db5eaf5e5ec6","affectsGlobalScope":true},{"version":"d4b1d2c51d058fc21ec2629fff7a76249dec2e36e12960ea056e3ef89174080f","affectsGlobalScope":true},{"version":"2fef54945a13095fdb9b84f705f2b5994597640c46afeb2ce78352fab4cb3279","affectsGlobalScope":true},{"version":"56e4ed5aab5f5920980066a9409bfaf53e6d21d3f8d020c17e4de584d29600ad","affectsGlobalScope":true},{"version":"33358442698bb565130f52ba79bfd3d4d484ac85fe33f3cb1759c54d18201393","affectsGlobalScope":true},{"version":"782dec38049b92d4e85c1585fbea5474a219c6984a35b004963b00beb1aab538","affectsGlobalScope":true},{"version":"f0b6690984c3a44b15740ac24bfb63853617731c0f40c87a956ce537c4b50969","affectsGlobalScope":true},"b7589677bd27b038f8aae8afeb030e554f1d5ff29dc4f45854e2cb7e5095d59a","f0cb4b3ab88193e3e51e9e2622e4c375955003f1f81239d72c5b7a95415dad3e","13d94ac3ee5780f99988ae4cce0efd139598ca159553bc0100811eba74fc2351","3cf5f191d75bbe7c92f921e5ae12004ac672266e2be2ece69f40b1d6b1b678f9",{"version":"64d4b35c5456adf258d2cf56c341e203a073253f229ef3208fc0d5020253b241","affectsGlobalScope":true},"ee7d8894904b465b072be0d2e4b45cf6b887cdba16a467645c4e200982ece7ea","f3d8c757e148ad968f0d98697987db363070abada5f503da3c06aefd9d4248c1","0c5a621a8cf10464c2020f05c99a86d8ac6875d9e17038cb8522cc2f604d539f","e050a0afcdbb269720a900c85076d18e0c1ab73e580202a2bf6964978181222a","1d78c35b7e8ce86a188e3e5528cc5d1edfc85187a85177458d26e17c8b48105f","bde8c75c442f701f7c428265ecad3da98023b6152db9ca49552304fd19fdba38","acdc9fb9638a235a69bd270003d8db4d6153ada2b7ccbea741ade36b295e431e","7394959e5a741b185456e1ef5d64599c36c60a323207450991e7a42e08911419","4967529644e391115ca5592184d4b63980569adf60ee685f968fd59ab1557188","5929864ce17fba74232584d90cb721a89b7ad277220627cc97054ba15a98ea8f","7180c03fd3cb6e22f911ce9ba0f8a7008b1a6ddbe88ccf16a9c8140ef9ac1686","25c8056edf4314820382a5fdb4bb7816999acdcb929c8f75e3f39473b87e85bc","54cb85a47d760da1c13c00add10d26b5118280d44d58e6908d8e89abbd9d7725","3e4825171442666d31c845aeb47fcd34b62e14041bb353ae2b874285d78482aa","c6fd2c5a395f2432786c9cb8deb870b9b0e8ff7e22c029954fabdd692bff6195","a967bfe3ad4e62243eb604bf956101e4c740f5921277c60debaf325c1320bf88","e9775e97ac4877aebf963a0289c81abe76d1ec9a2a7778dbe637e5151f25c5f3","471e1da5a78350bc55ef8cef24eb3aca6174143c281b8b214ca2beda51f5e04a","cadc8aced301244057c4e7e73fbcae534b0f5b12a37b150d80e5a45aa4bebcbd","385aab901643aa54e1c36f5ef3107913b10d1b5bb8cbcd933d4263b80a0d7f20","9670d44354bab9d9982eca21945686b5c24a3f893db73c0dae0fd74217a4c219","db3435f3525cd785bf21ec6769bf8da7e8a776be1a99e2e7efb5f244a2ef5fee","c3b170c45fc031db31f782e612adf7314b167e60439d304b49e704010e7bafe5","40383ebef22b943d503c6ce2cb2e060282936b952a01bea5f9f493d5fb487cc7","4893a895ea92c85345017a04ed427cbd6a1710453338df26881a6019432febdd","3a84b7cb891141824bd00ef8a50b6a44596aded4075da937f180c90e362fe5f6","13f6f39e12b1518c6650bbb220c8985999020fe0f21d818e28f512b7771d00f9","9b5369969f6e7175740bf51223112ff209f94ba43ecd3bb09eefff9fd675624a","4fe9e626e7164748e8769bbf74b538e09607f07ed17c2f20af8d680ee49fc1da","24515859bc0b836719105bb6cc3d68255042a9f02a6022b3187948b204946bd2","33203609eba548914dc83ddf6cadbc0bcb6e8ef89f6d648ca0908ae887f9fcc5","0db18c6e78ea846316c012478888f33c11ffadab9efd1cc8bcc12daded7a60b6","89167d696a849fce5ca508032aabfe901c0868f833a8625d5a9c6e861ef935d2","e53a3c2a9f624d90f24bf4588aacd223e7bec1b9d0d479b68d2f4a9e6011147f","339dc5265ee5ed92e536a93a04c4ebbc2128f45eeec6ed29f379e0085283542c","9f0a92164925aa37d4a5d9dd3e0134cff8177208dba55fd2310cd74beea40ee2","8bfdb79bf1a9d435ec48d9372dc93291161f152c0865b81fc0b2694aedb4578d","2e85db9e6fd73cfa3d7f28e0ab6b55417ea18931423bd47b409a96e4a169e8e6","c46e079fe54c76f95c67fb89081b3e399da2c7d109e7dca8e4b58d83e332e605","d32275be3546f252e3ad33976caf8c5e842c09cb87d468cb40d5f4cf092d1acc","4a0c3504813a3289f7fb1115db13967c8e004aa8e4f8a9021b95285502221bd1",{"version":"a14ed46fa3f5ffc7a8336b497cd07b45c2084213aaca933a22443fcb2eef0d07","affectsGlobalScope":true},"cce1f5f86974c1e916ec4a8cab6eec9aa8e31e8148845bf07fbaa8e1d97b1a2c",{"version":"7fd7fcbf021a5845bdd9397d4649fcf2fe17152d2098140fc723099a215d19ad","affectsGlobalScope":true},"df3389f71a71a38bc931aaf1ef97a65fada98f0a27f19dd12f8b8de2b0f4e461","d69a3298a197fe5d59edba0ec23b4abf2c8e7b8c6718eac97833633cd664e4c9",{"version":"a9544f6f8af0d046565e8dde585502698ebc99eef28b715bad7c2bded62e4a32","affectsGlobalScope":true},"a40826e8476694e90da94aa008283a7de50d1dafd37beada623863f1901cb7fb",{"version":"8b809082dfeffc8cc4f3b9c59f55c0ff52ba12f5ae0766cb5c35deee83b8552e","affectsGlobalScope":true},"bd3f5d05b6b5e4bfcea7739a45f3ffb4a7f4a3442ba7baf93e0200799285b8f1","4c775c2fccabf49483c03cd5e3673f87c1ffb6079d98e7b81089c3def79e29c6","d4f9d3ae2fe1ae199e1c832cca2c44f45e0b305dfa2808afdd51249b6f4a5163","7525257b4aa35efc7a1bbc00f205a9a96c4e4ab791da90db41b77938c4e0c18e","b7fe70be794e13d1b7940e318b8770cd1fb3eced7707805318a2e3aaac2c3e9e",{"version":"ee1ee365d88c4c6c0c0a5a5701d66ebc27ccd0bcfcfaa482c6e2e7fe7b98edf7","affectsGlobalScope":true},{"version":"9c611eff81287837680c1f4496daf9e737d6f3a1ff17752207814b8f8e1265af","affectsGlobalScope":true},"fe1fd6afdfe77976d4c702f3746c05fb05a7e566845c890e0e970fe9376d6a90","b5d4e3e524f2eead4519c8e819eaf7fa44a27c22418eff1b7b2d0ebc5fdc510d","afb1701fd4be413a8a5a88df6befdd4510c30a31372c07a4138facf61594c66d","9bd8e5984676cf28ebffcc65620b4ab5cb38ab2ec0aac0825df8568856895653","396a8939b5e177542bdf9b5262b4eee85d29851b2d57681fa9d7eae30e225830","5e8dc64e7e68b2b3ea52ed685cf85239e0d5fb9df31aabc94370c6bc7e19077b",{"version":"ea455cc68871b049bcecd9f56d4cf27b852d6dafd5e3b54468ca87cc11604e4d","affectsGlobalScope":true},"c07146dbbbd8b347241b5df250a51e48f2d7bef19b1e187b1a3f20c849988ff1","45b1053e691c5af9bfe85060a3e1542835f8d84a7e6e2e77ca305251eda0cb3c","0f05c06ff6196958d76b865ae17245b52d8fe01773626ac3c43214a2458ea7b7",{"version":"ae5507fc333d637dec9f37c6b3f4d423105421ea2820a64818de55db85214d66","affectsGlobalScope":true},{"version":"46755a4afc53df75f0bfce72259fb971daac826b0cdd8c4eaccad2755a817403","affectsGlobalScope":true},"8abd0566d2854c4bd1c5e48e05df5c74927187f1541e6770001d9637ac41542e","54e854615c4eafbdd3fd7688bd02a3aafd0ccf0e87c98f79d3e9109f047ce6b8","d8dba11dc34d50cb4202de5effa9a1b296d7a2f4a029eec871f894bddfb6430d","8b71dd18e7e63b6f991b511a201fad7c3bf8d1e0dd98acb5e3d844f335a73634","01d8e1419c84affad359cc240b2b551fb9812b450b4d3d456b64cda8102d4f60","9eece5e586312581ccd106d4853e861aaaa1a39f8e3ea672b8c3847eedd12f6e","8221b00f271cf7f535a8eeec03b0f80f0929c7a16116e2d2df089b41066de69b","269929a24b2816343a178008ac9ae9248304d92a8ba8e233055e0ed6dbe6ef71","93452d394fdd1dc551ec62f5042366f011a00d342d36d50793b3529bfc9bd633","7fa32887f8a97909fca35ebba3740f8caf8df146618d8fff957a3f89f67a2f6a","9a9634296cca836c3308923ba7aa094fa6ed76bb1e366d8ddcf5c65888ab1024",{"version":"bddce945d552a963c9733db106b17a25474eefcab7fc990157a2134ef55d4954","affectsGlobalScope":true},{"version":"7052b7b0c3829df3b4985bab2fd74531074b4835d5a7b263b75c82f0916ad62f","affectsGlobalScope":true},"aa34c3aa493d1c699601027c441b9664547c3024f9dbab1639df7701d63d18fa","4b55240c2a03b2c71e98a7fc528b16136faa762211c92e781a01c37821915ea6","7c651f8dce91a927ab62925e73f190763574c46098f2b11fb8ddc1b147a6709a","7440ab60f4cb031812940cc38166b8bb6fbf2540cfe599f87c41c08011f0c1df",{"version":"94c086dff8dbc5998749326bc69b520e8e4273fb5b7b58b50e0210e0885dfcde","affectsGlobalScope":true},{"version":"f5b5dc128973498b75f52b1b8c2d5f8629869104899733ae485100c2309b4c12","affectsGlobalScope":true},"ebe5facd12fd7745cda5f4bc3319f91fb29dc1f96e57e9c6f8b260a7cc5b67ee","79bad8541d5779c85e82a9fb119c1fe06af77a71cc40f869d62ad379473d4b75","21c56c6e8eeacef15f63f373a29fab6a2b36e4705be7a528aae8c51469e2737b",{"version":"629d20681ca284d9e38c0a019f647108f5fe02f9c59ac164d56f5694fc3faf4d","affectsGlobalScope":true},"e7dbf5716d76846c7522e910896c5747b6df1abd538fee8f5291bdc843461795",{"version":"ab9b9a36e5284fd8d3bf2f7d5fcbc60052f25f27e4d20954782099282c60d23e","affectsGlobalScope":true},"a42be67ed1ddaec743582f41fc219db96a1b69719fccac6d1464321178d610fc","8841e2aa774b89bd23302dede20663306dc1b9902431ac64b24be8b8d0e3f649","fd326577c62145816fe1acc306c734c2396487f76719d3785d4e825b34540b33","9e951ec338c4232d611552a1be7b4ecec79a8c2307a893ce39701316fe2374bd","70c61ff569aabdf2b36220da6c06caaa27e45cd7acac81a1966ab4ee2eadc4f2","905c3e8f7ddaa6c391b60c05b2f4c3931d7127ad717a080359db3df510b7bdab","6c1e688f95fcaf53b1e41c0fdadf2c1cfc96fa924eaf7f9fdb60f96deb0a4986","0d14fa22c41fdc7277e6f71473b20ebc07f40f00e38875142335d5b63cdfc9d2","c085e9aa62d1ae1375794c1fb927a445fa105fed891a7e24edbb1c3300f7384a","f315e1e65a1f80992f0509e84e4ae2df15ecd9ef73df975f7c98813b71e4c8da","5b9586e9b0b6322e5bfbd2c29bd3b8e21ab9d871f82346cb71020e3d84bae73e","3e70a7e67c2cb16f8cd49097360c0309fe9d1e3210ff9222e9dac1f8df9d4fb6","ab68d2a3e3e8767c3fba8f80de099a1cfc18c0de79e42cb02ae66e22dfe14a66","6d969939c4a63f70f2aa49e88da6f64b655c8e6799612807bef41ccff6ea0da9","5b9586e9b0b6322e5bfbd2c29bd3b8e21ab9d871f82346cb71020e3d84bae73e",{"version":"46894b2a21a60f8449ca6b2b7223b7179bba846a61b1434bed77b34b2902c306","affectsGlobalScope":true},"84a805c22a49922085dc337ca71ac0b85aad6d4dba6b01cee5bd5776ff54df39","96d14f21b7652903852eef49379d04dbda28c16ed36468f8c9fa08f7c14c9538","6d727c1f6a7122c04e4f7c164c5e6f460c21ada618856894cdaa6ac25e95f38c","8baa5d0febc68db886c40bf341e5c90dc215a90cd64552e47e8184be6b7e3358","cf3d384d082b933d987c4e2fe7bfb8710adfd9dc8155190056ed6695a25a559e","9871b7ee672bc16c78833bdab3052615834b08375cb144e4d2cba74473f4a589","c863198dae89420f3c552b5a03da6ed6d0acfa3807a64772b895db624b0de707","8b03a5e327d7db67112ebbc93b4f744133eda2c1743dbb0a990c61a8007823ef","86c73f2ee1752bac8eeeece234fd05dfcf0637a4fbd8032e4f5f43102faa8eec","42fad1f540271e35ca37cecda12c4ce2eef27f0f5cf0f8dd761d723c744d3159","ff3743a5de32bee10906aff63d1de726f6a7fd6ee2da4b8229054dfa69de2c34","83acd370f7f84f203e71ebba33ba61b7f1291ca027d7f9a662c6307d74e4ac22","1445cec898f90bdd18b2949b9590b3c012f5b7e1804e6e329fb0fe053946d5ec","0e5318ec2275d8da858b541920d9306650ae6ac8012f0e872fe66eb50321a669","cf530297c3fb3a92ec9591dd4fa229d58b5981e45fe6702a0bd2bea53a5e59be","c1f6f7d08d42148ddfe164d36d7aba91f467dbcb3caa715966ff95f55048b3a4","f4e9bf9103191ef3b3612d3ec0044ca4044ca5be27711fe648ada06fad4bcc85","0c1ee27b8f6a00097c2d6d91a21ee4d096ab52c1e28350f6362542b55380059a","7677d5b0db9e020d3017720f853ba18f415219fb3a9597343b1b1012cfd699f7","bc1c6bc119c1784b1a2be6d9c47addec0d83ef0d52c8fbe1f14a51b4dfffc675","52cf2ce99c2a23de70225e252e9822a22b4e0adb82643ab0b710858810e00bf1","770625067bb27a20b9826255a8d47b6b5b0a2d3dfcbd21f89904c731f671ba77","d1ed6765f4d7906a05968fb5cd6d1db8afa14dbe512a4884e8ea5c0f5e142c80","799c0f1b07c092626cf1efd71d459997635911bb5f7fc1196efe449bba87e965","2a184e4462b9914a30b1b5c41cf80c6d3428f17b20d3afb711fff3f0644001fd","9eabde32a3aa5d80de34af2c2206cdc3ee094c6504a8d0c2d6d20c7c179503cc","397c8051b6cfcb48aa22656f0faca2553c5f56187262135162ee79d2b2f6c966","a8ead142e0c87dcd5dc130eba1f8eeed506b08952d905c47621dc2f583b1bff9","a02f10ea5f73130efca046429254a4e3c06b5475baecc8f7b99a0014731be8b3","c2576a4083232b0e2d9bd06875dd43d371dee2e090325a9eac0133fd5650c1cb","4c9a0564bb317349de6a24eb4efea8bb79898fa72ad63a1809165f5bd42970dd","f40ac11d8859092d20f953aae14ba967282c3bb056431a37fced1866ec7a2681","cc11e9e79d4746cc59e0e17473a59d6f104692fd0eeea1bdb2e206eabed83b03","b444a410d34fb5e98aa5ee2b381362044f4884652e8bc8a11c8fe14bbd85518e","c35808c1f5e16d2c571aa65067e3cb95afeff843b259ecfa2fc107a9519b5392","14d5dc055143e941c8743c6a21fa459f961cbc3deedf1bfe47b11587ca4b3ef5","a3ad4e1fc542751005267d50a6298e6765928c0c3a8dce1572f2ba6ca518661c","f237e7c97a3a89f4591afd49ecb3bd8d14f51a1c4adc8fcae3430febedff5eb6","3ffdfbec93b7aed71082af62b8c3e0cc71261cc68d796665faa1e91604fbae8f","662201f943ed45b1ad600d03a90dffe20841e725203ced8b708c91fcd7f9379a","c9ef74c64ed051ea5b958621e7fb853fe3b56e8787c1587aefc6ea988b3c7e79","2462ccfac5f3375794b861abaa81da380f1bbd9401de59ffa43119a0b644253d","34baf65cfee92f110d6653322e2120c2d368ee64b3c7981dff08ed105c4f19b0","7d8ddf0f021c53099e34ee831a06c394d50371816caa98684812f089b4c6b3d4","c6c4fea9acc55d5e38ff2b70d57ab0b5cdbd08f8bc5d7a226e322cea128c5b57","9ad8802fd8850d22277c08f5653e69e551a2e003a376ce0afb3fe28474b51d65","fdfbe321c556c39a2ecf791d537b999591d0849e971dd938d88f460fea0186f6","105b9a2234dcb06ae922f2cd8297201136d416503ff7d16c72bfc8791e9895c1"],"root":[72],"options":{"allowImportingTsExtensions":true,"composite":true,"declaration":true,"declarationDir":"../../dts","declarationMap":true,"emitDeclarationOnly":true,"esModuleInterop":true,"module":200,"noImplicitAny":true,"noImplicitThis":true,"rootDir":"../..","skipLibCheck":true,"strictBindCallApply":true,"target":99},"fileIdsList":[[179],[78,80],[77,78,79],[133,134,171,172],[174],[175],[181,184],[120,171,177,183],[178,182],[180],[84],[120],[121,126,155],[122,133,134,141,152,163],[122,123,133,141],[124,164],[125,126,134,142],[126,152,160],[127,129,133,141],[120,128],[129,130],[133],[131,133],[120,133],[133,134,135,152,163],[133,134,135,148,152,155],[118,121,168],[129,133,136,141,152,163],[133,134,136,137,141,152,160,163],[136,138,152,160,163],[84,85,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170],[133,139],[140,163,168],[129,133,141,152],[142],[143],[120,144],[145,162,168],[146],[147],[133,148,149],[148,150,164,166],[121,133,152,153,154,155],[121,152,154],[152,153],[155],[156],[120,152],[133,158,159],[158,159],[126,141,152,160],[161],[141,162],[121,136,147,163],[126,164],[152,165],[140,166],[167],[121,126,133,135,144,152,163,166,168],[152,169],[191,230],[191,215,230],[230],[191],[191,216,230],[191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229],[216,230],[233],[181],[95,99,163],[95,152,163],[90],[92,95,160,163],[141,160],[171],[90,171],[92,95,141,163],[87,88,91,94,121,133,152,163],[87,93],[91,95,121,155,163,171],[121,171],[111,121,171],[89,90,171],[95],[89,90,91,92,93,94,95,96,97,99,100,101,102,103,104,105,106,107,108,109,110,112,113,114,115,116,117],[95,102,103],[93,95,103,104],[94],[87,90,95],[95,99,103,104],[99],[93,95,98,163],[87,92,93,95,99,102],[121,152],[90,95,111,121,168,171]],"referencedMap":[[180,1],[81,2],[80,3],[173,4],[175,5],[176,6],[186,7],[184,8],[183,9],[185,10],[84,11],[85,11],[120,12],[121,13],[122,14],[123,15],[124,16],[125,17],[126,18],[127,19],[128,20],[129,21],[130,21],[132,22],[131,23],[133,24],[134,25],[135,26],[119,27],[136,28],[137,29],[138,30],[171,31],[139,32],[140,33],[141,34],[142,35],[143,36],[144,37],[145,38],[146,39],[147,40],[148,41],[149,41],[150,42],[152,43],[154,44],[153,45],[155,46],[156,47],[157,48],[158,49],[159,50],[160,51],[161,52],[162,53],[163,54],[164,55],[165,56],[166,57],[167,58],[168,59],[169,60],[215,61],[216,62],[191,63],[194,63],[213,61],[214,61],[204,61],[203,64],[201,61],[196,61],[209,61],[207,61],[211,61],[195,61],[208,61],[212,61],[197,61],[198,61],[210,61],[192,61],[199,61],[200,61],[202,61],[206,61],[217,65],[205,61],[193,61],[230,66],[224,65],[226,67],[225,65],[218,65],[219,65],[221,65],[223,65],[227,67],[228,67],[220,67],[222,67],[234,68],[182,69],[181,10],[102,70],[109,71],[101,70],[116,72],[93,73],[92,74],[115,75],[110,76],[113,77],[95,78],[94,79],[90,80],[89,81],[112,82],[91,83],[96,84],[100,84],[118,85],[117,84],[104,86],[105,87],[107,88],[103,89],[106,90],[111,75],[98,91],[99,92],[108,93],[88,94],[114,95]]},"version":"5.5.3"} \ No newline at end of file diff --git a/node_modules/@babel/core/LICENSE b/node_modules/@babel/core/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/core/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/core/README.md b/node_modules/@babel/core/README.md new file mode 100644 index 0000000..2903543 --- /dev/null +++ b/node_modules/@babel/core/README.md @@ -0,0 +1,19 @@ +# @babel/core + +> Babel compiler core. + +See our website [@babel/core](https://babeljs.io/docs/babel-core) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20core%22+is%3Aopen) associated with this package. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/core +``` + +or using yarn: + +```sh +yarn add @babel/core --dev +``` diff --git a/node_modules/@babel/core/cjs-proxy.cjs b/node_modules/@babel/core/cjs-proxy.cjs new file mode 100644 index 0000000..17dac4a --- /dev/null +++ b/node_modules/@babel/core/cjs-proxy.cjs @@ -0,0 +1,59 @@ +"use strict"; + +const babelP = import("./lib/index.js"); +let babel = null; +Object.defineProperty(exports, "__ initialize @babel/core cjs proxy __", { + set(val) { + babel = val; + }, +}); + +exports.version = require("./package.json").version; + +const functionNames = [ + "createConfigItem", + "loadPartialConfig", + "loadOptions", + "transform", + "transformFile", + "transformFromAst", + "parse", +]; +const propertyNames = [ + "buildExternalHelpers", + "types", + "tokTypes", + "traverse", + "template", +]; + +for (const name of functionNames) { + exports[name] = function (...args) { + babelP.then(babel => { + babel[name](...args); + }); + }; + exports[`${name}Async`] = function (...args) { + return babelP.then(babel => babel[`${name}Async`](...args)); + }; + exports[`${name}Sync`] = function (...args) { + if (!babel) throw notLoadedError(`${name}Sync`, "callable"); + return babel[`${name}Sync`](...args); + }; +} + +for (const name of propertyNames) { + Object.defineProperty(exports, name, { + get() { + if (!babel) throw notLoadedError(name, "accessible"); + return babel[name]; + }, + }); +} + +function notLoadedError(name, keyword) { + return new Error( + `The \`${name}\` export of @babel/core is only ${keyword}` + + ` from the CommonJS version after that the ESM version is loaded.` + ); +} diff --git a/node_modules/@babel/core/lib/config/cache-contexts.js b/node_modules/@babel/core/lib/config/cache-contexts.js new file mode 100644 index 0000000..d7c0912 --- /dev/null +++ b/node_modules/@babel/core/lib/config/cache-contexts.js @@ -0,0 +1,3 @@ +0 && 0; + +//# sourceMappingURL=cache-contexts.js.map diff --git a/node_modules/@babel/core/lib/config/cache-contexts.js.map b/node_modules/@babel/core/lib/config/cache-contexts.js.map new file mode 100644 index 0000000..9fa85d5 --- /dev/null +++ b/node_modules/@babel/core/lib/config/cache-contexts.js.map @@ -0,0 +1 @@ +{"version":3,"names":[],"sources":["../../src/config/cache-contexts.ts"],"sourcesContent":["import type { Targets } from \"@babel/helper-compilation-targets\";\n\nimport type { ConfigContext } from \"./config-chain.ts\";\nimport type { CallerMetadata } from \"./validation/options.ts\";\n\nexport type { ConfigContext as FullConfig };\n\nexport type FullPreset = {\n targets: Targets;\n} & ConfigContext;\nexport type FullPlugin = {\n assumptions: { [name: string]: boolean };\n} & FullPreset;\n\n// Context not including filename since it is used in places that cannot\n// process 'ignore'/'only' and other filename-based logic.\nexport type SimpleConfig = {\n envName: string;\n caller: CallerMetadata | undefined;\n};\nexport type SimplePreset = {\n targets: Targets;\n} & SimpleConfig;\nexport type SimplePlugin = {\n assumptions: {\n [name: string]: boolean;\n };\n} & SimplePreset;\n"],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/caching.js b/node_modules/@babel/core/lib/config/caching.js new file mode 100644 index 0000000..344c839 --- /dev/null +++ b/node_modules/@babel/core/lib/config/caching.js @@ -0,0 +1,261 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.assertSimpleType = assertSimpleType; +exports.makeStrongCache = makeStrongCache; +exports.makeStrongCacheSync = makeStrongCacheSync; +exports.makeWeakCache = makeWeakCache; +exports.makeWeakCacheSync = makeWeakCacheSync; +function _gensync() { + const data = require("gensync"); + _gensync = function () { + return data; + }; + return data; +} +var _async = require("../gensync-utils/async.js"); +var _util = require("./util.js"); +const synchronize = gen => { + return _gensync()(gen).sync; +}; +function* genTrue() { + return true; +} +function makeWeakCache(handler) { + return makeCachedFunction(WeakMap, handler); +} +function makeWeakCacheSync(handler) { + return synchronize(makeWeakCache(handler)); +} +function makeStrongCache(handler) { + return makeCachedFunction(Map, handler); +} +function makeStrongCacheSync(handler) { + return synchronize(makeStrongCache(handler)); +} +function makeCachedFunction(CallCache, handler) { + const callCacheSync = new CallCache(); + const callCacheAsync = new CallCache(); + const futureCache = new CallCache(); + return function* cachedFunction(arg, data) { + const asyncContext = yield* (0, _async.isAsync)(); + const callCache = asyncContext ? callCacheAsync : callCacheSync; + const cached = yield* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data); + if (cached.valid) return cached.value; + const cache = new CacheConfigurator(data); + const handlerResult = handler(arg, cache); + let finishLock; + let value; + if ((0, _util.isIterableIterator)(handlerResult)) { + value = yield* (0, _async.onFirstPause)(handlerResult, () => { + finishLock = setupAsyncLocks(cache, futureCache, arg); + }); + } else { + value = handlerResult; + } + updateFunctionCache(callCache, cache, arg, value); + if (finishLock) { + futureCache.delete(arg); + finishLock.release(value); + } + return value; + }; +} +function* getCachedValue(cache, arg, data) { + const cachedValue = cache.get(arg); + if (cachedValue) { + for (const { + value, + valid + } of cachedValue) { + if (yield* valid(data)) return { + valid: true, + value + }; + } + } + return { + valid: false, + value: null + }; +} +function* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data) { + const cached = yield* getCachedValue(callCache, arg, data); + if (cached.valid) { + return cached; + } + if (asyncContext) { + const cached = yield* getCachedValue(futureCache, arg, data); + if (cached.valid) { + const value = yield* (0, _async.waitFor)(cached.value.promise); + return { + valid: true, + value + }; + } + } + return { + valid: false, + value: null + }; +} +function setupAsyncLocks(config, futureCache, arg) { + const finishLock = new Lock(); + updateFunctionCache(futureCache, config, arg, finishLock); + return finishLock; +} +function updateFunctionCache(cache, config, arg, value) { + if (!config.configured()) config.forever(); + let cachedValue = cache.get(arg); + config.deactivate(); + switch (config.mode()) { + case "forever": + cachedValue = [{ + value, + valid: genTrue + }]; + cache.set(arg, cachedValue); + break; + case "invalidate": + cachedValue = [{ + value, + valid: config.validator() + }]; + cache.set(arg, cachedValue); + break; + case "valid": + if (cachedValue) { + cachedValue.push({ + value, + valid: config.validator() + }); + } else { + cachedValue = [{ + value, + valid: config.validator() + }]; + cache.set(arg, cachedValue); + } + } +} +class CacheConfigurator { + constructor(data) { + this._active = true; + this._never = false; + this._forever = false; + this._invalidate = false; + this._configured = false; + this._pairs = []; + this._data = void 0; + this._data = data; + } + simple() { + return makeSimpleConfigurator(this); + } + mode() { + if (this._never) return "never"; + if (this._forever) return "forever"; + if (this._invalidate) return "invalidate"; + return "valid"; + } + forever() { + if (!this._active) { + throw new Error("Cannot change caching after evaluation has completed."); + } + if (this._never) { + throw new Error("Caching has already been configured with .never()"); + } + this._forever = true; + this._configured = true; + } + never() { + if (!this._active) { + throw new Error("Cannot change caching after evaluation has completed."); + } + if (this._forever) { + throw new Error("Caching has already been configured with .forever()"); + } + this._never = true; + this._configured = true; + } + using(handler) { + if (!this._active) { + throw new Error("Cannot change caching after evaluation has completed."); + } + if (this._never || this._forever) { + throw new Error("Caching has already been configured with .never or .forever()"); + } + this._configured = true; + const key = handler(this._data); + const fn = (0, _async.maybeAsync)(handler, `You appear to be using an async cache handler, but Babel has been called synchronously`); + if ((0, _async.isThenable)(key)) { + return key.then(key => { + this._pairs.push([key, fn]); + return key; + }); + } + this._pairs.push([key, fn]); + return key; + } + invalidate(handler) { + this._invalidate = true; + return this.using(handler); + } + validator() { + const pairs = this._pairs; + return function* (data) { + for (const [key, fn] of pairs) { + if (key !== (yield* fn(data))) return false; + } + return true; + }; + } + deactivate() { + this._active = false; + } + configured() { + return this._configured; + } +} +function makeSimpleConfigurator(cache) { + function cacheFn(val) { + if (typeof val === "boolean") { + if (val) cache.forever();else cache.never(); + return; + } + return cache.using(() => assertSimpleType(val())); + } + cacheFn.forever = () => cache.forever(); + cacheFn.never = () => cache.never(); + cacheFn.using = cb => cache.using(() => assertSimpleType(cb())); + cacheFn.invalidate = cb => cache.invalidate(() => assertSimpleType(cb())); + return cacheFn; +} +function assertSimpleType(value) { + if ((0, _async.isThenable)(value)) { + throw new Error(`You appear to be using an async cache handler, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously handle your caching logic.`); + } + if (value != null && typeof value !== "string" && typeof value !== "boolean" && typeof value !== "number") { + throw new Error("Cache keys must be either string, boolean, number, null, or undefined."); + } + return value; +} +class Lock { + constructor() { + this.released = false; + this.promise = void 0; + this._resolve = void 0; + this.promise = new Promise(resolve => { + this._resolve = resolve; + }); + } + release(value) { + this.released = true; + this._resolve(value); + } +} +0 && 0; + +//# sourceMappingURL=caching.js.map diff --git a/node_modules/@babel/core/lib/config/caching.js.map b/node_modules/@babel/core/lib/config/caching.js.map new file mode 100644 index 0000000..174ac86 --- /dev/null +++ b/node_modules/@babel/core/lib/config/caching.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_gensync","data","require","_async","_util","synchronize","gen","gensync","sync","genTrue","makeWeakCache","handler","makeCachedFunction","WeakMap","makeWeakCacheSync","makeStrongCache","Map","makeStrongCacheSync","CallCache","callCacheSync","callCacheAsync","futureCache","cachedFunction","arg","asyncContext","isAsync","callCache","cached","getCachedValueOrWait","valid","value","cache","CacheConfigurator","handlerResult","finishLock","isIterableIterator","onFirstPause","setupAsyncLocks","updateFunctionCache","delete","release","getCachedValue","cachedValue","get","waitFor","promise","config","Lock","configured","forever","deactivate","mode","set","validator","push","constructor","_active","_never","_forever","_invalidate","_configured","_pairs","_data","simple","makeSimpleConfigurator","Error","never","using","key","fn","maybeAsync","isThenable","then","invalidate","pairs","cacheFn","val","assertSimpleType","cb","released","_resolve","Promise","resolve"],"sources":["../../src/config/caching.ts"],"sourcesContent":["import gensync from \"gensync\";\nimport type { Handler } from \"gensync\";\nimport {\n maybeAsync,\n isAsync,\n onFirstPause,\n waitFor,\n isThenable,\n} from \"../gensync-utils/async.ts\";\nimport { isIterableIterator } from \"./util.ts\";\n\nexport type { CacheConfigurator };\n\nexport type SimpleCacheConfigurator = {\n (forever: boolean): void;\n (handler: () => T): T;\n\n forever: () => void;\n never: () => void;\n using: (handler: () => T) => T;\n invalidate: (handler: () => T) => T;\n};\n\nexport type CacheEntry = Array<{\n value: ResultT;\n valid: (channel: SideChannel) => Handler;\n}>;\n\nconst synchronize = (\n gen: (...args: ArgsT) => Handler,\n): ((...args: ArgsT) => ResultT) => {\n return gensync(gen).sync;\n};\n\n// eslint-disable-next-line require-yield\nfunction* genTrue() {\n return true;\n}\n\nexport function makeWeakCache(\n handler: (\n arg: ArgT,\n cache: CacheConfigurator,\n ) => Handler | ResultT,\n): (arg: ArgT, data: SideChannel) => Handler {\n return makeCachedFunction(WeakMap, handler);\n}\n\nexport function makeWeakCacheSync(\n handler: (arg: ArgT, cache?: CacheConfigurator) => ResultT,\n): (arg: ArgT, data?: SideChannel) => ResultT {\n return synchronize<[ArgT, SideChannel], ResultT>(\n makeWeakCache(handler),\n );\n}\n\nexport function makeStrongCache(\n handler: (\n arg: ArgT,\n cache: CacheConfigurator,\n ) => Handler | ResultT,\n): (arg: ArgT, data: SideChannel) => Handler {\n return makeCachedFunction(Map, handler);\n}\n\nexport function makeStrongCacheSync(\n handler: (arg: ArgT, cache?: CacheConfigurator) => ResultT,\n): (arg: ArgT, data?: SideChannel) => ResultT {\n return synchronize<[ArgT, SideChannel], ResultT>(\n makeStrongCache(handler),\n );\n}\n\n/* NOTE: Part of the logic explained in this comment is explained in the\n * getCachedValueOrWait and setupAsyncLocks functions.\n *\n * > There are only two hard things in Computer Science: cache invalidation and naming things.\n * > -- Phil Karlton\n *\n * I don't know if Phil was also thinking about handling a cache whose invalidation function is\n * defined asynchronously is considered, but it is REALLY hard to do correctly.\n *\n * The implemented logic (only when gensync is run asynchronously) is the following:\n * 1. If there is a valid cache associated to the current \"arg\" parameter,\n * a. RETURN the cached value\n * 3. If there is a FinishLock associated to the current \"arg\" parameter representing a valid cache,\n * a. Wait for that lock to be released\n * b. RETURN the value associated with that lock\n * 5. Start executing the function to be cached\n * a. If it pauses on a promise, then\n * i. Let FinishLock be a new lock\n * ii. Store FinishLock as associated to the current \"arg\" parameter\n * iii. Wait for the function to finish executing\n * iv. Release FinishLock\n * v. Send the function result to anyone waiting on FinishLock\n * 6. Store the result in the cache\n * 7. RETURN the result\n */\nfunction makeCachedFunction(\n CallCache: new () => CacheMap,\n handler: (\n arg: ArgT,\n cache: CacheConfigurator,\n ) => Handler | ResultT,\n): (arg: ArgT, data: SideChannel) => Handler {\n const callCacheSync = new CallCache();\n const callCacheAsync = new CallCache();\n const futureCache = new CallCache>();\n\n return function* cachedFunction(arg: ArgT, data: SideChannel) {\n const asyncContext = yield* isAsync();\n const callCache = asyncContext ? callCacheAsync : callCacheSync;\n\n const cached = yield* getCachedValueOrWait(\n asyncContext,\n callCache,\n futureCache,\n arg,\n data,\n );\n if (cached.valid) return cached.value;\n\n const cache = new CacheConfigurator(data);\n\n const handlerResult: Handler | ResultT = handler(arg, cache);\n\n let finishLock: Lock;\n let value: ResultT;\n\n if (isIterableIterator(handlerResult)) {\n value = yield* onFirstPause(handlerResult, () => {\n finishLock = setupAsyncLocks(cache, futureCache, arg);\n });\n } else {\n value = handlerResult;\n }\n\n updateFunctionCache(callCache, cache, arg, value);\n\n if (finishLock) {\n futureCache.delete(arg);\n finishLock.release(value);\n }\n\n return value;\n };\n}\n\ntype CacheMap =\n | Map>\n // @ts-expect-error todo(flow->ts): add `extends object` constraint to ArgT\n | WeakMap>;\n\nfunction* getCachedValue(\n cache: CacheMap,\n arg: ArgT,\n data: SideChannel,\n): Handler<{ valid: true; value: ResultT } | { valid: false; value: null }> {\n const cachedValue: CacheEntry | void = cache.get(arg);\n\n if (cachedValue) {\n for (const { value, valid } of cachedValue) {\n if (yield* valid(data)) return { valid: true, value };\n }\n }\n\n return { valid: false, value: null };\n}\n\nfunction* getCachedValueOrWait(\n asyncContext: boolean,\n callCache: CacheMap,\n futureCache: CacheMap, SideChannel>,\n arg: ArgT,\n data: SideChannel,\n): Handler<{ valid: true; value: ResultT } | { valid: false; value: null }> {\n const cached = yield* getCachedValue(callCache, arg, data);\n if (cached.valid) {\n return cached;\n }\n\n if (asyncContext) {\n const cached = yield* getCachedValue(futureCache, arg, data);\n if (cached.valid) {\n const value = yield* waitFor(cached.value.promise);\n return { valid: true, value };\n }\n }\n\n return { valid: false, value: null };\n}\n\nfunction setupAsyncLocks(\n config: CacheConfigurator,\n futureCache: CacheMap, SideChannel>,\n arg: ArgT,\n): Lock {\n const finishLock = new Lock();\n\n updateFunctionCache(futureCache, config, arg, finishLock);\n\n return finishLock;\n}\n\nfunction updateFunctionCache<\n ArgT,\n ResultT,\n SideChannel,\n Cache extends CacheMap,\n>(\n cache: Cache,\n config: CacheConfigurator,\n arg: ArgT,\n value: ResultT,\n) {\n if (!config.configured()) config.forever();\n\n let cachedValue: CacheEntry | void = cache.get(arg);\n\n config.deactivate();\n\n switch (config.mode()) {\n case \"forever\":\n cachedValue = [{ value, valid: genTrue }];\n cache.set(arg, cachedValue);\n break;\n case \"invalidate\":\n cachedValue = [{ value, valid: config.validator() }];\n cache.set(arg, cachedValue);\n break;\n case \"valid\":\n if (cachedValue) {\n cachedValue.push({ value, valid: config.validator() });\n } else {\n cachedValue = [{ value, valid: config.validator() }];\n cache.set(arg, cachedValue);\n }\n }\n}\n\nclass CacheConfigurator {\n _active: boolean = true;\n _never: boolean = false;\n _forever: boolean = false;\n _invalidate: boolean = false;\n\n _configured: boolean = false;\n\n _pairs: Array<\n [cachedValue: unknown, handler: (data: SideChannel) => Handler]\n > = [];\n\n _data: SideChannel;\n\n constructor(data: SideChannel) {\n this._data = data;\n }\n\n simple() {\n return makeSimpleConfigurator(this);\n }\n\n mode() {\n if (this._never) return \"never\";\n if (this._forever) return \"forever\";\n if (this._invalidate) return \"invalidate\";\n return \"valid\";\n }\n\n forever() {\n if (!this._active) {\n throw new Error(\"Cannot change caching after evaluation has completed.\");\n }\n if (this._never) {\n throw new Error(\"Caching has already been configured with .never()\");\n }\n this._forever = true;\n this._configured = true;\n }\n\n never() {\n if (!this._active) {\n throw new Error(\"Cannot change caching after evaluation has completed.\");\n }\n if (this._forever) {\n throw new Error(\"Caching has already been configured with .forever()\");\n }\n this._never = true;\n this._configured = true;\n }\n\n using(handler: (data: SideChannel) => T): T {\n if (!this._active) {\n throw new Error(\"Cannot change caching after evaluation has completed.\");\n }\n if (this._never || this._forever) {\n throw new Error(\n \"Caching has already been configured with .never or .forever()\",\n );\n }\n this._configured = true;\n\n const key = handler(this._data);\n\n const fn = maybeAsync(\n handler,\n `You appear to be using an async cache handler, but Babel has been called synchronously`,\n );\n\n if (isThenable(key)) {\n // @ts-expect-error todo(flow->ts): improve function return type annotation\n return key.then((key: unknown) => {\n this._pairs.push([key, fn]);\n return key;\n });\n }\n\n this._pairs.push([key, fn]);\n return key;\n }\n\n invalidate(handler: (data: SideChannel) => T): T {\n this._invalidate = true;\n return this.using(handler);\n }\n\n validator(): (data: SideChannel) => Handler {\n const pairs = this._pairs;\n return function* (data: SideChannel) {\n for (const [key, fn] of pairs) {\n if (key !== (yield* fn(data))) return false;\n }\n return true;\n };\n }\n\n deactivate() {\n this._active = false;\n }\n\n configured() {\n return this._configured;\n }\n}\n\nfunction makeSimpleConfigurator(\n cache: CacheConfigurator,\n): SimpleCacheConfigurator {\n function cacheFn(val: any) {\n if (typeof val === \"boolean\") {\n if (val) cache.forever();\n else cache.never();\n return;\n }\n\n return cache.using(() => assertSimpleType(val()));\n }\n cacheFn.forever = () => cache.forever();\n cacheFn.never = () => cache.never();\n cacheFn.using = (cb: () => SimpleType) =>\n cache.using(() => assertSimpleType(cb()));\n cacheFn.invalidate = (cb: () => SimpleType) =>\n cache.invalidate(() => assertSimpleType(cb()));\n\n return cacheFn as any;\n}\n\n// Types are limited here so that in the future these values can be used\n// as part of Babel's caching logic.\nexport type SimpleType =\n | string\n | boolean\n | number\n | null\n | void\n | Promise;\nexport function assertSimpleType(value: unknown): SimpleType {\n if (isThenable(value)) {\n throw new Error(\n `You appear to be using an async cache handler, ` +\n `which your current version of Babel does not support. ` +\n `We may add support for this in the future, ` +\n `but if you're on the most recent version of @babel/core and still ` +\n `seeing this error, then you'll need to synchronously handle your caching logic.`,\n );\n }\n\n if (\n value != null &&\n typeof value !== \"string\" &&\n typeof value !== \"boolean\" &&\n typeof value !== \"number\"\n ) {\n throw new Error(\n \"Cache keys must be either string, boolean, number, null, or undefined.\",\n );\n }\n // @ts-expect-error Type 'unknown' is not assignable to type 'SimpleType'. This can be removed\n // when strictNullCheck is enabled\n return value;\n}\n\nclass Lock {\n released: boolean = false;\n promise: Promise;\n _resolve: (value: T) => void;\n\n constructor() {\n this.promise = new Promise(resolve => {\n this._resolve = resolve;\n });\n }\n\n release(value: T) {\n this.released = true;\n this._resolve(value);\n }\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAAA,SAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,QAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,IAAAE,MAAA,GAAAD,OAAA;AAOA,IAAAE,KAAA,GAAAF,OAAA;AAmBA,MAAMG,WAAW,GACfC,GAAyC,IACP;EAClC,OAAOC,SAAMA,CAAC,CAACD,GAAG,CAAC,CAACE,IAAI;AAC1B,CAAC;AAGD,UAAUC,OAAOA,CAAA,EAAG;EAClB,OAAO,IAAI;AACb;AAEO,SAASC,aAAaA,CAC3BC,OAG+B,EACqB;EACpD,OAAOC,kBAAkB,CAA6BC,OAAO,EAAEF,OAAO,CAAC;AACzE;AAEO,SAASG,iBAAiBA,CAC/BH,OAAuE,EAC3B;EAC5C,OAAON,WAAW,CAChBK,aAAa,CAA6BC,OAAO,CACnD,CAAC;AACH;AAEO,SAASI,eAAeA,CAC7BJ,OAG+B,EACqB;EACpD,OAAOC,kBAAkB,CAA6BI,GAAG,EAAEL,OAAO,CAAC;AACrE;AAEO,SAASM,mBAAmBA,CACjCN,OAAuE,EAC3B;EAC5C,OAAON,WAAW,CAChBU,eAAe,CAA6BJ,OAAO,CACrD,CAAC;AACH;AA2BA,SAASC,kBAAkBA,CACzBM,SAAgE,EAChEP,OAG+B,EACqB;EACpD,MAAMQ,aAAa,GAAG,IAAID,SAAS,CAAU,CAAC;EAC9C,MAAME,cAAc,GAAG,IAAIF,SAAS,CAAU,CAAC;EAC/C,MAAMG,WAAW,GAAG,IAAIH,SAAS,CAAgB,CAAC;EAElD,OAAO,UAAUI,cAAcA,CAACC,GAAS,EAAEtB,IAAiB,EAAE;IAC5D,MAAMuB,YAAY,GAAG,OA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C,KAAK,CAAC,CAAC;EACnCS,OAAO,CAACR,KAAK,GAAIW,EAAoB,IACnC/C,KAAK,CAACoC,KAAK,CAAC,MAAMU,gBAAgB,CAACC,EAAE,CAAC,CAAC,CAAC,CAAC;EAC3CH,OAAO,CAACF,UAAU,GAAIK,EAAoB,IACxC/C,KAAK,CAAC0C,UAAU,CAAC,MAAMI,gBAAgB,CAACC,EAAE,CAAC,CAAC,CAAC,CAAC;EAEhD,OAAOH,OAAO;AAChB;AAWO,SAASE,gBAAgBA,CAAC/C,KAAc,EAAc;EAC3D,IAAI,IAAAyC,iBAAU,EAACzC,KAAK,CAAC,EAAE;IACrB,MAAM,IAAImC,KAAK,CACb,iDAAiD,GAC/C,wDAAwD,GACxD,6CAA6C,GAC7C,oEAAoE,GACpE,iFACJ,CAAC;EACH;EAEA,IACEnC,KAAK,IAAI,IAAI,IACb,OAAOA,KAAK,KAAK,QAAQ,IACzB,OAAOA,KAAK,KAAK,SAAS,IAC1B,OAAOA,KAAK,KAAK,QAAQ,EACzB;IACA,MAAM,IAAImC,KAAK,CACb,wEACF,CAAC;EACH;EAGA,OAAOnC,KAAK;AACd;AAEA,MAAMiB,IAAI,CAAI;EAKZQ,WAAWA,CAAA,EAAG;IAAA,KAJdwB,QAAQ,GAAY,KAAK;IAAA,KACzBlC,OAAO;IAAA,KACPmC,QAAQ;IAGN,IAAI,CAACnC,OAAO,GAAG,IAAIoC,OAAO,CAACC,OAAO,IAAI;MACpC,IAAI,CAACF,QAAQ,GAAGE,OAAO;IACzB,CAAC,CAAC;EACJ;EAEA1C,OAAOA,CAACV,KAAQ,EAAE;IAChB,IAAI,CAACiD,QAAQ,GAAG,IAAI;IACpB,IAAI,CAACC,QAAQ,CAAClD,KAAK,CAAC;EACtB;AACF;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/config-chain.js b/node_modules/@babel/core/lib/config/config-chain.js new file mode 100644 index 0000000..591de0c --- /dev/null +++ b/node_modules/@babel/core/lib/config/config-chain.js @@ -0,0 +1,469 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.buildPresetChain = buildPresetChain; +exports.buildPresetChainWalker = void 0; +exports.buildRootChain = buildRootChain; +function _path() { + const data = require("path"); + _path = function () { + return data; + }; + return data; +} +function _debug() { + const data = require("debug"); + _debug = function () { + return data; + }; + return data; +} +var _options = require("./validation/options.js"); +var _patternToRegex = require("./pattern-to-regex.js"); +var _printer = require("./printer.js"); +var _rewriteStackTrace = require("../errors/rewrite-stack-trace.js"); +var _configError = require("../errors/config-error.js"); +var _index = require("./files/index.js"); +var _caching = require("./caching.js"); +var _configDescriptors = require("./config-descriptors.js"); +const debug = _debug()("babel:config:config-chain"); +function* buildPresetChain(arg, context) { + const chain = yield* buildPresetChainWalker(arg, context); + if (!chain) return null; + return { + plugins: dedupDescriptors(chain.plugins), + presets: dedupDescriptors(chain.presets), + options: chain.options.map(o => normalizeOptions(o)), + files: new Set() + }; +} +const buildPresetChainWalker = exports.buildPresetChainWalker = makeChainWalker({ + root: preset => loadPresetDescriptors(preset), + env: (preset, envName) => loadPresetEnvDescriptors(preset)(envName), + overrides: (preset, index) => loadPresetOverridesDescriptors(preset)(index), + overridesEnv: (preset, index, envName) => loadPresetOverridesEnvDescriptors(preset)(index)(envName), + createLogger: () => () => {} +}); +const loadPresetDescriptors = (0, _caching.makeWeakCacheSync)(preset => buildRootDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors)); +const loadPresetEnvDescriptors = (0, _caching.makeWeakCacheSync)(preset => (0, _caching.makeStrongCacheSync)(envName => buildEnvDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, envName))); +const loadPresetOverridesDescriptors = (0, _caching.makeWeakCacheSync)(preset => (0, _caching.makeStrongCacheSync)(index => buildOverrideDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, index))); +const loadPresetOverridesEnvDescriptors = (0, _caching.makeWeakCacheSync)(preset => (0, _caching.makeStrongCacheSync)(index => (0, _caching.makeStrongCacheSync)(envName => buildOverrideEnvDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, index, envName)))); +function* buildRootChain(opts, context) { + let configReport, babelRcReport; + const programmaticLogger = new _printer.ConfigPrinter(); + const programmaticChain = yield* loadProgrammaticChain({ + options: opts, + dirname: context.cwd + }, context, undefined, programmaticLogger); + if (!programmaticChain) return null; + const programmaticReport = yield* programmaticLogger.output(); + let configFile; + if (typeof opts.configFile === "string") { + configFile = yield* (0, _index.loadConfig)(opts.configFile, context.cwd, context.envName, context.caller); + } else if (opts.configFile !== false) { + configFile = yield* (0, _index.findRootConfig)(context.root, context.envName, context.caller); + } + let { + babelrc, + babelrcRoots + } = opts; + let babelrcRootsDirectory = context.cwd; + const configFileChain = emptyChain(); + const configFileLogger = new _printer.ConfigPrinter(); + if (configFile) { + const validatedFile = validateConfigFile(configFile); + const result = yield* loadFileChain(validatedFile, context, undefined, configFileLogger); + if (!result) return null; + configReport = yield* configFileLogger.output(); + if (babelrc === undefined) { + babelrc = validatedFile.options.babelrc; + } + if (babelrcRoots === undefined) { + babelrcRootsDirectory = validatedFile.dirname; + babelrcRoots = validatedFile.options.babelrcRoots; + } + mergeChain(configFileChain, result); + } + let ignoreFile, babelrcFile; + let isIgnored = false; + const fileChain = emptyChain(); + if ((babelrc === true || babelrc === undefined) && typeof context.filename === "string") { + const pkgData = yield* (0, _index.findPackageData)(context.filename); + if (pkgData && babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory)) { + ({ + ignore: ignoreFile, + config: babelrcFile + } = yield* (0, _index.findRelativeConfig)(pkgData, context.envName, context.caller)); + if (ignoreFile) { + fileChain.files.add(ignoreFile.filepath); + } + if (ignoreFile && shouldIgnore(context, ignoreFile.ignore, null, ignoreFile.dirname)) { + isIgnored = true; + } + if (babelrcFile && !isIgnored) { + const validatedFile = validateBabelrcFile(babelrcFile); + const babelrcLogger = new _printer.ConfigPrinter(); + const result = yield* loadFileChain(validatedFile, context, undefined, babelrcLogger); + if (!result) { + isIgnored = true; + } else { + babelRcReport = yield* babelrcLogger.output(); + mergeChain(fileChain, result); + } + } + if (babelrcFile && isIgnored) { + fileChain.files.add(babelrcFile.filepath); + } + } + } + if (context.showConfig) { + console.log(`Babel configs on "${context.filename}" (ascending priority):\n` + [configReport, babelRcReport, programmaticReport].filter(x => !!x).join("\n\n") + "\n-----End Babel configs-----"); + } + const chain = mergeChain(mergeChain(mergeChain(emptyChain(), configFileChain), fileChain), programmaticChain); + return { + plugins: isIgnored ? [] : dedupDescriptors(chain.plugins), + presets: isIgnored ? [] : dedupDescriptors(chain.presets), + options: isIgnored ? [] : chain.options.map(o => normalizeOptions(o)), + fileHandling: isIgnored ? "ignored" : "transpile", + ignore: ignoreFile || undefined, + babelrc: babelrcFile || undefined, + config: configFile || undefined, + files: chain.files + }; +} +function babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory) { + if (typeof babelrcRoots === "boolean") return babelrcRoots; + const absoluteRoot = context.root; + if (babelrcRoots === undefined) { + return pkgData.directories.includes(absoluteRoot); + } + let babelrcPatterns = babelrcRoots; + if (!Array.isArray(babelrcPatterns)) { + babelrcPatterns = [babelrcPatterns]; + } + babelrcPatterns = babelrcPatterns.map(pat => { + return typeof pat === "string" ? _path().resolve(babelrcRootsDirectory, pat) : pat; + }); + if (babelrcPatterns.length === 1 && babelrcPatterns[0] === absoluteRoot) { + return pkgData.directories.includes(absoluteRoot); + } + return babelrcPatterns.some(pat => { + if (typeof pat === "string") { + pat = (0, _patternToRegex.default)(pat, babelrcRootsDirectory); + } + return pkgData.directories.some(directory => { + return matchPattern(pat, babelrcRootsDirectory, directory, context); + }); + }); +} +const validateConfigFile = (0, _caching.makeWeakCacheSync)(file => ({ + filepath: file.filepath, + dirname: file.dirname, + options: (0, _options.validate)("configfile", file.options, file.filepath) +})); +const validateBabelrcFile = (0, _caching.makeWeakCacheSync)(file => ({ + filepath: file.filepath, + dirname: file.dirname, + options: (0, _options.validate)("babelrcfile", file.options, file.filepath) +})); +const validateExtendFile = (0, _caching.makeWeakCacheSync)(file => ({ + filepath: file.filepath, + dirname: file.dirname, + options: (0, _options.validate)("extendsfile", file.options, file.filepath) +})); +const loadProgrammaticChain = makeChainWalker({ + root: input => buildRootDescriptors(input, "base", _configDescriptors.createCachedDescriptors), + env: (input, envName) => buildEnvDescriptors(input, "base", _configDescriptors.createCachedDescriptors, envName), + overrides: (input, index) => buildOverrideDescriptors(input, "base", _configDescriptors.createCachedDescriptors, index), + overridesEnv: (input, index, envName) => buildOverrideEnvDescriptors(input, "base", _configDescriptors.createCachedDescriptors, index, envName), + createLogger: (input, context, baseLogger) => buildProgrammaticLogger(input, context, baseLogger) +}); +const loadFileChainWalker = makeChainWalker({ + root: file => loadFileDescriptors(file), + env: (file, envName) => loadFileEnvDescriptors(file)(envName), + overrides: (file, index) => loadFileOverridesDescriptors(file)(index), + overridesEnv: (file, index, envName) => loadFileOverridesEnvDescriptors(file)(index)(envName), + createLogger: (file, context, baseLogger) => buildFileLogger(file.filepath, context, baseLogger) +}); +function* loadFileChain(input, context, files, baseLogger) { + const chain = yield* loadFileChainWalker(input, context, files, baseLogger); + chain == null || chain.files.add(input.filepath); + return chain; +} +const loadFileDescriptors = (0, _caching.makeWeakCacheSync)(file => buildRootDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors)); +const loadFileEnvDescriptors = (0, _caching.makeWeakCacheSync)(file => (0, _caching.makeStrongCacheSync)(envName => buildEnvDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, envName))); +const loadFileOverridesDescriptors = (0, _caching.makeWeakCacheSync)(file => (0, _caching.makeStrongCacheSync)(index => buildOverrideDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, index))); +const loadFileOverridesEnvDescriptors = (0, _caching.makeWeakCacheSync)(file => (0, _caching.makeStrongCacheSync)(index => (0, _caching.makeStrongCacheSync)(envName => buildOverrideEnvDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, index, envName)))); +function buildFileLogger(filepath, context, baseLogger) { + if (!baseLogger) { + return () => {}; + } + return baseLogger.configure(context.showConfig, _printer.ChainFormatter.Config, { + filepath + }); +} +function buildRootDescriptors({ + dirname, + options +}, alias, descriptors) { + return descriptors(dirname, options, alias); +} +function buildProgrammaticLogger(_, context, baseLogger) { + var _context$caller; + if (!baseLogger) { + return () => {}; + } + return baseLogger.configure(context.showConfig, _printer.ChainFormatter.Programmatic, { + callerName: (_context$caller = context.caller) == null ? void 0 : _context$caller.name + }); +} +function buildEnvDescriptors({ + dirname, + options +}, alias, descriptors, envName) { + var _options$env; + const opts = (_options$env = options.env) == null ? void 0 : _options$env[envName]; + return opts ? descriptors(dirname, opts, `${alias}.env["${envName}"]`) : null; +} +function buildOverrideDescriptors({ + dirname, + options +}, alias, descriptors, index) { + var _options$overrides; + const opts = (_options$overrides = options.overrides) == null ? void 0 : _options$overrides[index]; + if (!opts) throw new Error("Assertion failure - missing override"); + return descriptors(dirname, opts, `${alias}.overrides[${index}]`); +} +function buildOverrideEnvDescriptors({ + dirname, + options +}, alias, descriptors, index, envName) { + var _options$overrides2, _override$env; + const override = (_options$overrides2 = options.overrides) == null ? void 0 : _options$overrides2[index]; + if (!override) throw new Error("Assertion failure - missing override"); + const opts = (_override$env = override.env) == null ? void 0 : _override$env[envName]; + return opts ? descriptors(dirname, opts, `${alias}.overrides[${index}].env["${envName}"]`) : null; +} +function makeChainWalker({ + root, + env, + overrides, + overridesEnv, + createLogger +}) { + return function* chainWalker(input, context, files = new Set(), baseLogger) { + const { + dirname + } = input; + const flattenedConfigs = []; + const rootOpts = root(input); + if (configIsApplicable(rootOpts, dirname, context, input.filepath)) { + flattenedConfigs.push({ + config: rootOpts, + envName: undefined, + index: undefined + }); + const envOpts = env(input, context.envName); + if (envOpts && configIsApplicable(envOpts, dirname, context, input.filepath)) { + flattenedConfigs.push({ + config: envOpts, + envName: context.envName, + index: undefined + }); + } + (rootOpts.options.overrides || []).forEach((_, index) => { + const overrideOps = overrides(input, index); + if (configIsApplicable(overrideOps, dirname, context, input.filepath)) { + flattenedConfigs.push({ + config: overrideOps, + index, + envName: undefined + }); + const overrideEnvOpts = overridesEnv(input, index, context.envName); + if (overrideEnvOpts && configIsApplicable(overrideEnvOpts, dirname, context, input.filepath)) { + flattenedConfigs.push({ + config: overrideEnvOpts, + index, + envName: context.envName + }); + } + } + }); + } + if (flattenedConfigs.some(({ + config: { + options: { + ignore, + only + } + } + }) => shouldIgnore(context, ignore, only, dirname))) { + return null; + } + const chain = emptyChain(); + const logger = createLogger(input, context, baseLogger); + for (const { + config, + index, + envName + } of flattenedConfigs) { + if (!(yield* mergeExtendsChain(chain, config.options, dirname, context, files, baseLogger))) { + return null; + } + logger(config, index, envName); + yield* mergeChainOpts(chain, config); + } + return chain; + }; +} +function* mergeExtendsChain(chain, opts, dirname, context, files, baseLogger) { + if (opts.extends === undefined) return true; + const file = yield* (0, _index.loadConfig)(opts.extends, dirname, context.envName, context.caller); + if (files.has(file)) { + throw new Error(`Configuration cycle detected loading ${file.filepath}.\n` + `File already loaded following the config chain:\n` + Array.from(files, file => ` - ${file.filepath}`).join("\n")); + } + files.add(file); + const fileChain = yield* loadFileChain(validateExtendFile(file), context, files, baseLogger); + files.delete(file); + if (!fileChain) return false; + mergeChain(chain, fileChain); + return true; +} +function mergeChain(target, source) { + target.options.push(...source.options); + target.plugins.push(...source.plugins); + target.presets.push(...source.presets); + for (const file of source.files) { + target.files.add(file); + } + return target; +} +function* mergeChainOpts(target, { + options, + plugins, + presets +}) { + target.options.push(options); + target.plugins.push(...(yield* plugins())); + target.presets.push(...(yield* presets())); + return target; +} +function emptyChain() { + return { + options: [], + presets: [], + plugins: [], + files: new Set() + }; +} +function normalizeOptions(opts) { + const options = Object.assign({}, opts); + delete options.extends; + delete options.env; + delete options.overrides; + delete options.plugins; + delete options.presets; + delete options.passPerPreset; + delete options.ignore; + delete options.only; + delete options.test; + delete options.include; + delete options.exclude; + if (hasOwnProperty.call(options, "sourceMap")) { + options.sourceMaps = options.sourceMap; + delete options.sourceMap; + } + return options; +} +function dedupDescriptors(items) { + const map = new Map(); + const descriptors = []; + for (const item of items) { + if (typeof item.value === "function") { + const fnKey = item.value; + let nameMap = map.get(fnKey); + if (!nameMap) { + nameMap = new Map(); + map.set(fnKey, nameMap); + } + let desc = nameMap.get(item.name); + if (!desc) { + desc = { + value: item + }; + descriptors.push(desc); + if (!item.ownPass) nameMap.set(item.name, desc); + } else { + desc.value = item; + } + } else { + descriptors.push({ + value: item + }); + } + } + return descriptors.reduce((acc, desc) => { + acc.push(desc.value); + return acc; + }, []); +} +function configIsApplicable({ + options +}, dirname, context, configName) { + return (options.test === undefined || configFieldIsApplicable(context, options.test, dirname, configName)) && (options.include === undefined || configFieldIsApplicable(context, options.include, dirname, configName)) && (options.exclude === undefined || !configFieldIsApplicable(context, options.exclude, dirname, configName)); +} +function configFieldIsApplicable(context, test, dirname, configName) { + const patterns = Array.isArray(test) ? test : [test]; + return matchesPatterns(context, patterns, dirname, configName); +} +function ignoreListReplacer(_key, value) { + if (value instanceof RegExp) { + return String(value); + } + return value; +} +function shouldIgnore(context, ignore, only, dirname) { + if (ignore && matchesPatterns(context, ignore, dirname)) { + var _context$filename; + const message = `No config is applied to "${(_context$filename = context.filename) != null ? _context$filename : "(unknown)"}" because it matches one of \`ignore: ${JSON.stringify(ignore, ignoreListReplacer)}\` from "${dirname}"`; + debug(message); + if (context.showConfig) { + console.log(message); + } + return true; + } + if (only && !matchesPatterns(context, only, dirname)) { + var _context$filename2; + const message = `No config is applied to "${(_context$filename2 = context.filename) != null ? _context$filename2 : "(unknown)"}" because it fails to match one of \`only: ${JSON.stringify(only, ignoreListReplacer)}\` from "${dirname}"`; + debug(message); + if (context.showConfig) { + console.log(message); + } + return true; + } + return false; +} +function matchesPatterns(context, patterns, dirname, configName) { + return patterns.some(pattern => matchPattern(pattern, dirname, context.filename, context, configName)); +} +function matchPattern(pattern, dirname, pathToTest, context, configName) { + if (typeof pattern === "function") { + return !!(0, _rewriteStackTrace.endHiddenCallStack)(pattern)(pathToTest, { + dirname, + envName: context.envName, + caller: context.caller + }); + } + if (typeof pathToTest !== "string") { + throw new _configError.default(`Configuration contains string/RegExp pattern, but no filename was passed to Babel`, configName); + } + if (typeof pattern === "string") { + pattern = (0, _patternToRegex.default)(pattern, dirname); + } + return pattern.test(pathToTest); +} +0 && 0; + +//# sourceMappingURL=config-chain.js.map diff --git a/node_modules/@babel/core/lib/config/config-chain.js.map b/node_modules/@babel/core/lib/config/config-chain.js.map new file mode 100644 index 0000000..8e58051 --- /dev/null +++ b/node_modules/@babel/core/lib/config/config-chain.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_path","data","require","_debug","_options","_patternToRegex","_printer","_rewriteStackTrace","_configError","_index","_caching","_configDescriptors","debug","buildDebug","buildPresetChain","arg","context","chain","buildPresetChainWalker","plugins","dedupDescriptors","presets","options","map","o","normalizeOptions","files","Set","exports","makeChainWalker","root","preset","loadPresetDescriptors","env","envName","loadPresetEnvDescriptors","overrides","index","loadPresetOverridesDescriptors","overridesEnv","loadPresetOverridesEnvDescriptors","createLogger","makeWeakCacheSync","buildRootDescriptors","alias","createUncachedDescriptors","makeStrongCacheSync","buildEnvDescriptors","buildOverrideDescriptors","buildOverrideEnvDescriptors","buildRootChain","opts","configReport","babelRcReport","programmaticLogger","ConfigPrinter","programmaticChain","loadProgrammaticChain","dirname","cwd","undefined","programmaticReport","output","configFile","loadConfig","caller","findRootConfig","babelrc","babelrcRoots","babelrcRootsDirectory","configFileChain","emptyChain","configFileLogger","validatedFile","validateConfigFile","result","loadFileChain","mergeChain","ignoreFile","babelrcFile","isIgnored","fileChain","filename","pkgData","findPackageData","babelrcLoadEnabled","ignore","config","findRelativeConfig","add","filepath","shouldIgnore","validateBabelrcFile","babelrcLogger","showConfig","console","log","filter","x","join","fileHandling","absoluteRoot","directories","includes","babelrcPatterns","Array","isArray","pat","path","resolve","length","some","pathPatternToRegex","directory","matchPattern","file","validate","validateExtendFile","input","createCachedDescriptors","baseLogger","buildProgrammaticLogger","loadFileChainWalker","loadFileDescriptors","loadFileEnvDescriptors","loadFileOverridesDescriptors","loadFileOverridesEnvDescriptors","buildFileLogger","configure","ChainFormatter","Config","descriptors","_","_context$caller","Programmatic","callerName","name","_options$env","_options$overrides","Error","_options$overrides2","_override$env","override","chainWalker","flattenedConfigs","rootOpts","configIsApplicable","push","envOpts","forEach","overrideOps","overrideEnvOpts","only","logger","mergeExtendsChain","mergeChainOpts","extends","has","from","delete","target","source","Object","assign","passPerPreset","test","include","exclude","hasOwnProperty","call","sourceMaps","sourceMap","items","Map","item","value","fnKey","nameMap","get","set","desc","ownPass","reduce","acc","configName","configFieldIsApplicable","patterns","matchesPatterns","ignoreListReplacer","_key","RegExp","String","_context$filename","message","JSON","stringify","_context$filename2","pattern","pathToTest","endHiddenCallStack","ConfigError"],"sources":["../../src/config/config-chain.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-use-before-define */\n\nimport path from \"path\";\nimport buildDebug from \"debug\";\nimport type { Handler } from \"gensync\";\nimport { validate } from \"./validation/options.ts\";\nimport type {\n ValidatedOptions,\n IgnoreList,\n ConfigApplicableTest,\n BabelrcSearch,\n CallerMetadata,\n IgnoreItem,\n} from \"./validation/options.ts\";\nimport pathPatternToRegex from \"./pattern-to-regex.ts\";\nimport { ConfigPrinter, ChainFormatter } from \"./printer.ts\";\nimport type { ReadonlyDeepArray } from \"./helpers/deep-array.ts\";\n\nimport { endHiddenCallStack } from \"../errors/rewrite-stack-trace.ts\";\nimport ConfigError from \"../errors/config-error.ts\";\nimport type { PluginAPI, PresetAPI } from \"./helpers/config-api.ts\";\n\nconst debug = buildDebug(\"babel:config:config-chain\");\n\nimport {\n findPackageData,\n findRelativeConfig,\n findRootConfig,\n loadConfig,\n} from \"./files/index.ts\";\nimport type { ConfigFile, IgnoreFile, FilePackageData } from \"./files/index.ts\";\n\nimport { makeWeakCacheSync, makeStrongCacheSync } from \"./caching.ts\";\n\nimport {\n createCachedDescriptors,\n createUncachedDescriptors,\n} from \"./config-descriptors.ts\";\nimport type {\n UnloadedDescriptor,\n OptionsAndDescriptors,\n ValidatedFile,\n} from \"./config-descriptors.ts\";\n\nexport type ConfigChain = {\n plugins: Array>;\n presets: Array>;\n options: Array;\n files: Set;\n};\n\nexport type PresetInstance = {\n options: ValidatedOptions;\n alias: string;\n dirname: string;\n externalDependencies: ReadonlyDeepArray;\n};\n\nexport type ConfigContext = {\n filename: string | undefined;\n cwd: string;\n root: string;\n envName: string;\n caller: CallerMetadata | undefined;\n showConfig: boolean;\n};\n\n/**\n * Build a config chain for a given preset.\n */\nexport function* buildPresetChain(\n arg: PresetInstance,\n context: any,\n): Handler {\n const chain = yield* buildPresetChainWalker(arg, context);\n if (!chain) return null;\n\n return {\n plugins: dedupDescriptors(chain.plugins),\n presets: dedupDescriptors(chain.presets),\n options: chain.options.map(o => normalizeOptions(o)),\n files: new Set(),\n };\n}\n\nexport const buildPresetChainWalker = makeChainWalker({\n root: preset => loadPresetDescriptors(preset),\n env: (preset, envName) => loadPresetEnvDescriptors(preset)(envName),\n overrides: (preset, index) => loadPresetOverridesDescriptors(preset)(index),\n overridesEnv: (preset, index, envName) =>\n loadPresetOverridesEnvDescriptors(preset)(index)(envName),\n createLogger: () => () => {}, // Currently we don't support logging how preset is expanded\n});\nconst loadPresetDescriptors = makeWeakCacheSync((preset: PresetInstance) =>\n buildRootDescriptors(preset, preset.alias, createUncachedDescriptors),\n);\nconst loadPresetEnvDescriptors = makeWeakCacheSync((preset: PresetInstance) =>\n makeStrongCacheSync((envName: string) =>\n buildEnvDescriptors(\n preset,\n preset.alias,\n createUncachedDescriptors,\n envName,\n ),\n ),\n);\nconst loadPresetOverridesDescriptors = makeWeakCacheSync(\n (preset: PresetInstance) =>\n makeStrongCacheSync((index: number) =>\n buildOverrideDescriptors(\n preset,\n preset.alias,\n createUncachedDescriptors,\n index,\n ),\n ),\n);\nconst loadPresetOverridesEnvDescriptors = makeWeakCacheSync(\n (preset: PresetInstance) =>\n makeStrongCacheSync((index: number) =>\n makeStrongCacheSync((envName: string) =>\n buildOverrideEnvDescriptors(\n preset,\n preset.alias,\n createUncachedDescriptors,\n index,\n envName,\n ),\n ),\n ),\n);\n\nexport type FileHandling = \"transpile\" | \"ignored\" | \"unsupported\";\nexport type RootConfigChain = ConfigChain & {\n babelrc: ConfigFile | void;\n config: ConfigFile | void;\n ignore: IgnoreFile | void;\n fileHandling: FileHandling;\n files: Set;\n};\n\n/**\n * Build a config chain for Babel's full root configuration.\n */\nexport function* buildRootChain(\n opts: ValidatedOptions,\n context: ConfigContext,\n): Handler {\n let configReport, babelRcReport;\n const programmaticLogger = new ConfigPrinter();\n const programmaticChain = yield* loadProgrammaticChain(\n {\n options: opts,\n dirname: context.cwd,\n },\n context,\n undefined,\n programmaticLogger,\n );\n if (!programmaticChain) return null;\n const programmaticReport = yield* programmaticLogger.output();\n\n let configFile;\n if (typeof opts.configFile === \"string\") {\n configFile = yield* loadConfig(\n opts.configFile,\n context.cwd,\n context.envName,\n context.caller,\n );\n } else if (opts.configFile !== false) {\n configFile = yield* findRootConfig(\n context.root,\n context.envName,\n context.caller,\n );\n }\n\n let { babelrc, babelrcRoots } = opts;\n let babelrcRootsDirectory = context.cwd;\n\n const configFileChain = emptyChain();\n const configFileLogger = new ConfigPrinter();\n if (configFile) {\n const validatedFile = validateConfigFile(configFile);\n const result = yield* loadFileChain(\n validatedFile,\n context,\n undefined,\n configFileLogger,\n );\n if (!result) return null;\n configReport = yield* configFileLogger.output();\n\n // Allow config files to toggle `.babelrc` resolution on and off and\n // specify where the roots are.\n if (babelrc === undefined) {\n babelrc = validatedFile.options.babelrc;\n }\n if (babelrcRoots === undefined) {\n babelrcRootsDirectory = validatedFile.dirname;\n babelrcRoots = validatedFile.options.babelrcRoots;\n }\n\n mergeChain(configFileChain, result);\n }\n\n let ignoreFile, babelrcFile;\n let isIgnored = false;\n const fileChain = emptyChain();\n // resolve all .babelrc files\n if (\n (babelrc === true || babelrc === undefined) &&\n typeof context.filename === \"string\"\n ) {\n const pkgData = yield* findPackageData(context.filename);\n\n if (\n pkgData &&\n babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory)\n ) {\n ({ ignore: ignoreFile, config: babelrcFile } = yield* findRelativeConfig(\n pkgData,\n context.envName,\n context.caller,\n ));\n\n if (ignoreFile) {\n fileChain.files.add(ignoreFile.filepath);\n }\n\n if (\n ignoreFile &&\n shouldIgnore(context, ignoreFile.ignore, null, ignoreFile.dirname)\n ) {\n isIgnored = true;\n }\n\n if (babelrcFile && !isIgnored) {\n const validatedFile = validateBabelrcFile(babelrcFile);\n const babelrcLogger = new ConfigPrinter();\n const result = yield* loadFileChain(\n validatedFile,\n context,\n undefined,\n babelrcLogger,\n );\n if (!result) {\n isIgnored = true;\n } else {\n babelRcReport = yield* babelrcLogger.output();\n mergeChain(fileChain, result);\n }\n }\n\n if (babelrcFile && isIgnored) {\n fileChain.files.add(babelrcFile.filepath);\n }\n }\n }\n\n if (context.showConfig) {\n console.log(\n `Babel configs on \"${context.filename}\" (ascending priority):\\n` +\n // print config by the order of ascending priority\n [configReport, babelRcReport, programmaticReport]\n .filter(x => !!x)\n .join(\"\\n\\n\") +\n \"\\n-----End Babel configs-----\",\n );\n }\n // Insert file chain in front so programmatic options have priority\n // over configuration file chain items.\n const chain = mergeChain(\n mergeChain(mergeChain(emptyChain(), configFileChain), fileChain),\n programmaticChain,\n );\n\n return {\n plugins: isIgnored ? [] : dedupDescriptors(chain.plugins),\n presets: isIgnored ? [] : dedupDescriptors(chain.presets),\n options: isIgnored ? [] : chain.options.map(o => normalizeOptions(o)),\n fileHandling: isIgnored ? \"ignored\" : \"transpile\",\n ignore: ignoreFile || undefined,\n babelrc: babelrcFile || undefined,\n config: configFile || undefined,\n files: chain.files,\n };\n}\n\nfunction babelrcLoadEnabled(\n context: ConfigContext,\n pkgData: FilePackageData,\n babelrcRoots: BabelrcSearch | undefined,\n babelrcRootsDirectory: string,\n): boolean {\n if (typeof babelrcRoots === \"boolean\") return babelrcRoots;\n\n const absoluteRoot = context.root;\n\n // Fast path to avoid having to match patterns if the babelrc is just\n // loading in the standard root directory.\n if (babelrcRoots === undefined) {\n return pkgData.directories.includes(absoluteRoot);\n }\n\n let babelrcPatterns = babelrcRoots;\n if (!Array.isArray(babelrcPatterns)) {\n babelrcPatterns = [babelrcPatterns as IgnoreItem];\n }\n babelrcPatterns = babelrcPatterns.map(pat => {\n return typeof pat === \"string\"\n ? path.resolve(babelrcRootsDirectory, pat)\n : pat;\n });\n\n // Fast path to avoid having to match patterns if the babelrc is just\n // loading in the standard root directory.\n if (babelrcPatterns.length === 1 && babelrcPatterns[0] === absoluteRoot) {\n return pkgData.directories.includes(absoluteRoot);\n }\n\n return babelrcPatterns.some(pat => {\n if (typeof pat === \"string\") {\n pat = pathPatternToRegex(pat, babelrcRootsDirectory);\n }\n\n return pkgData.directories.some(directory => {\n return matchPattern(pat, babelrcRootsDirectory, directory, context);\n });\n });\n}\n\nconst validateConfigFile = makeWeakCacheSync(\n (file: ConfigFile): ValidatedFile => ({\n filepath: file.filepath,\n dirname: file.dirname,\n options: validate(\"configfile\", file.options, file.filepath),\n }),\n);\n\nconst validateBabelrcFile = makeWeakCacheSync(\n (file: ConfigFile): ValidatedFile => ({\n filepath: file.filepath,\n dirname: file.dirname,\n options: validate(\"babelrcfile\", file.options, file.filepath),\n }),\n);\n\nconst validateExtendFile = makeWeakCacheSync(\n (file: ConfigFile): ValidatedFile => ({\n filepath: file.filepath,\n dirname: file.dirname,\n options: validate(\"extendsfile\", file.options, file.filepath),\n }),\n);\n\n/**\n * Build a config chain for just the programmatic options passed into Babel.\n */\nconst loadProgrammaticChain = makeChainWalker({\n root: input => buildRootDescriptors(input, \"base\", createCachedDescriptors),\n env: (input, envName) =>\n buildEnvDescriptors(input, \"base\", createCachedDescriptors, envName),\n overrides: (input, index) =>\n buildOverrideDescriptors(input, \"base\", createCachedDescriptors, index),\n overridesEnv: (input, index, envName) =>\n buildOverrideEnvDescriptors(\n input,\n \"base\",\n createCachedDescriptors,\n index,\n envName,\n ),\n createLogger: (input, context, baseLogger) =>\n buildProgrammaticLogger(input, context, baseLogger),\n});\n\n/**\n * Build a config chain for a given file.\n */\nconst loadFileChainWalker = makeChainWalker({\n root: file => loadFileDescriptors(file),\n env: (file, envName) => loadFileEnvDescriptors(file)(envName),\n overrides: (file, index) => loadFileOverridesDescriptors(file)(index),\n overridesEnv: (file, index, envName) =>\n loadFileOverridesEnvDescriptors(file)(index)(envName),\n createLogger: (file, context, baseLogger) =>\n buildFileLogger(file.filepath, context, baseLogger),\n});\n\nfunction* loadFileChain(\n input: ValidatedFile,\n context: ConfigContext,\n files: Set,\n baseLogger: ConfigPrinter,\n) {\n const chain = yield* loadFileChainWalker(input, context, files, baseLogger);\n chain?.files.add(input.filepath);\n\n return chain;\n}\n\nconst loadFileDescriptors = makeWeakCacheSync((file: ValidatedFile) =>\n buildRootDescriptors(file, file.filepath, createUncachedDescriptors),\n);\nconst loadFileEnvDescriptors = makeWeakCacheSync((file: ValidatedFile) =>\n makeStrongCacheSync((envName: string) =>\n buildEnvDescriptors(\n file,\n file.filepath,\n createUncachedDescriptors,\n envName,\n ),\n ),\n);\nconst loadFileOverridesDescriptors = makeWeakCacheSync((file: ValidatedFile) =>\n makeStrongCacheSync((index: number) =>\n buildOverrideDescriptors(\n file,\n file.filepath,\n createUncachedDescriptors,\n index,\n ),\n ),\n);\nconst loadFileOverridesEnvDescriptors = makeWeakCacheSync(\n (file: ValidatedFile) =>\n makeStrongCacheSync((index: number) =>\n makeStrongCacheSync((envName: string) =>\n buildOverrideEnvDescriptors(\n file,\n file.filepath,\n createUncachedDescriptors,\n index,\n envName,\n ),\n ),\n ),\n);\n\nfunction buildFileLogger(\n filepath: string,\n context: ConfigContext,\n baseLogger: ConfigPrinter | void,\n) {\n if (!baseLogger) {\n return () => {};\n }\n return baseLogger.configure(context.showConfig, ChainFormatter.Config, {\n filepath,\n });\n}\n\nfunction buildRootDescriptors(\n { dirname, options }: Partial,\n alias: string,\n descriptors: (\n dirname: string,\n options: ValidatedOptions,\n alias: string,\n ) => OptionsAndDescriptors,\n) {\n return descriptors(dirname, options, alias);\n}\n\nfunction buildProgrammaticLogger(\n _: unknown,\n context: ConfigContext,\n baseLogger: ConfigPrinter | void,\n) {\n if (!baseLogger) {\n return () => {};\n }\n return baseLogger.configure(context.showConfig, ChainFormatter.Programmatic, {\n callerName: context.caller?.name,\n });\n}\n\nfunction buildEnvDescriptors(\n { dirname, options }: Partial,\n alias: string,\n descriptors: (\n dirname: string,\n options: ValidatedOptions,\n alias: string,\n ) => OptionsAndDescriptors,\n envName: string,\n) {\n const opts = options.env?.[envName];\n return opts ? descriptors(dirname, opts, `${alias}.env[\"${envName}\"]`) : null;\n}\n\nfunction buildOverrideDescriptors(\n { dirname, options }: Partial,\n alias: string,\n descriptors: (\n dirname: string,\n options: ValidatedOptions,\n alias: string,\n ) => OptionsAndDescriptors,\n index: number,\n) {\n const opts = options.overrides?.[index];\n if (!opts) throw new Error(\"Assertion failure - missing override\");\n\n return descriptors(dirname, opts, `${alias}.overrides[${index}]`);\n}\n\nfunction buildOverrideEnvDescriptors(\n { dirname, options }: Partial,\n alias: string,\n descriptors: (\n dirname: string,\n options: ValidatedOptions,\n alias: string,\n ) => OptionsAndDescriptors,\n index: number,\n envName: string,\n) {\n const override = options.overrides?.[index];\n if (!override) throw new Error(\"Assertion failure - missing override\");\n\n const opts = override.env?.[envName];\n return opts\n ? descriptors(\n dirname,\n opts,\n `${alias}.overrides[${index}].env[\"${envName}\"]`,\n )\n : null;\n}\n\nfunction makeChainWalker<\n ArgT extends {\n options: ValidatedOptions;\n dirname: string;\n filepath?: string;\n },\n>({\n root,\n env,\n overrides,\n overridesEnv,\n createLogger,\n}: {\n root: (configEntry: ArgT) => OptionsAndDescriptors;\n env: (configEntry: ArgT, env: string) => OptionsAndDescriptors | null;\n overrides: (configEntry: ArgT, index: number) => OptionsAndDescriptors;\n overridesEnv: (\n configEntry: ArgT,\n index: number,\n env: string,\n ) => OptionsAndDescriptors | null;\n createLogger: (\n configEntry: ArgT,\n context: ConfigContext,\n printer: ConfigPrinter | void,\n ) => (\n opts: OptionsAndDescriptors,\n index?: number | null,\n env?: string | null,\n ) => void;\n}): (\n configEntry: ArgT,\n context: ConfigContext,\n files?: Set,\n baseLogger?: ConfigPrinter,\n) => Handler {\n return function* chainWalker(input, context, files = new Set(), baseLogger) {\n const { dirname } = input;\n\n const flattenedConfigs: Array<{\n config: OptionsAndDescriptors;\n index: number | undefined | null;\n envName: string | undefined | null;\n }> = [];\n\n const rootOpts = root(input);\n if (configIsApplicable(rootOpts, dirname, context, input.filepath)) {\n flattenedConfigs.push({\n config: rootOpts,\n envName: undefined,\n index: undefined,\n });\n\n const envOpts = env(input, context.envName);\n if (\n envOpts &&\n configIsApplicable(envOpts, dirname, context, input.filepath)\n ) {\n flattenedConfigs.push({\n config: envOpts,\n envName: context.envName,\n index: undefined,\n });\n }\n\n (rootOpts.options.overrides || []).forEach((_, index) => {\n const overrideOps = overrides(input, index);\n if (configIsApplicable(overrideOps, dirname, context, input.filepath)) {\n flattenedConfigs.push({\n config: overrideOps,\n index,\n envName: undefined,\n });\n\n const overrideEnvOpts = overridesEnv(input, index, context.envName);\n if (\n overrideEnvOpts &&\n configIsApplicable(\n overrideEnvOpts,\n dirname,\n context,\n input.filepath,\n )\n ) {\n flattenedConfigs.push({\n config: overrideEnvOpts,\n index,\n envName: context.envName,\n });\n }\n }\n });\n }\n\n // Process 'ignore' and 'only' before 'extends' items are processed so\n // that we don't do extra work loading extended configs if a file is\n // ignored.\n if (\n flattenedConfigs.some(\n ({\n config: {\n options: { ignore, only },\n },\n }) => shouldIgnore(context, ignore, only, dirname),\n )\n ) {\n return null;\n }\n\n const chain = emptyChain();\n const logger = createLogger(input, context, baseLogger);\n\n for (const { config, index, envName } of flattenedConfigs) {\n if (\n !(yield* mergeExtendsChain(\n chain,\n config.options,\n dirname,\n context,\n files,\n baseLogger,\n ))\n ) {\n return null;\n }\n\n logger(config, index, envName);\n yield* mergeChainOpts(chain, config);\n }\n return chain;\n };\n}\n\nfunction* mergeExtendsChain(\n chain: ConfigChain,\n opts: ValidatedOptions,\n dirname: string,\n context: ConfigContext,\n files: Set,\n baseLogger?: ConfigPrinter,\n): Handler {\n if (opts.extends === undefined) return true;\n\n const file = yield* loadConfig(\n opts.extends,\n dirname,\n context.envName,\n context.caller,\n );\n\n if (files.has(file)) {\n throw new Error(\n `Configuration cycle detected loading ${file.filepath}.\\n` +\n `File already loaded following the config chain:\\n` +\n Array.from(files, file => ` - ${file.filepath}`).join(\"\\n\"),\n );\n }\n\n files.add(file);\n const fileChain = yield* loadFileChain(\n validateExtendFile(file),\n context,\n files,\n baseLogger,\n );\n files.delete(file);\n\n if (!fileChain) return false;\n\n mergeChain(chain, fileChain);\n\n return true;\n}\n\nfunction mergeChain(target: ConfigChain, source: ConfigChain): ConfigChain {\n target.options.push(...source.options);\n target.plugins.push(...source.plugins);\n target.presets.push(...source.presets);\n for (const file of source.files) {\n target.files.add(file);\n }\n\n return target;\n}\n\nfunction* mergeChainOpts(\n target: ConfigChain,\n { options, plugins, presets }: OptionsAndDescriptors,\n): Handler {\n target.options.push(options);\n target.plugins.push(...(yield* plugins()));\n target.presets.push(...(yield* presets()));\n\n return target;\n}\n\nfunction emptyChain(): ConfigChain {\n return {\n options: [],\n presets: [],\n plugins: [],\n files: new Set(),\n };\n}\n\nfunction normalizeOptions(opts: ValidatedOptions): ValidatedOptions {\n const options = {\n ...opts,\n };\n delete options.extends;\n delete options.env;\n delete options.overrides;\n delete options.plugins;\n delete options.presets;\n delete options.passPerPreset;\n delete options.ignore;\n delete options.only;\n delete options.test;\n delete options.include;\n delete options.exclude;\n\n // \"sourceMap\" is just aliased to sourceMap, so copy it over as\n // we merge the options together.\n if (Object.hasOwn(options, \"sourceMap\")) {\n options.sourceMaps = options.sourceMap;\n delete options.sourceMap;\n }\n return options;\n}\n\nfunction dedupDescriptors(\n items: Array>,\n): Array> {\n const map: Map<\n Function,\n Map }>\n > = new Map();\n\n const descriptors = [];\n\n for (const item of items) {\n if (typeof item.value === \"function\") {\n const fnKey = item.value;\n let nameMap = map.get(fnKey);\n if (!nameMap) {\n nameMap = new Map();\n map.set(fnKey, nameMap);\n }\n let desc = nameMap.get(item.name);\n if (!desc) {\n desc = { value: item };\n descriptors.push(desc);\n\n // Treat passPerPreset presets as unique, skipping them\n // in the merge processing steps.\n if (!item.ownPass) nameMap.set(item.name, desc);\n } else {\n desc.value = item;\n }\n } else {\n descriptors.push({ value: item });\n }\n }\n\n return descriptors.reduce((acc, desc) => {\n acc.push(desc.value);\n return acc;\n }, []);\n}\n\nfunction configIsApplicable(\n { options }: OptionsAndDescriptors,\n dirname: string,\n context: ConfigContext,\n configName: string,\n): boolean {\n return (\n (options.test === undefined ||\n configFieldIsApplicable(context, options.test, dirname, configName)) &&\n (options.include === undefined ||\n configFieldIsApplicable(context, options.include, dirname, configName)) &&\n (options.exclude === undefined ||\n !configFieldIsApplicable(context, options.exclude, dirname, configName))\n );\n}\n\nfunction configFieldIsApplicable(\n context: ConfigContext,\n test: ConfigApplicableTest,\n dirname: string,\n configName: string,\n): boolean {\n const patterns = Array.isArray(test) ? test : [test];\n\n return matchesPatterns(context, patterns, dirname, configName);\n}\n\n/**\n * Print the ignoreList-values in a more helpful way than the default.\n */\nfunction ignoreListReplacer(\n _key: string,\n value: IgnoreList | IgnoreItem,\n): IgnoreList | IgnoreItem | string {\n if (value instanceof RegExp) {\n return String(value);\n }\n\n return value;\n}\n\n/**\n * Tests if a filename should be ignored based on \"ignore\" and \"only\" options.\n */\nfunction shouldIgnore(\n context: ConfigContext,\n ignore: IgnoreList | undefined | null,\n only: IgnoreList | undefined | null,\n dirname: string,\n): boolean {\n if (ignore && matchesPatterns(context, ignore, dirname)) {\n const message = `No config is applied to \"${\n context.filename ?? \"(unknown)\"\n }\" because it matches one of \\`ignore: ${JSON.stringify(\n ignore,\n ignoreListReplacer,\n )}\\` from \"${dirname}\"`;\n debug(message);\n if (context.showConfig) {\n console.log(message);\n }\n return true;\n }\n\n if (only && !matchesPatterns(context, only, dirname)) {\n const message = `No config is applied to \"${\n context.filename ?? \"(unknown)\"\n }\" because it fails to match one of \\`only: ${JSON.stringify(\n only,\n ignoreListReplacer,\n )}\\` from \"${dirname}\"`;\n debug(message);\n if (context.showConfig) {\n console.log(message);\n }\n return true;\n }\n\n return false;\n}\n\n/**\n * Returns result of calling function with filename if pattern is a function.\n * Otherwise returns result of matching pattern Regex with filename.\n */\nfunction matchesPatterns(\n context: ConfigContext,\n patterns: IgnoreList,\n dirname: string,\n configName?: string,\n): boolean {\n return patterns.some(pattern =>\n matchPattern(pattern, dirname, context.filename, context, configName),\n );\n}\n\nfunction matchPattern(\n pattern: IgnoreItem,\n dirname: string,\n pathToTest: string | undefined,\n context: ConfigContext,\n configName?: string,\n): boolean {\n if (typeof pattern === \"function\") {\n return !!endHiddenCallStack(pattern)(pathToTest, {\n dirname,\n envName: context.envName,\n caller: context.caller,\n });\n }\n\n if (typeof pathToTest !== \"string\") {\n throw new ConfigError(\n `Configuration contains string/RegExp pattern, but no filename was passed to Babel`,\n configName,\n );\n }\n\n if (typeof pattern === \"string\") {\n pattern = pathPatternToRegex(pattern, dirname);\n }\n return pattern.test(pathToTest);\n}\n"],"mappings":";;;;;;;;AAEA,SAAAA,MAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,KAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,OAAA;EAAA,MAAAF,IAAA,GAAAC,OAAA;EAAAC,MAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,IAAAG,QAAA,GAAAF,OAAA;AASA,IAAAG,eAAA,GAAAH,OAAA;AACA,IAAAI,QAAA,GAAAJ,OAAA;AAGA,IAAAK,kBAA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CACnBmF,OAAmB,EACnB3I,OAAe,EACf4I,UAA8B,EAC9BtL,OAAsB,EACtBwK,UAAmB,EACV;EACT,IAAI,OAAOa,OAAO,KAAK,UAAU,EAAE;IACjC,OAAO,CAAC,CAAC,IAAAE,qCAAkB,EAACF,OAAO,CAAC,CAACC,UAAU,EAAE;MAC/C5I,OAAO;MACPxB,OAAO,EAAElB,OAAO,CAACkB,OAAO;MACxB+B,MAAM,EAAEjD,OAAO,CAACiD;IAClB,CAAC,CAAC;EACJ;EAEA,IAAI,OAAOqI,UAAU,KAAK,QAAQ,EAAE;IAClC,MAAM,IAAIE,oBAAW,CACnB,mFAAmF,EACnFhB,UACF,CAAC;EACH;EAEA,IAAI,OAAOa,OAAO,KAAK,QAAQ,EAAE;IAC/BA,OAAO,GAAG,IAAArF,uBAAkB,EAACqF,OAAO,EAAE3I,OAAO,CAAC;EAChD;EACA,OAAO2I,OAAO,CAAChC,IAAI,CAACiC,UAAU,CAAC;AACjC;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/config-descriptors.js b/node_modules/@babel/core/lib/config/config-descriptors.js new file mode 100644 index 0000000..21fb414 --- /dev/null +++ b/node_modules/@babel/core/lib/config/config-descriptors.js @@ -0,0 +1,190 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createCachedDescriptors = createCachedDescriptors; +exports.createDescriptor = createDescriptor; +exports.createUncachedDescriptors = createUncachedDescriptors; +function _gensync() { + const data = require("gensync"); + _gensync = function () { + return data; + }; + return data; +} +var _functional = require("../gensync-utils/functional.js"); +var _index = require("./files/index.js"); +var _item = require("./item.js"); +var _caching = require("./caching.js"); +var _resolveTargets = require("./resolve-targets.js"); +function isEqualDescriptor(a, b) { + var _a$file, _b$file, _a$file2, _b$file2; + return a.name === b.name && a.value === b.value && a.options === b.options && a.dirname === b.dirname && a.alias === b.alias && a.ownPass === b.ownPass && ((_a$file = a.file) == null ? void 0 : _a$file.request) === ((_b$file = b.file) == null ? void 0 : _b$file.request) && ((_a$file2 = a.file) == null ? void 0 : _a$file2.resolved) === ((_b$file2 = b.file) == null ? void 0 : _b$file2.resolved); +} +function* handlerOf(value) { + return value; +} +function optionsWithResolvedBrowserslistConfigFile(options, dirname) { + if (typeof options.browserslistConfigFile === "string") { + options.browserslistConfigFile = (0, _resolveTargets.resolveBrowserslistConfigFile)(options.browserslistConfigFile, dirname); + } + return options; +} +function createCachedDescriptors(dirname, options, alias) { + const { + plugins, + presets, + passPerPreset + } = options; + return { + options: optionsWithResolvedBrowserslistConfigFile(options, dirname), + plugins: plugins ? () => createCachedPluginDescriptors(plugins, dirname)(alias) : () => handlerOf([]), + presets: presets ? () => createCachedPresetDescriptors(presets, dirname)(alias)(!!passPerPreset) : () => handlerOf([]) + }; +} +function createUncachedDescriptors(dirname, options, alias) { + return { + options: optionsWithResolvedBrowserslistConfigFile(options, dirname), + plugins: (0, _functional.once)(() => createPluginDescriptors(options.plugins || [], dirname, alias)), + presets: (0, _functional.once)(() => createPresetDescriptors(options.presets || [], dirname, alias, !!options.passPerPreset)) + }; +} +const PRESET_DESCRIPTOR_CACHE = new WeakMap(); +const createCachedPresetDescriptors = (0, _caching.makeWeakCacheSync)((items, cache) => { + const dirname = cache.using(dir => dir); + return (0, _caching.makeStrongCacheSync)(alias => (0, _caching.makeStrongCache)(function* (passPerPreset) { + const descriptors = yield* createPresetDescriptors(items, dirname, alias, passPerPreset); + return descriptors.map(desc => loadCachedDescriptor(PRESET_DESCRIPTOR_CACHE, desc)); + })); +}); +const PLUGIN_DESCRIPTOR_CACHE = new WeakMap(); +const createCachedPluginDescriptors = (0, _caching.makeWeakCacheSync)((items, cache) => { + const dirname = cache.using(dir => dir); + return (0, _caching.makeStrongCache)(function* (alias) { + const descriptors = yield* createPluginDescriptors(items, dirname, alias); + return descriptors.map(desc => loadCachedDescriptor(PLUGIN_DESCRIPTOR_CACHE, desc)); + }); +}); +const DEFAULT_OPTIONS = {}; +function loadCachedDescriptor(cache, desc) { + const { + value, + options = DEFAULT_OPTIONS + } = desc; + if (options === false) return desc; + let cacheByOptions = cache.get(value); + if (!cacheByOptions) { + cacheByOptions = new WeakMap(); + cache.set(value, cacheByOptions); + } + let possibilities = cacheByOptions.get(options); + if (!possibilities) { + possibilities = []; + cacheByOptions.set(options, possibilities); + } + if (!possibilities.includes(desc)) { + const matches = possibilities.filter(possibility => isEqualDescriptor(possibility, desc)); + if (matches.length > 0) { + return matches[0]; + } + possibilities.push(desc); + } + return desc; +} +function* createPresetDescriptors(items, dirname, alias, passPerPreset) { + return yield* createDescriptors("preset", items, dirname, alias, passPerPreset); +} +function* createPluginDescriptors(items, dirname, alias) { + return yield* createDescriptors("plugin", items, dirname, alias); +} +function* createDescriptors(type, items, dirname, alias, ownPass) { + const descriptors = yield* _gensync().all(items.map((item, index) => createDescriptor(item, dirname, { + type, + alias: `${alias}$${index}`, + ownPass: !!ownPass + }))); + assertNoDuplicates(descriptors); + return descriptors; +} +function* createDescriptor(pair, dirname, { + type, + alias, + ownPass +}) { + const desc = (0, _item.getItemDescriptor)(pair); + if (desc) { + return desc; + } + let name; + let options; + let value = pair; + if (Array.isArray(value)) { + if (value.length === 3) { + [value, options, name] = value; + } else { + [value, options] = value; + } + } + let file = undefined; + let filepath = null; + if (typeof value === "string") { + if (typeof type !== "string") { + throw new Error("To resolve a string-based item, the type of item must be given"); + } + const resolver = type === "plugin" ? _index.loadPlugin : _index.loadPreset; + const request = value; + ({ + filepath, + value + } = yield* resolver(value, dirname)); + file = { + request, + resolved: filepath + }; + } + if (!value) { + throw new Error(`Unexpected falsy value: ${String(value)}`); + } + if (typeof value === "object" && value.__esModule) { + if (value.default) { + value = value.default; + } else { + throw new Error("Must export a default export when using ES6 modules."); + } + } + if (typeof value !== "object" && typeof value !== "function") { + throw new Error(`Unsupported format: ${typeof value}. Expected an object or a function.`); + } + if (filepath !== null && typeof value === "object" && value) { + throw new Error(`Plugin/Preset files are not allowed to export objects, only functions. In ${filepath}`); + } + return { + name, + alias: filepath || alias, + value, + options, + dirname, + ownPass, + file + }; +} +function assertNoDuplicates(items) { + const map = new Map(); + for (const item of items) { + if (typeof item.value !== "function") continue; + let nameMap = map.get(item.value); + if (!nameMap) { + nameMap = new Set(); + map.set(item.value, nameMap); + } + if (nameMap.has(item.name)) { + const conflicts = items.filter(i => i.value === item.value); + throw new Error([`Duplicate plugin/preset detected.`, `If you'd like to use two separate instances of a plugin,`, `they need separate names, e.g.`, ``, ` plugins: [`, ` ['some-plugin', {}],`, ` ['some-plugin', {}, 'some unique name'],`, ` ]`, ``, `Duplicates detected are:`, `${JSON.stringify(conflicts, null, 2)}`].join("\n")); + } + nameMap.add(item.name); + } +} +0 && 0; + +//# sourceMappingURL=config-descriptors.js.map diff --git a/node_modules/@babel/core/lib/config/config-descriptors.js.map b/node_modules/@babel/core/lib/config/config-descriptors.js.map new file mode 100644 index 0000000..cddcbd8 --- /dev/null +++ b/node_modules/@babel/core/lib/config/config-descriptors.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_gensync","data","require","_functional","_index","_item","_caching","_resolveTargets","isEqualDescriptor","a","b","_a$file","_b$file","_a$file2","_b$file2","name","value","options","dirname","alias","ownPass","file","request","resolved","handlerOf","optionsWithResolvedBrowserslistConfigFile","browserslistConfigFile","resolveBrowserslistConfigFile","createCachedDescriptors","plugins","presets","passPerPreset","createCachedPluginDescriptors","createCachedPresetDescriptors","createUncachedDescriptors","once","createPluginDescriptors","createPresetDescriptors","PRESET_DESCRIPTOR_CACHE","WeakMap","makeWeakCacheSync","items","cache","using","dir","makeStrongCacheSync","makeStrongCache","descriptors","map","desc","loadCachedDescriptor","PLUGIN_DESCRIPTOR_CACHE","DEFAULT_OPTIONS","cacheByOptions","get","set","possibilities","includes","matches","filter","possibility","length","push","createDescriptors","type","gensync","all","item","index","createDescriptor","assertNoDuplicates","pair","getItemDescriptor","Array","isArray","undefined","filepath","Error","resolver","loadPlugin","loadPreset","String","__esModule","default","Map","nameMap","Set","has","conflicts","i","JSON","stringify","join","add"],"sources":["../../src/config/config-descriptors.ts"],"sourcesContent":["import gensync, { type Handler } from \"gensync\";\nimport { once } from \"../gensync-utils/functional.ts\";\n\nimport { loadPlugin, loadPreset } from \"./files/index.ts\";\n\nimport { getItemDescriptor } from \"./item.ts\";\n\nimport {\n makeWeakCacheSync,\n makeStrongCacheSync,\n makeStrongCache,\n} from \"./caching.ts\";\nimport type { CacheConfigurator } from \"./caching.ts\";\n\nimport type {\n ValidatedOptions,\n PluginList,\n PluginItem,\n} from \"./validation/options.ts\";\n\nimport { resolveBrowserslistConfigFile } from \"./resolve-targets.ts\";\nimport type { PluginAPI, PresetAPI } from \"./helpers/config-api.ts\";\n\n// Represents a config object and functions to lazily load the descriptors\n// for the plugins and presets so we don't load the plugins/presets unless\n// the options object actually ends up being applicable.\nexport type OptionsAndDescriptors = {\n options: ValidatedOptions;\n plugins: () => Handler>>;\n presets: () => Handler>>;\n};\n\n// Represents a plugin or presets at a given location in a config object.\n// At this point these have been resolved to a specific object or function,\n// but have not yet been executed to call functions with options.\nexport interface UnloadedDescriptor {\n name: string | undefined;\n value: object | ((api: API, options: Options, dirname: string) => unknown);\n options: Options;\n dirname: string;\n alias: string;\n ownPass?: boolean;\n file?: {\n request: string;\n resolved: string;\n };\n}\n\nfunction isEqualDescriptor(\n a: UnloadedDescriptor,\n b: UnloadedDescriptor,\n): boolean {\n return (\n a.name === b.name &&\n a.value === b.value &&\n a.options === b.options &&\n a.dirname === b.dirname &&\n a.alias === b.alias &&\n a.ownPass === b.ownPass &&\n a.file?.request === b.file?.request &&\n a.file?.resolved === b.file?.resolved\n );\n}\n\nexport type ValidatedFile = {\n filepath: string;\n dirname: string;\n options: ValidatedOptions;\n};\n\n// eslint-disable-next-line require-yield\nfunction* handlerOf(value: T): Handler {\n return value;\n}\n\nfunction optionsWithResolvedBrowserslistConfigFile(\n options: ValidatedOptions,\n dirname: string,\n): ValidatedOptions {\n if (typeof options.browserslistConfigFile === \"string\") {\n options.browserslistConfigFile = resolveBrowserslistConfigFile(\n options.browserslistConfigFile,\n dirname,\n );\n }\n return options;\n}\n\n/**\n * Create a set of descriptors from a given options object, preserving\n * descriptor identity based on the identity of the plugin/preset arrays\n * themselves, and potentially on the identity of the plugins/presets + options.\n */\nexport function createCachedDescriptors(\n dirname: string,\n options: ValidatedOptions,\n alias: string,\n): OptionsAndDescriptors {\n const { plugins, presets, passPerPreset } = options;\n return {\n options: optionsWithResolvedBrowserslistConfigFile(options, dirname),\n plugins: plugins\n ? () =>\n // @ts-expect-error todo(flow->ts) ts complains about incorrect arguments\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n createCachedPluginDescriptors(plugins, dirname)(alias)\n : () => handlerOf([]),\n presets: presets\n ? () =>\n // @ts-expect-error todo(flow->ts) ts complains about incorrect arguments\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n createCachedPresetDescriptors(presets, dirname)(alias)(\n !!passPerPreset,\n )\n : () => handlerOf([]),\n };\n}\n\n/**\n * Create a set of descriptors from a given options object, with consistent\n * identity for the descriptors, but not caching based on any specific identity.\n */\nexport function createUncachedDescriptors(\n dirname: string,\n options: ValidatedOptions,\n alias: string,\n): OptionsAndDescriptors {\n return {\n options: optionsWithResolvedBrowserslistConfigFile(options, dirname),\n // The returned result here is cached to represent a config object in\n // memory, so we build and memoize the descriptors to ensure the same\n // values are returned consistently.\n plugins: once(() =>\n createPluginDescriptors(options.plugins || [], dirname, alias),\n ),\n presets: once(() =>\n createPresetDescriptors(\n options.presets || [],\n dirname,\n alias,\n !!options.passPerPreset,\n ),\n ),\n };\n}\n\nconst PRESET_DESCRIPTOR_CACHE = new WeakMap();\nconst createCachedPresetDescriptors = makeWeakCacheSync(\n (items: PluginList, cache: CacheConfigurator) => {\n const dirname = cache.using(dir => dir);\n return makeStrongCacheSync((alias: string) =>\n makeStrongCache(function* (\n passPerPreset: boolean,\n ): Handler>> {\n const descriptors = yield* createPresetDescriptors(\n items,\n dirname,\n alias,\n passPerPreset,\n );\n return descriptors.map(\n // Items are cached using the overall preset array identity when\n // possibly, but individual descriptors are also cached if a match\n // can be found in the previously-used descriptor lists.\n desc => loadCachedDescriptor(PRESET_DESCRIPTOR_CACHE, desc),\n );\n }),\n );\n },\n);\n\nconst PLUGIN_DESCRIPTOR_CACHE = new WeakMap();\nconst createCachedPluginDescriptors = makeWeakCacheSync(\n (items: PluginList, cache: CacheConfigurator) => {\n const dirname = cache.using(dir => dir);\n return makeStrongCache(function* (\n alias: string,\n ): Handler>> {\n const descriptors = yield* createPluginDescriptors(items, dirname, alias);\n return descriptors.map(\n // Items are cached using the overall plugin array identity when\n // possibly, but individual descriptors are also cached if a match\n // can be found in the previously-used descriptor lists.\n desc => loadCachedDescriptor(PLUGIN_DESCRIPTOR_CACHE, desc),\n );\n });\n },\n);\n\n/**\n * When no options object is given in a descriptor, this object is used\n * as a WeakMap key in order to have consistent identity.\n */\nconst DEFAULT_OPTIONS = {};\n\n/**\n * Given the cache and a descriptor, returns a matching descriptor from the\n * cache, or else returns the input descriptor and adds it to the cache for\n * next time.\n */\nfunction loadCachedDescriptor(\n cache: WeakMap<\n object | Function,\n WeakMap>>\n >,\n desc: UnloadedDescriptor,\n) {\n const { value, options = DEFAULT_OPTIONS } = desc;\n if (options === false) return desc;\n\n let cacheByOptions = cache.get(value);\n if (!cacheByOptions) {\n cacheByOptions = new WeakMap();\n cache.set(value, cacheByOptions);\n }\n\n let possibilities = cacheByOptions.get(options);\n if (!possibilities) {\n possibilities = [];\n cacheByOptions.set(options, possibilities);\n }\n\n if (!possibilities.includes(desc)) {\n const matches = possibilities.filter(possibility =>\n isEqualDescriptor(possibility, desc),\n );\n if (matches.length > 0) {\n return matches[0];\n }\n\n possibilities.push(desc);\n }\n\n return desc;\n}\n\nfunction* createPresetDescriptors(\n items: PluginList,\n dirname: string,\n alias: string,\n passPerPreset: boolean,\n): Handler>> {\n return yield* createDescriptors(\n \"preset\",\n items,\n dirname,\n alias,\n passPerPreset,\n );\n}\n\nfunction* createPluginDescriptors(\n items: PluginList,\n dirname: string,\n alias: string,\n): Handler>> {\n return yield* createDescriptors(\"plugin\", items, dirname, alias);\n}\n\nfunction* createDescriptors(\n type: \"plugin\" | \"preset\",\n items: PluginList,\n dirname: string,\n alias: string,\n ownPass?: boolean,\n): Handler>> {\n const descriptors = yield* gensync.all(\n items.map((item, index) =>\n createDescriptor(item, dirname, {\n type,\n alias: `${alias}$${index}`,\n ownPass: !!ownPass,\n }),\n ),\n );\n\n assertNoDuplicates(descriptors);\n\n return descriptors;\n}\n\n/**\n * Given a plugin/preset item, resolve it into a standard format.\n */\nexport function* createDescriptor(\n pair: PluginItem,\n dirname: string,\n {\n type,\n alias,\n ownPass,\n }: {\n type?: \"plugin\" | \"preset\";\n alias: string;\n ownPass?: boolean;\n },\n): Handler> {\n const desc = getItemDescriptor(pair);\n if (desc) {\n return desc;\n }\n\n let name;\n let options;\n // todo(flow->ts) better type annotation\n let value: any = pair;\n if (Array.isArray(value)) {\n if (value.length === 3) {\n [value, options, name] = value;\n } else {\n [value, options] = value;\n }\n }\n\n let file = undefined;\n let filepath = null;\n if (typeof value === \"string\") {\n if (typeof type !== \"string\") {\n throw new Error(\n \"To resolve a string-based item, the type of item must be given\",\n );\n }\n const resolver = type === \"plugin\" ? loadPlugin : loadPreset;\n const request = value;\n\n ({ filepath, value } = yield* resolver(value, dirname));\n\n file = {\n request,\n resolved: filepath,\n };\n }\n\n if (!value) {\n throw new Error(`Unexpected falsy value: ${String(value)}`);\n }\n\n if (typeof value === \"object\" && value.__esModule) {\n if (value.default) {\n value = value.default;\n } else {\n throw new Error(\"Must export a default export when using ES6 modules.\");\n }\n }\n\n if (typeof value !== \"object\" && typeof value !== \"function\") {\n throw new Error(\n `Unsupported format: ${typeof value}. Expected an object or a function.`,\n );\n }\n\n if (filepath !== null && typeof value === \"object\" && value) {\n // We allow object values for plugins/presets nested directly within a\n // config object, because it can be useful to define them in nested\n // configuration contexts.\n throw new Error(\n `Plugin/Preset files are not allowed to export objects, only functions. In ${filepath}`,\n );\n }\n\n return {\n name,\n alias: filepath || alias,\n value,\n options,\n dirname,\n ownPass,\n file,\n };\n}\n\nfunction assertNoDuplicates(items: Array>): void {\n const map = new Map();\n\n for (const item of items) {\n if (typeof item.value !== \"function\") continue;\n\n let nameMap = map.get(item.value);\n if (!nameMap) {\n nameMap = new Set();\n map.set(item.value, nameMap);\n }\n\n if (nameMap.has(item.name)) {\n const conflicts = items.filter(i => i.value === item.value);\n throw new Error(\n [\n `Duplicate plugin/preset detected.`,\n `If you'd like to use two separate instances of a plugin,`,\n `they need separate names, e.g.`,\n ``,\n ` plugins: [`,\n ` ['some-plugin', {}],`,\n ` ['some-plugin', {}, 'some unique name'],`,\n ` ]`,\n ``,\n `Duplicates detected are:`,\n `${JSON.stringify(conflicts, null, 2)}`,\n ].join(\"\\n\"),\n );\n }\n\n nameMap.add(item.name);\n }\n}\n"],"mappings":";;;;;;;;AAAA,SAAAA,SAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,QAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,IAAAE,WAAA,GAAAD,OAAA;AAEA,IAAAE,MAAA,GAAAF,OAAA;AAEA,IAAAG,KAAA,GAAAH,OAAA;AAEA,IAAAI,QAAA,GAAAJ,OAAA;AAaA,IAAAK,eAAA,GAAAL,OAAA;AA4BA,SAASM,iBAAiBA,CACxBC,CAA0B,EAC1BC,CAA0B,EACjB;EAAA,IAAAC,OAAA,EAAAC,OAAA,EAAAC,QAAA,EAAAC,QAAA;EACT,OACEL,CAAC,CAACM,IAAI,KAAKL,CAAC,CAACK,IAAI,IACjBN,CAAC,CAACO,KAAK,KAAKN,CAAC,CAACM,KAAK,IACnBP,CAAC,CAACQ,OAAO,KAAKP,CAAC,CAACO,OAAO,IACvBR,CAAC,CAACS,OAAO,KAAKR,CAAC,CAACQ,OAAO,IACvBT,CAAC,CAACU,KAAK,KAAKT,CAAC,CAACS,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,KAAK;IACxBH,KAAK;IACLC,OAAO;IACPC,OAAO;IACPE,OAAO;IACPC;EACF,CAAC;AACH;AAEA,SAASiD,kBAAkBA,CAAM7B,KAAqC,EAAQ;EAC5E,MAAMO,GAAG,GAAG,IAAIoC,GAAG,CAAC,CAAC;EAErB,KAAK,MAAMjB,IAAI,IAAI1B,KAAK,EAAE;IACxB,IAAI,OAAO0B,IAAI,CAACnD,KAAK,KAAK,UAAU,EAAE;IAEtC,IAAIqE,OAAO,GAAGrC,GAAG,CAACM,GAAG,CAACa,IAAI,CAACnD,KAAK,CAAC;IACjC,IAAI,CAACqE,OAAO,EAAE;MACZA,OAAO,GAAG,IAAIC,GAAG,CAAC,CAAC;MACnBtC,GAAG,CAACO,GAAG,CAACY,IAAI,CAACnD,KAAK,EAAEqE,OAAO,CAAC;IAC9B;IAEA,IAAIA,OAAO,CAACE,GAAG,CAACpB,IAAI,CAACpD,IAAI,CAAC,EAAE;MAC1B,MAAMyE,SAAS,GAAG/C,KAAK,CAACkB,MAAM,CAAC8B,CAAC,IAAIA,CAAC,CAACzE,KAAK,KAAKmD,IAAI,CAACnD,KAAK,CAAC;MAC3D,MAAM,IAAI6D,KAAK,CACb,CACE,mCAAmC,EACnC,0DAA0D,EAC1D,gCAAgC,EAChC,EAAE,EACF,cAAc,EACd,0BAA0B,EAC1B,8CAA8C,EAC9C,KAAK,EACL,EAAE,EACF,0BAA0B,EAC1B,GAAGa,IAAI,CAACC,SAAS,CAACH,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CACxC,CAACI,IAAI,CAAC,IAAI,CACb,CAAC;IACH;IAEAP,OAAO,CAACQ,GAAG,CAAC1B,IAAI,CAACpD,IAAI,CAAC;EACxB;AACF;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/configuration.js b/node_modules/@babel/core/lib/config/files/configuration.js new file mode 100644 index 0000000..9c6d49c --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/configuration.js @@ -0,0 +1,286 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ROOT_CONFIG_FILENAMES = void 0; +exports.findConfigUpwards = findConfigUpwards; +exports.findRelativeConfig = findRelativeConfig; +exports.findRootConfig = findRootConfig; +exports.loadConfig = loadConfig; +exports.resolveShowConfigPath = resolveShowConfigPath; +function _debug() { + const data = require("debug"); + _debug = function () { + return data; + }; + return data; +} +function _fs() { + const data = require("fs"); + _fs = function () { + return data; + }; + return data; +} +function _path() { + const data = require("path"); + _path = function () { + return data; + }; + return data; +} +function _json() { + const data = require("json5"); + _json = function () { + return data; + }; + return data; +} +function _gensync() { + const data = require("gensync"); + _gensync = function () { + return data; + }; + return data; +} +var _caching = require("../caching.js"); +var _configApi = require("../helpers/config-api.js"); +var _utils = require("./utils.js"); +var _moduleTypes = require("./module-types.js"); +var _patternToRegex = require("../pattern-to-regex.js"); +var _configError = require("../../errors/config-error.js"); +var fs = require("../../gensync-utils/fs.js"); +var _rewriteStackTrace = require("../../errors/rewrite-stack-trace.js"); +const debug = _debug()("babel:config:loading:files:configuration"); +const ROOT_CONFIG_FILENAMES = exports.ROOT_CONFIG_FILENAMES = ["babel.config.js", "babel.config.cjs", "babel.config.mjs", "babel.config.json", "babel.config.cts"]; +const RELATIVE_CONFIG_FILENAMES = [".babelrc", ".babelrc.js", ".babelrc.cjs", ".babelrc.mjs", ".babelrc.json", ".babelrc.cts"]; +const BABELIGNORE_FILENAME = ".babelignore"; +const runConfig = (0, _caching.makeWeakCache)(function* runConfig(options, cache) { + yield* []; + return { + options: (0, _rewriteStackTrace.endHiddenCallStack)(options)((0, _configApi.makeConfigAPI)(cache)), + cacheNeedsConfiguration: !cache.configured() + }; +}); +function* readConfigCode(filepath, data) { + if (!_fs().existsSync(filepath)) return null; + let options = yield* (0, _moduleTypes.default)(filepath, "You appear to be using a native ECMAScript module configuration " + "file, which is only supported when running Babel asynchronously."); + let cacheNeedsConfiguration = false; + if (typeof options === "function") { + ({ + options, + cacheNeedsConfiguration + } = yield* runConfig(options, data)); + } + if (!options || typeof options !== "object" || Array.isArray(options)) { + throw new _configError.default(`Configuration should be an exported JavaScript object.`, filepath); + } + if (typeof options.then === "function") { + options.catch == null || options.catch(() => {}); + throw new _configError.default(`You appear to be using an async configuration, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously return your config.`, filepath); + } + if (cacheNeedsConfiguration) throwConfigError(filepath); + return buildConfigFileObject(options, filepath); +} +const cfboaf = new WeakMap(); +function buildConfigFileObject(options, filepath) { + let configFilesByFilepath = cfboaf.get(options); + if (!configFilesByFilepath) { + cfboaf.set(options, configFilesByFilepath = new Map()); + } + let configFile = configFilesByFilepath.get(filepath); + if (!configFile) { + configFile = { + filepath, + dirname: _path().dirname(filepath), + options + }; + configFilesByFilepath.set(filepath, configFile); + } + return configFile; +} +const packageToBabelConfig = (0, _caching.makeWeakCacheSync)(file => { + const babel = file.options["babel"]; + if (typeof babel === "undefined") return null; + if (typeof babel !== "object" || Array.isArray(babel) || babel === null) { + throw new _configError.default(`.babel property must be an object`, file.filepath); + } + return { + filepath: file.filepath, + dirname: file.dirname, + options: babel + }; +}); +const readConfigJSON5 = (0, _utils.makeStaticFileCache)((filepath, content) => { + let options; + try { + options = _json().parse(content); + } catch (err) { + throw new _configError.default(`Error while parsing config - ${err.message}`, filepath); + } + if (!options) throw new _configError.default(`No config detected`, filepath); + if (typeof options !== "object") { + throw new _configError.default(`Config returned typeof ${typeof options}`, filepath); + } + if (Array.isArray(options)) { + throw new _configError.default(`Expected config object but found array`, filepath); + } + delete options["$schema"]; + return { + filepath, + dirname: _path().dirname(filepath), + options + }; +}); +const readIgnoreConfig = (0, _utils.makeStaticFileCache)((filepath, content) => { + const ignoreDir = _path().dirname(filepath); + const ignorePatterns = content.split("\n").map(line => line.replace(/#.*$/, "").trim()).filter(line => !!line); + for (const pattern of ignorePatterns) { + if (pattern[0] === "!") { + throw new _configError.default(`Negation of file paths is not supported.`, filepath); + } + } + return { + filepath, + dirname: _path().dirname(filepath), + ignore: ignorePatterns.map(pattern => (0, _patternToRegex.default)(pattern, ignoreDir)) + }; +}); +function findConfigUpwards(rootDir) { + let dirname = rootDir; + for (;;) { + for (const filename of ROOT_CONFIG_FILENAMES) { + if (_fs().existsSync(_path().join(dirname, filename))) { + return dirname; + } + } + const nextDir = _path().dirname(dirname); + if (dirname === nextDir) break; + dirname = nextDir; + } + return null; +} +function* findRelativeConfig(packageData, envName, caller) { + let config = null; + let ignore = null; + const dirname = _path().dirname(packageData.filepath); + for (const loc of packageData.directories) { + if (!config) { + var _packageData$pkg; + config = yield* loadOneConfig(RELATIVE_CONFIG_FILENAMES, loc, envName, caller, ((_packageData$pkg = packageData.pkg) == null ? void 0 : _packageData$pkg.dirname) === loc ? packageToBabelConfig(packageData.pkg) : null); + } + if (!ignore) { + const ignoreLoc = _path().join(loc, BABELIGNORE_FILENAME); + ignore = yield* readIgnoreConfig(ignoreLoc); + if (ignore) { + debug("Found ignore %o from %o.", ignore.filepath, dirname); + } + } + } + return { + config, + ignore + }; +} +function findRootConfig(dirname, envName, caller) { + return loadOneConfig(ROOT_CONFIG_FILENAMES, dirname, envName, caller); +} +function* loadOneConfig(names, dirname, envName, caller, previousConfig = null) { + const configs = yield* _gensync().all(names.map(filename => readConfig(_path().join(dirname, filename), envName, caller))); + const config = configs.reduce((previousConfig, config) => { + if (config && previousConfig) { + throw new _configError.default(`Multiple configuration files found. Please remove one:\n` + ` - ${_path().basename(previousConfig.filepath)}\n` + ` - ${config.filepath}\n` + `from ${dirname}`); + } + return config || previousConfig; + }, previousConfig); + if (config) { + debug("Found configuration %o from %o.", config.filepath, dirname); + } + return config; +} +function* loadConfig(name, dirname, envName, caller) { + const filepath = (((v, w) => (v = v.split("."), w = w.split("."), +v[0] > +w[0] || v[0] == w[0] && +v[1] >= +w[1]))(process.versions.node, "8.9") ? require.resolve : (r, { + paths: [b] + }, M = require("module")) => { + let f = M._findPath(r, M._nodeModulePaths(b).concat(b)); + if (f) return f; + f = new Error(`Cannot resolve module '${r}'`); + f.code = "MODULE_NOT_FOUND"; + throw f; + })(name, { + paths: [dirname] + }); + const conf = yield* readConfig(filepath, envName, caller); + if (!conf) { + throw new _configError.default(`Config file contains no configuration data`, filepath); + } + debug("Loaded config %o from %o.", name, dirname); + return conf; +} +function readConfig(filepath, envName, caller) { + const ext = _path().extname(filepath); + switch (ext) { + case ".js": + case ".cjs": + case ".mjs": + case ".cts": + return readConfigCode(filepath, { + envName, + caller + }); + default: + return readConfigJSON5(filepath); + } +} +function* resolveShowConfigPath(dirname) { + const targetPath = process.env.BABEL_SHOW_CONFIG_FOR; + if (targetPath != null) { + const absolutePath = _path().resolve(dirname, targetPath); + const stats = yield* fs.stat(absolutePath); + if (!stats.isFile()) { + throw new Error(`${absolutePath}: BABEL_SHOW_CONFIG_FOR must refer to a regular file, directories are not supported.`); + } + return absolutePath; + } + return null; +} +function throwConfigError(filepath) { + throw new _configError.default(`\ +Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured +for various types of caching, using the first param of their handler functions: + +module.exports = function(api) { + // The API exposes the following: + + // Cache the returned value forever and don't call this function again. + api.cache(true); + + // Don't cache at all. Not recommended because it will be very slow. + api.cache(false); + + // Cached based on the value of some function. If this function returns a value different from + // a previously-encountered value, the plugins will re-evaluate. + var env = api.cache(() => process.env.NODE_ENV); + + // If testing for a specific env, we recommend specifics to avoid instantiating a plugin for + // any possible NODE_ENV value that might come up during plugin execution. + var isProd = api.cache(() => process.env.NODE_ENV === "production"); + + // .cache(fn) will perform a linear search though instances to find the matching plugin based + // based on previous instantiated plugins. If you want to recreate the plugin and discard the + // previous instance whenever something changes, you may use: + var isProd = api.cache.invalidate(() => process.env.NODE_ENV === "production"); + + // Note, we also expose the following more-verbose versions of the above examples: + api.cache.forever(); // api.cache(true) + api.cache.never(); // api.cache(false) + api.cache.using(fn); // api.cache(fn) + + // Return the value that will be cached. + return { }; +};`, filepath); +} +0 && 0; + +//# sourceMappingURL=configuration.js.map diff --git a/node_modules/@babel/core/lib/config/files/configuration.js.map b/node_modules/@babel/core/lib/config/files/configuration.js.map new file mode 100644 index 0000000..6ecd1ae --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/configuration.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_debug","data","require","_fs","_path","_json","_gensync","_caching","_configApi","_utils","_moduleTypes","_patternToRegex","_configError","fs","_rewriteStackTrace","debug","buildDebug","ROOT_CONFIG_FILENAMES","exports","RELATIVE_CONFIG_FILENAMES","BABELIGNORE_FILENAME","runConfig","makeWeakCache","options","cache","endHiddenCallStack","makeConfigAPI","cacheNeedsConfiguration","configured","readConfigCode","filepath","nodeFs","existsSync","loadCodeDefault","Array","isArray","ConfigError","then","catch","throwConfigError","buildConfigFileObject","cfboaf","WeakMap","configFilesByFilepath","get","set","Map","configFile","dirname","path","packageToBabelConfig","makeWeakCacheSync","file","babel","readConfigJSON5","makeStaticFileCache","content","json5","parse","err","message","readIgnoreConfig","ignoreDir","ignorePatterns","split","map","line","replace","trim","filter","pattern","ignore","pathPatternToRegex","findConfigUpwards","rootDir","filename","join","nextDir","findRelativeConfig","packageData","envName","caller","config","loc","directories","_packageData$pkg","loadOneConfig","pkg","ignoreLoc","findRootConfig","names","previousConfig","configs","gensync","all","readConfig","reduce","basename","loadConfig","name","v","w","process","versions","node","resolve","r","paths","b","M","f","_findPath","_nodeModulePaths","concat","Error","code","conf","ext","extname","resolveShowConfigPath","targetPath","env","BABEL_SHOW_CONFIG_FOR","absolutePath","stats","stat","isFile"],"sources":["../../../src/config/files/configuration.ts"],"sourcesContent":["import buildDebug from \"debug\";\nimport nodeFs from \"fs\";\nimport path from \"path\";\nimport json5 from \"json5\";\nimport gensync from \"gensync\";\nimport type { Handler } from \"gensync\";\nimport { makeWeakCache, makeWeakCacheSync } from \"../caching.ts\";\nimport type { CacheConfigurator } from \"../caching.ts\";\nimport { makeConfigAPI } from \"../helpers/config-api.ts\";\nimport type { ConfigAPI } from \"../helpers/config-api.ts\";\nimport { makeStaticFileCache } from \"./utils.ts\";\nimport loadCodeDefault from \"./module-types.ts\";\nimport pathPatternToRegex from \"../pattern-to-regex.ts\";\nimport type { FilePackageData, RelativeConfig, ConfigFile } from \"./types.ts\";\nimport type { CallerMetadata, InputOptions } from \"../validation/options.ts\";\nimport ConfigError from \"../../errors/config-error.ts\";\n\nimport * as fs from \"../../gensync-utils/fs.ts\";\n\nimport { createRequire } from \"module\";\nimport { endHiddenCallStack } from \"../../errors/rewrite-stack-trace.ts\";\nconst require = createRequire(import.meta.url);\n\nconst debug = buildDebug(\"babel:config:loading:files:configuration\");\n\nexport const ROOT_CONFIG_FILENAMES = [\n \"babel.config.js\",\n \"babel.config.cjs\",\n \"babel.config.mjs\",\n \"babel.config.json\",\n \"babel.config.cts\",\n];\nconst RELATIVE_CONFIG_FILENAMES = [\n \".babelrc\",\n \".babelrc.js\",\n \".babelrc.cjs\",\n \".babelrc.mjs\",\n \".babelrc.json\",\n \".babelrc.cts\",\n];\n\nconst BABELIGNORE_FILENAME = \".babelignore\";\n\ntype ConfigCacheData = {\n envName: string;\n caller: CallerMetadata | undefined;\n};\n\nconst runConfig = makeWeakCache(function* runConfig(\n options: Function,\n cache: CacheConfigurator,\n): Handler<{\n options: InputOptions | null;\n cacheNeedsConfiguration: boolean;\n}> {\n // @ts-expect-error - if we want to make it possible to use async configs\n yield* [];\n\n return {\n options: endHiddenCallStack(options as any as (api: ConfigAPI) => unknown)(\n makeConfigAPI(cache),\n ),\n cacheNeedsConfiguration: !cache.configured(),\n };\n});\n\nfunction* readConfigCode(\n filepath: string,\n data: ConfigCacheData,\n): Handler {\n if (!nodeFs.existsSync(filepath)) return null;\n\n let options = yield* loadCodeDefault(\n filepath,\n \"You appear to be using a native ECMAScript module configuration \" +\n \"file, which is only supported when running Babel asynchronously.\",\n );\n\n let cacheNeedsConfiguration = false;\n if (typeof options === \"function\") {\n ({ options, cacheNeedsConfiguration } = yield* runConfig(options, data));\n }\n\n if (!options || typeof options !== \"object\" || Array.isArray(options)) {\n throw new ConfigError(\n `Configuration should be an exported JavaScript object.`,\n filepath,\n );\n }\n\n // @ts-expect-error todo(flow->ts)\n if (typeof options.then === \"function\") {\n // @ts-expect-error We use ?. in case options is a thenable but not a promise\n options.catch?.(() => {});\n\n throw new ConfigError(\n `You appear to be using an async configuration, ` +\n `which your current version of Babel does not support. ` +\n `We may add support for this in the future, ` +\n `but if you're on the most recent version of @babel/core and still ` +\n `seeing this error, then you'll need to synchronously return your config.`,\n filepath,\n );\n }\n\n if (cacheNeedsConfiguration) throwConfigError(filepath);\n\n return buildConfigFileObject(options, filepath);\n}\n\n// We cache the generated ConfigFile object rather than creating a new one\n// every time, so that it can be used as a cache key in other functions.\nconst cfboaf /* configFilesByOptionsAndFilepath */ = new WeakMap<\n InputOptions,\n Map\n>();\nfunction buildConfigFileObject(\n options: InputOptions,\n filepath: string,\n): ConfigFile {\n let configFilesByFilepath = cfboaf.get(options);\n if (!configFilesByFilepath) {\n cfboaf.set(options, (configFilesByFilepath = new Map()));\n }\n\n let configFile = configFilesByFilepath.get(filepath);\n if (!configFile) {\n configFile = {\n filepath,\n dirname: path.dirname(filepath),\n options,\n };\n configFilesByFilepath.set(filepath, configFile);\n }\n\n return configFile;\n}\n\nconst packageToBabelConfig = makeWeakCacheSync(\n (file: ConfigFile): ConfigFile | null => {\n const babel: unknown = file.options[\"babel\"];\n\n if (typeof babel === \"undefined\") return null;\n\n if (typeof babel !== \"object\" || Array.isArray(babel) || babel === null) {\n throw new ConfigError(`.babel property must be an object`, file.filepath);\n }\n\n return {\n filepath: file.filepath,\n dirname: file.dirname,\n options: babel,\n };\n },\n);\n\nconst readConfigJSON5 = makeStaticFileCache((filepath, content): ConfigFile => {\n let options;\n try {\n options = json5.parse(content);\n } catch (err) {\n throw new ConfigError(\n `Error while parsing config - ${err.message}`,\n filepath,\n );\n }\n\n if (!options) throw new ConfigError(`No config detected`, filepath);\n\n if (typeof options !== \"object\") {\n throw new ConfigError(`Config returned typeof ${typeof options}`, filepath);\n }\n if (Array.isArray(options)) {\n throw new ConfigError(`Expected config object but found array`, filepath);\n }\n\n delete options[\"$schema\"];\n\n return {\n filepath,\n dirname: path.dirname(filepath),\n options,\n };\n});\n\nconst readIgnoreConfig = makeStaticFileCache((filepath, content) => {\n const ignoreDir = path.dirname(filepath);\n const ignorePatterns = content\n .split(\"\\n\")\n .map(line => line.replace(/#.*$/, \"\").trim())\n .filter(line => !!line);\n\n for (const pattern of ignorePatterns) {\n if (pattern[0] === \"!\") {\n throw new ConfigError(\n `Negation of file paths is not supported.`,\n filepath,\n );\n }\n }\n\n return {\n filepath,\n dirname: path.dirname(filepath),\n ignore: ignorePatterns.map(pattern =>\n pathPatternToRegex(pattern, ignoreDir),\n ),\n };\n});\n\nexport function findConfigUpwards(rootDir: string): string | null {\n let dirname = rootDir;\n for (;;) {\n for (const filename of ROOT_CONFIG_FILENAMES) {\n if (nodeFs.existsSync(path.join(dirname, filename))) {\n return dirname;\n }\n }\n\n const nextDir = path.dirname(dirname);\n if (dirname === nextDir) break;\n dirname = nextDir;\n }\n\n return null;\n}\n\nexport function* findRelativeConfig(\n packageData: FilePackageData,\n envName: string,\n caller: CallerMetadata | undefined,\n): Handler {\n let config = null;\n let ignore = null;\n\n const dirname = path.dirname(packageData.filepath);\n\n for (const loc of packageData.directories) {\n if (!config) {\n config = yield* loadOneConfig(\n RELATIVE_CONFIG_FILENAMES,\n loc,\n envName,\n caller,\n packageData.pkg?.dirname === loc\n ? packageToBabelConfig(packageData.pkg)\n : null,\n );\n }\n\n if (!ignore) {\n const ignoreLoc = path.join(loc, BABELIGNORE_FILENAME);\n ignore = yield* readIgnoreConfig(ignoreLoc);\n\n if (ignore) {\n debug(\"Found ignore %o from %o.\", ignore.filepath, dirname);\n }\n }\n }\n\n return { config, ignore };\n}\n\nexport function findRootConfig(\n dirname: string,\n envName: string,\n caller: CallerMetadata | undefined,\n): Handler {\n return loadOneConfig(ROOT_CONFIG_FILENAMES, dirname, envName, caller);\n}\n\nfunction* loadOneConfig(\n names: string[],\n dirname: string,\n envName: string,\n caller: CallerMetadata | undefined,\n previousConfig: ConfigFile | null = null,\n): Handler {\n const configs = yield* gensync.all(\n names.map(filename =>\n readConfig(path.join(dirname, filename), envName, caller),\n ),\n );\n const config = configs.reduce((previousConfig: ConfigFile | null, config) => {\n if (config && previousConfig) {\n throw new ConfigError(\n `Multiple configuration files found. Please remove one:\\n` +\n ` - ${path.basename(previousConfig.filepath)}\\n` +\n ` - ${config.filepath}\\n` +\n `from ${dirname}`,\n );\n }\n\n return config || previousConfig;\n }, previousConfig);\n\n if (config) {\n debug(\"Found configuration %o from %o.\", config.filepath, dirname);\n }\n return config;\n}\n\nexport function* loadConfig(\n name: string,\n dirname: string,\n envName: string,\n caller: CallerMetadata | undefined,\n): Handler {\n const filepath = require.resolve(name, { paths: [dirname] });\n\n const conf = yield* readConfig(filepath, envName, caller);\n if (!conf) {\n throw new ConfigError(\n `Config file contains no configuration data`,\n filepath,\n );\n }\n\n debug(\"Loaded config %o from %o.\", name, dirname);\n return conf;\n}\n\n/**\n * Read the given config file, returning the result. Returns null if no config was found, but will\n * throw if there are parsing errors while loading a config.\n */\nfunction readConfig(\n filepath: string,\n envName: string,\n caller: CallerMetadata | undefined,\n): Handler {\n const ext = path.extname(filepath);\n switch (ext) {\n case \".js\":\n case \".cjs\":\n case \".mjs\":\n case \".cts\":\n return readConfigCode(filepath, { envName, caller });\n default:\n return readConfigJSON5(filepath);\n }\n}\n\nexport function* resolveShowConfigPath(\n dirname: string,\n): Handler {\n const targetPath = process.env.BABEL_SHOW_CONFIG_FOR;\n if (targetPath != null) {\n const absolutePath = path.resolve(dirname, targetPath);\n const stats = yield* fs.stat(absolutePath);\n if (!stats.isFile()) {\n throw new Error(\n `${absolutePath}: BABEL_SHOW_CONFIG_FOR must refer to a regular file, directories are not supported.`,\n );\n }\n return absolutePath;\n }\n return null;\n}\n\nfunction throwConfigError(filepath: string): never {\n throw new ConfigError(\n `\\\nCaching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured\nfor various types of caching, using the first param of their handler functions:\n\nmodule.exports = function(api) {\n // The API exposes the following:\n\n // Cache the returned value forever and don't call this function again.\n api.cache(true);\n\n // Don't cache at all. Not recommended because it will be very slow.\n api.cache(false);\n\n // Cached based on the value of some function. If this function returns a value different from\n // a previously-encountered value, the plugins will re-evaluate.\n var env = api.cache(() => process.env.NODE_ENV);\n\n // If testing for a specific env, we recommend specifics to avoid instantiating a plugin for\n // any possible NODE_ENV value that might come up during plugin execution.\n var isProd = api.cache(() => process.env.NODE_ENV === \"production\");\n\n // .cache(fn) will perform a linear search though instances to find the matching plugin based\n // based on previous instantiated plugins. If you want to recreate the plugin and discard the\n // previous instance whenever something changes, you may use:\n var isProd = api.cache.invalidate(() => process.env.NODE_ENV === \"production\");\n\n // Note, we also expose the following more-verbose versions of the above examples:\n api.cache.forever(); // api.cache(true)\n api.cache.never(); // api.cache(false)\n api.cache.using(fn); // api.cache(fn)\n\n // Return the value that will be cached.\n return { };\n};`,\n filepath,\n );\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAAA,OAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,MAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,IAAA;EAAA,MAAAF,IAAA,GAAAC,OAAA;EAAAC,GAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAG,MAAA;EAAA,MAAAH,IAAA,GAAAC,OAAA;EAAAE,KAAA,YAAAA,CAAA;IAAA,OAAAH,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAI,MAAA;EAAA,MAAAJ,IAAA,GAAAC,OAAA;EAAAG,KAAA,YAAAA,CAAA;IAAA,OAAAJ,IAAA;EAAA;EAAA,OAAAA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wE,UAAU,GAAGlB,OAAO,CAACmB,GAAG,CAACC,qBAAqB;EACpD,IAAIF,UAAU,IAAI,IAAI,EAAE;IACtB,MAAMG,YAAY,GAAG1E,MAAGA,CAAC,CAACwD,OAAO,CAACzD,OAAO,EAAEwE,UAAU,CAAC;IACtD,MAAMI,KAAK,GAAG,OAAO/G,EAAE,CAACgH,IAAI,CAACF,YAAY,CAAC;IAC1C,IAAI,CAACC,KAAK,CAACE,MAAM,CAAC,CAAC,EAAE;MACnB,MAAM,IAAIZ,KAAK,CACb,GAAGS,YAAY,sFACjB,CAAC;IACH;IACA,OAAOA,YAAY;EACrB;EACA,OAAO,IAAI;AACb;AAEA,SAASpF,gBAAgBA,CAACT,QAAgB,EAAS;EACjD,MAAM,IAAIM,oBAAW,CACnB;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG,EACCN,QACF,CAAC;AACH;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/import.cjs b/node_modules/@babel/core/lib/config/files/import.cjs new file mode 100644 index 0000000..46fa5d5 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/import.cjs @@ -0,0 +1,6 @@ +module.exports = function import_(filepath) { + return import(filepath); +}; +0 && 0; + +//# sourceMappingURL=import.cjs.map diff --git a/node_modules/@babel/core/lib/config/files/import.cjs.map b/node_modules/@babel/core/lib/config/files/import.cjs.map new file mode 100644 index 0000000..2200da8 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/import.cjs.map @@ -0,0 +1 @@ +{"version":3,"names":["module","exports","import_","filepath"],"sources":["../../../src/config/files/import.cjs"],"sourcesContent":["// We keep this in a separate file so that in older node versions, where\n// import() isn't supported, we can try/catch around the require() call\n// when loading this file.\n\nmodule.exports = function import_(filepath) {\n return import(filepath);\n};\n"],"mappings":"AAIAA,MAAM,CAACC,OAAO,GAAG,SAASC,OAAOA,CAACC,QAAQ,EAAE;EAC1C,OAAO,OAAOA,QAAQ,CAAC;AACzB,CAAC;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/index-browser.js b/node_modules/@babel/core/lib/config/files/index-browser.js new file mode 100644 index 0000000..d8ba7db --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/index-browser.js @@ -0,0 +1,58 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ROOT_CONFIG_FILENAMES = void 0; +exports.findConfigUpwards = findConfigUpwards; +exports.findPackageData = findPackageData; +exports.findRelativeConfig = findRelativeConfig; +exports.findRootConfig = findRootConfig; +exports.loadConfig = loadConfig; +exports.loadPlugin = loadPlugin; +exports.loadPreset = loadPreset; +exports.resolvePlugin = resolvePlugin; +exports.resolvePreset = resolvePreset; +exports.resolveShowConfigPath = resolveShowConfigPath; +function findConfigUpwards(rootDir) { + return null; +} +function* findPackageData(filepath) { + return { + filepath, + directories: [], + pkg: null, + isPackage: false + }; +} +function* findRelativeConfig(pkgData, envName, caller) { + return { + config: null, + ignore: null + }; +} +function* findRootConfig(dirname, envName, caller) { + return null; +} +function* loadConfig(name, dirname, envName, caller) { + throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`); +} +function* resolveShowConfigPath(dirname) { + return null; +} +const ROOT_CONFIG_FILENAMES = exports.ROOT_CONFIG_FILENAMES = []; +function resolvePlugin(name, dirname) { + return null; +} +function resolvePreset(name, dirname) { + return null; +} +function loadPlugin(name, dirname) { + throw new Error(`Cannot load plugin ${name} relative to ${dirname} in a browser`); +} +function loadPreset(name, dirname) { + throw new Error(`Cannot load preset ${name} relative to ${dirname} in a browser`); +} +0 && 0; + +//# sourceMappingURL=index-browser.js.map diff --git a/node_modules/@babel/core/lib/config/files/index-browser.js.map b/node_modules/@babel/core/lib/config/files/index-browser.js.map new file mode 100644 index 0000000..fdcc2c5 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/index-browser.js.map @@ -0,0 +1 @@ +{"version":3,"names":["findConfigUpwards","rootDir","findPackageData","filepath","directories","pkg","isPackage","findRelativeConfig","pkgData","envName","caller","config","ignore","findRootConfig","dirname","loadConfig","name","Error","resolveShowConfigPath","ROOT_CONFIG_FILENAMES","exports","resolvePlugin","resolvePreset","loadPlugin","loadPreset"],"sources":["../../../src/config/files/index-browser.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\n\nimport type {\n ConfigFile,\n IgnoreFile,\n RelativeConfig,\n FilePackageData,\n} from \"./types.ts\";\n\nimport type { CallerMetadata } from \"../validation/options.ts\";\n\nexport type { ConfigFile, IgnoreFile, RelativeConfig, FilePackageData };\n\nexport function findConfigUpwards(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n rootDir: string,\n): string | null {\n return null;\n}\n\n// eslint-disable-next-line require-yield\nexport function* findPackageData(filepath: string): Handler {\n return {\n filepath,\n directories: [],\n pkg: null,\n isPackage: false,\n };\n}\n\n// eslint-disable-next-line require-yield\nexport function* findRelativeConfig(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n pkgData: FilePackageData,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n envName: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n caller: CallerMetadata | undefined,\n): Handler {\n return { config: null, ignore: null };\n}\n\n// eslint-disable-next-line require-yield\nexport function* findRootConfig(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n dirname: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n envName: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n caller: CallerMetadata | undefined,\n): Handler {\n return null;\n}\n\n// eslint-disable-next-line require-yield\nexport function* loadConfig(\n name: string,\n dirname: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n envName: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n caller: CallerMetadata | undefined,\n): Handler {\n throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`);\n}\n\n// eslint-disable-next-line require-yield\nexport function* resolveShowConfigPath(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n dirname: string,\n): Handler {\n return null;\n}\n\nexport const ROOT_CONFIG_FILENAMES: string[] = [];\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function resolvePlugin(name: string, dirname: string): string | null {\n return null;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function resolvePreset(name: string, dirname: string): string | null {\n return null;\n}\n\nexport function loadPlugin(\n name: string,\n dirname: string,\n): Handler<{\n filepath: string;\n value: unknown;\n}> {\n throw new Error(\n `Cannot load plugin ${name} relative to ${dirname} in a browser`,\n );\n}\n\nexport function loadPreset(\n name: string,\n dirname: string,\n): Handler<{\n filepath: string;\n value: unknown;\n}> {\n throw new Error(\n `Cannot load preset ${name} relative to ${dirname} in a browser`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAaO,SAASA,iBAAiBA,CAE/BC,OAAe,EACA;EACf,OAAO,IAAI;AACb;AAGO,UAAUC,eAAeA,CAACC,QAAgB,EAA4B;EAC3E,OAAO;IACLA,QAAQ;IACRC,WAAW,EAAE,EAAE;IACfC,GAAG,EAAE,IAAI;IACTC,SAAS,EAAE;EACb,CAAC;AACH;AAGO,UAAUC,kBAAkBA,CAEjCC,OAAwB,EAExBC,OAAe,EAEfC,MAAkC,EACT;EACzB,OAAO;IAAEC,MAAM,EAAE,IAAI;IAAEC,MAAM,EAAE;EAAK,CAAC;AACvC;AAGO,UAAUC,cAAcA,CAE7BC,OAAe,EAEfL,OAAe,EAEfC,MAAkC,EACN;EAC5B,OAAO,IAAI;AACb;AAGO,UAAUK,UAAUA,CACzBC,IAAY,EACZF,OAAe,EAEfL,OAAe,EAEfC,MAAkC,EACb;EACrB,MAAM,IAAIO,KAAK,CAAC,eAAeD,IAAI,gBAAgBF,OAAO,eAAe,CAAC;AAC5E;AAGO,UAAUI,qBAAqBA,CAEpCJ,OAAe,EACS;EACxB,OAAO,IAAI;AACb;AAEO,MAAMK,qBAA+B,GAAAC,OAAA,CAAAD,qBAAA,GAAG,EAAE;AAG1C,SAASE,aAAaA,CAACL,IAAY,EAAEF,OAAe,EAAiB;EAC1E,OAAO,IAAI;AACb;AAGO,SAASQ,aAAaA,CAACN,IAAY,EAAEF,OAAe,EAAiB;EAC1E,OAAO,IAAI;AACb;AAEO,SAASS,UAAUA,CACxBP,IAAY,EACZF,OAAe,EAId;EACD,MAAM,IAAIG,KAAK,CACb,sBAAsBD,IAAI,gBAAgBF,OAAO,eACnD,CAAC;AACH;AAEO,SAASU,UAAUA,CACxBR,IAAY,EACZF,OAAe,EAId;EACD,MAAM,IAAIG,KAAK,CACb,sBAAsBD,IAAI,gBAAgBF,OAAO,eACnD,CAAC;AACH;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/index.js b/node_modules/@babel/core/lib/config/files/index.js new file mode 100644 index 0000000..8750f40 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/index.js @@ -0,0 +1,78 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "ROOT_CONFIG_FILENAMES", { + enumerable: true, + get: function () { + return _configuration.ROOT_CONFIG_FILENAMES; + } +}); +Object.defineProperty(exports, "findConfigUpwards", { + enumerable: true, + get: function () { + return _configuration.findConfigUpwards; + } +}); +Object.defineProperty(exports, "findPackageData", { + enumerable: true, + get: function () { + return _package.findPackageData; + } +}); +Object.defineProperty(exports, "findRelativeConfig", { + enumerable: true, + get: function () { + return _configuration.findRelativeConfig; + } +}); +Object.defineProperty(exports, "findRootConfig", { + enumerable: true, + get: function () { + return _configuration.findRootConfig; + } +}); +Object.defineProperty(exports, "loadConfig", { + enumerable: true, + get: function () { + return _configuration.loadConfig; + } +}); +Object.defineProperty(exports, "loadPlugin", { + enumerable: true, + get: function () { + return _plugins.loadPlugin; + } +}); +Object.defineProperty(exports, "loadPreset", { + enumerable: true, + get: function () { + return _plugins.loadPreset; + } +}); +Object.defineProperty(exports, "resolvePlugin", { + enumerable: true, + get: function () { + return _plugins.resolvePlugin; + } +}); +Object.defineProperty(exports, "resolvePreset", { + enumerable: true, + get: function () { + return _plugins.resolvePreset; + } +}); +Object.defineProperty(exports, "resolveShowConfigPath", { + enumerable: true, + get: function () { + return _configuration.resolveShowConfigPath; + } +}); +var _package = require("./package.js"); +var _configuration = require("./configuration.js"); +var _plugins = require("./plugins.js"); +({}); +0 && 0; + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/core/lib/config/files/index.js.map b/node_modules/@babel/core/lib/config/files/index.js.map new file mode 100644 index 0000000..1e473b8 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_package","require","_configuration","_plugins"],"sources":["../../../src/config/files/index.ts"],"sourcesContent":["type indexBrowserType = typeof import(\"./index-browser\");\ntype indexType = typeof import(\"./index\");\n\n// Kind of gross, but essentially asserting that the exports of this module are the same as the\n// exports of index-browser, since this file may be replaced at bundle time with index-browser.\n({}) as any as indexBrowserType as indexType;\n\nexport { findPackageData } from \"./package.ts\";\n\nexport {\n findConfigUpwards,\n findRelativeConfig,\n findRootConfig,\n loadConfig,\n resolveShowConfigPath,\n ROOT_CONFIG_FILENAMES,\n} from \"./configuration.ts\";\nexport type {\n ConfigFile,\n IgnoreFile,\n RelativeConfig,\n FilePackageData,\n} from \"./types.ts\";\nexport {\n loadPlugin,\n loadPreset,\n resolvePlugin,\n resolvePreset,\n} from \"./plugins.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,IAAAA,QAAA,GAAAC,OAAA;AAEA,IAAAC,cAAA,GAAAD,OAAA;AAcA,IAAAE,QAAA,GAAAF,OAAA;AAlBA,CAAC,CAAC,CAAC;AAA0C","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/module-types.js b/node_modules/@babel/core/lib/config/files/module-types.js new file mode 100644 index 0000000..a49f613 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/module-types.js @@ -0,0 +1,176 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = loadCodeDefault; +exports.supportsESM = void 0; +var _async = require("../../gensync-utils/async.js"); +function _path() { + const data = require("path"); + _path = function () { + return data; + }; + return data; +} +function _url() { + const data = require("url"); + _url = function () { + return data; + }; + return data; +} +function _semver() { + const data = require("semver"); + _semver = function () { + return data; + }; + return data; +} +function _debug() { + const data = require("debug"); + _debug = function () { + return data; + }; + return data; +} +var _rewriteStackTrace = require("../../errors/rewrite-stack-trace.js"); +var _configError = require("../../errors/config-error.js"); +var _transformFile = require("../../transform-file.js"); +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +const debug = _debug()("babel:config:loading:files:module-types"); +{ + try { + var import_ = require("./import.cjs"); + } catch (_unused) {} +} +const supportsESM = exports.supportsESM = _semver().satisfies(process.versions.node, "^12.17 || >=13.2"); +const LOADING_CJS_FILES = new Set(); +function loadCjsDefault(filepath) { + if (LOADING_CJS_FILES.has(filepath)) { + debug("Auto-ignoring usage of config %o.", filepath); + return {}; + } + let module; + try { + LOADING_CJS_FILES.add(filepath); + module = (0, _rewriteStackTrace.endHiddenCallStack)(require)(filepath); + } finally { + LOADING_CJS_FILES.delete(filepath); + } + { + var _module; + return (_module = module) != null && _module.__esModule ? module.default || (arguments[1] ? module : undefined) : module; + } +} +const loadMjsDefault = (0, _rewriteStackTrace.endHiddenCallStack)(function () { + var _loadMjsDefault = _asyncToGenerator(function* (filepath) { + const url = (0, _url().pathToFileURL)(filepath).toString(); + { + if (!import_) { + throw new _configError.default("Internal error: Native ECMAScript modules aren't supported by this platform.\n", filepath); + } + return (yield import_(url)).default; + } + }); + function loadMjsDefault(_x) { + return _loadMjsDefault.apply(this, arguments); + } + return loadMjsDefault; +}()); +function* loadCodeDefault(filepath, asyncError) { + switch (_path().extname(filepath)) { + case ".cjs": + { + return loadCjsDefault(filepath, arguments[2]); + } + case ".mjs": + break; + case ".cts": + return loadCtsDefault(filepath); + default: + try { + { + return loadCjsDefault(filepath, arguments[2]); + } + } catch (e) { + if (e.code !== "ERR_REQUIRE_ESM") throw e; + } + } + if (yield* (0, _async.isAsync)()) { + return yield* (0, _async.waitFor)(loadMjsDefault(filepath)); + } + throw new _configError.default(asyncError, filepath); +} +function loadCtsDefault(filepath) { + const ext = ".cts"; + const hasTsSupport = !!(require.extensions[".ts"] || require.extensions[".cts"] || require.extensions[".mts"]); + let handler; + if (!hasTsSupport) { + const opts = { + babelrc: false, + configFile: false, + sourceType: "unambiguous", + sourceMaps: "inline", + sourceFileName: _path().basename(filepath), + presets: [[getTSPreset(filepath), Object.assign({ + onlyRemoveTypeImports: true, + optimizeConstEnums: true + }, { + allowDeclareFields: true + })]] + }; + handler = function (m, filename) { + if (handler && filename.endsWith(ext)) { + try { + return m._compile((0, _transformFile.transformFileSync)(filename, Object.assign({}, opts, { + filename + })).code, filename); + } catch (error) { + if (!hasTsSupport) { + const packageJson = require("@babel/preset-typescript/package.json"); + if (_semver().lt(packageJson.version, "7.21.4")) { + console.error("`.cts` configuration file failed to load, please try to update `@babel/preset-typescript`."); + } + } + throw error; + } + } + return require.extensions[".js"](m, filename); + }; + require.extensions[ext] = handler; + } + try { + return loadCjsDefault(filepath); + } finally { + if (!hasTsSupport) { + if (require.extensions[ext] === handler) delete require.extensions[ext]; + handler = undefined; + } + } +} +function getTSPreset(filepath) { + try { + return require("@babel/preset-typescript"); + } catch (error) { + if (error.code !== "MODULE_NOT_FOUND") throw error; + let message = "You appear to be using a .cts file as Babel configuration, but the `@babel/preset-typescript` package was not found: please install it!"; + { + if (process.versions.pnp) { + message += ` +If you are using Yarn Plug'n'Play, you may also need to add the following configuration to your .yarnrc.yml file: + +packageExtensions: +\t"@babel/core@*": +\t\tpeerDependencies: +\t\t\t"@babel/preset-typescript": "*" +`; + } + } + throw new _configError.default(message, filepath); + } +} +0 && 0; + +//# sourceMappingURL=module-types.js.map diff --git a/node_modules/@babel/core/lib/config/files/module-types.js.map b/node_modules/@babel/core/lib/config/files/module-types.js.map new file mode 100644 index 0000000..0707261 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/module-types.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_async","require","_path","data","_url","_semver","_debug","_rewriteStackTrace","_configError","_transformFile","asyncGeneratorStep","gen","resolve","reject","_next","_throw","key","arg","info","value","error","done","Promise","then","_asyncToGenerator","fn","self","args","arguments","apply","err","undefined","debug","buildDebug","import_","_unused","supportsESM","exports","semver","satisfies","process","versions","node","LOADING_CJS_FILES","Set","loadCjsDefault","filepath","has","module","add","endHiddenCallStack","delete","_module","__esModule","default","loadMjsDefault","_loadMjsDefault","url","pathToFileURL","toString","ConfigError","_x","loadCodeDefault","asyncError","path","extname","loadCtsDefault","e","code","isAsync","waitFor","ext","hasTsSupport","extensions","handler","opts","babelrc","configFile","sourceType","sourceMaps","sourceFileName","basename","presets","getTSPreset","Object","assign","onlyRemoveTypeImports","optimizeConstEnums","allowDeclareFields","m","filename","endsWith","_compile","transformFileSync","packageJson","lt","version","console","message","pnp"],"sources":["../../../src/config/files/module-types.ts"],"sourcesContent":["import { isAsync, waitFor } from \"../../gensync-utils/async.ts\";\nimport type { Handler } from \"gensync\";\nimport path from \"path\";\nimport { pathToFileURL } from \"url\";\nimport { createRequire } from \"module\";\nimport semver from \"semver\";\nimport buildDebug from \"debug\";\n\nimport { endHiddenCallStack } from \"../../errors/rewrite-stack-trace.ts\";\nimport ConfigError from \"../../errors/config-error.ts\";\n\nimport type { InputOptions } from \"../index.ts\";\nimport { transformFileSync } from \"../../transform-file.ts\";\n\nconst debug = buildDebug(\"babel:config:loading:files:module-types\");\n\nconst require = createRequire(import.meta.url);\n\nif (!process.env.BABEL_8_BREAKING) {\n try {\n // Old Node.js versions don't support import() syntax.\n // eslint-disable-next-line no-var\n var import_:\n | ((specifier: string | URL) => any)\n | undefined = require(\"./import.cjs\");\n } catch {}\n}\n\nexport const supportsESM = semver.satisfies(\n process.versions.node,\n // older versions, starting from 10, support the dynamic\n // import syntax but always return a rejected promise.\n \"^12.17 || >=13.2\",\n);\n\nconst LOADING_CJS_FILES = new Set();\n\nfunction loadCjsDefault(filepath: string) {\n // The `require()` call below can make this code reentrant if a require hook\n // like @babel/register has been loaded into the system. That would cause\n // Babel to attempt to compile the `.babelrc.js` file as it loads below. To\n // cover this case, we auto-ignore re-entrant config processing. ESM loaders\n // do not have this problem, because loaders do not apply to themselves.\n if (LOADING_CJS_FILES.has(filepath)) {\n debug(\"Auto-ignoring usage of config %o.\", filepath);\n return {};\n }\n\n let module;\n try {\n LOADING_CJS_FILES.add(filepath);\n module = endHiddenCallStack(require)(filepath);\n } finally {\n LOADING_CJS_FILES.delete(filepath);\n }\n\n if (process.env.BABEL_8_BREAKING) {\n return module?.__esModule ? module.default : module;\n } else {\n return module?.__esModule\n ? module.default ||\n /* fallbackToTranspiledModule */ (arguments[1] ? module : undefined)\n : module;\n }\n}\n\nconst loadMjsDefault = endHiddenCallStack(async function loadMjsDefault(\n filepath: string,\n) {\n const url = pathToFileURL(filepath).toString();\n\n if (process.env.BABEL_8_BREAKING) {\n return (await import(url)).default;\n } else {\n if (!import_) {\n throw new ConfigError(\n \"Internal error: Native ECMAScript modules aren't supported by this platform.\\n\",\n filepath,\n );\n }\n\n return (await import_(url)).default;\n }\n});\n\nexport default function* loadCodeDefault(\n filepath: string,\n asyncError: string,\n): Handler {\n switch (path.extname(filepath)) {\n case \".cjs\":\n if (process.env.BABEL_8_BREAKING) {\n return loadCjsDefault(filepath);\n } else {\n return loadCjsDefault(\n filepath,\n // @ts-ignore(Babel 7 vs Babel 8) Removed in Babel 8\n /* fallbackToTranspiledModule */ arguments[2],\n );\n }\n case \".mjs\":\n break;\n case \".cts\":\n return loadCtsDefault(filepath);\n default:\n try {\n if (process.env.BABEL_8_BREAKING) {\n return loadCjsDefault(filepath);\n } else {\n return loadCjsDefault(\n filepath,\n // @ts-ignore(Babel 7 vs Babel 8) Removed in Babel 8\n /* fallbackToTranspiledModule */ arguments[2],\n );\n }\n } catch (e) {\n if (e.code !== \"ERR_REQUIRE_ESM\") throw e;\n }\n }\n if (yield* isAsync()) {\n return yield* waitFor(loadMjsDefault(filepath));\n }\n throw new ConfigError(asyncError, filepath);\n}\n\nfunction loadCtsDefault(filepath: string) {\n const ext = \".cts\";\n const hasTsSupport = !!(\n require.extensions[\".ts\"] ||\n require.extensions[\".cts\"] ||\n require.extensions[\".mts\"]\n );\n\n let handler: NodeJS.RequireExtensions[\"\"];\n\n if (!hasTsSupport) {\n const opts: InputOptions = {\n babelrc: false,\n configFile: false,\n sourceType: \"unambiguous\",\n sourceMaps: \"inline\",\n sourceFileName: path.basename(filepath),\n presets: [\n [\n getTSPreset(filepath),\n {\n onlyRemoveTypeImports: true,\n optimizeConstEnums: true,\n ...(process.env.BABEL_8_BREAKING\n ? {}\n : { allowDeclareFields: true }),\n },\n ],\n ],\n };\n\n handler = function (m, filename) {\n // If we want to support `.ts`, `.d.ts` must be handled specially.\n if (handler && filename.endsWith(ext)) {\n try {\n // @ts-expect-error Undocumented API\n return m._compile(\n transformFileSync(filename, {\n ...opts,\n filename,\n }).code,\n filename,\n );\n } catch (error) {\n if (!hasTsSupport) {\n // TODO(Babel 8): Add this as an optional peer dependency\n // eslint-disable-next-line import/no-extraneous-dependencies\n const packageJson = require(\"@babel/preset-typescript/package.json\");\n if (semver.lt(packageJson.version, \"7.21.4\")) {\n console.error(\n \"`.cts` configuration file failed to load, please try to update `@babel/preset-typescript`.\",\n );\n }\n }\n throw error;\n }\n }\n return require.extensions[\".js\"](m, filename);\n };\n require.extensions[ext] = handler;\n }\n try {\n return loadCjsDefault(filepath);\n } finally {\n if (!hasTsSupport) {\n if (require.extensions[ext] === handler) delete require.extensions[ext];\n handler = undefined;\n }\n }\n}\n\nfunction getTSPreset(filepath: string) {\n try {\n // eslint-disable-next-line import/no-extraneous-dependencies\n return require(\"@babel/preset-typescript\");\n } catch (error) {\n if (error.code !== \"MODULE_NOT_FOUND\") throw error;\n\n let message =\n \"You appear to be using a .cts file as Babel configuration, but the `@babel/preset-typescript` package was not found: please install it!\";\n\n if (!process.env.BABEL_8_BREAKING) {\n if (process.versions.pnp) {\n // Using Yarn PnP, which doesn't allow requiring packages that are not\n // explicitly specified as dependencies.\n message += `\nIf you are using Yarn Plug'n'Play, you may also need to add the following configuration to your .yarnrc.yml file:\n\npackageExtensions:\n\\t\"@babel/core@*\":\n\\t\\tpeerDependencies:\n\\t\\t\\t\"@babel/preset-typescript\": \"*\"\n`;\n }\n }\n\n throw new ConfigError(message, filepath);\n }\n}\n"],"mappings":";;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AAEA,SAAAC,MAAA;EAAA,MAAAC,IAAA,GAAAF,OAAA;EAAAC,KAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAC,KAAA;EAAA,MAAAD,IAAA,GAAAF,OAAA;EAAAG,IAAA,YAAAA,CAAA;IAAA,OAAAD,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,SAAAE,QAAA;EAAA,MAAAF,IAAA,GAAAF,OAAA;EAAAI,OAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAG,OAAA;EAAA,MAAAH,IAAA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gB,EAAE;EACrC,IAAI;IAEF,OAAO7C,OAAO,CAAC,0BAA0B,CAAC;EAC5C,CAAC,CAAC,OAAOmB,KAAK,EAAE;IACd,IAAIA,KAAK,CAACgD,IAAI,KAAK,kBAAkB,EAAE,MAAMhD,KAAK;IAElD,IAAI8E,OAAO,GACT,yIAAyI;IAExG;MACjC,IAAI1D,OAAO,CAACC,QAAQ,CAAC0D,GAAG,EAAE;QAGxBD,OAAO,IAAI;AACnB;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;MACK;IACF;IAEA,MAAM,IAAItC,oBAAW,CAACsC,OAAO,EAAEpD,QAAQ,CAAC;EAC1C;AACF;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/package.js b/node_modules/@babel/core/lib/config/files/package.js new file mode 100644 index 0000000..eed8ab8 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/package.js @@ -0,0 +1,61 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.findPackageData = findPackageData; +function _path() { + const data = require("path"); + _path = function () { + return data; + }; + return data; +} +var _utils = require("./utils.js"); +var _configError = require("../../errors/config-error.js"); +const PACKAGE_FILENAME = "package.json"; +const readConfigPackage = (0, _utils.makeStaticFileCache)((filepath, content) => { + let options; + try { + options = JSON.parse(content); + } catch (err) { + throw new _configError.default(`Error while parsing JSON - ${err.message}`, filepath); + } + if (!options) throw new Error(`${filepath}: No config detected`); + if (typeof options !== "object") { + throw new _configError.default(`Config returned typeof ${typeof options}`, filepath); + } + if (Array.isArray(options)) { + throw new _configError.default(`Expected config object but found array`, filepath); + } + return { + filepath, + dirname: _path().dirname(filepath), + options + }; +}); +function* findPackageData(filepath) { + let pkg = null; + const directories = []; + let isPackage = true; + let dirname = _path().dirname(filepath); + while (!pkg && _path().basename(dirname) !== "node_modules") { + directories.push(dirname); + pkg = yield* readConfigPackage(_path().join(dirname, PACKAGE_FILENAME)); + const nextLoc = _path().dirname(dirname); + if (dirname === nextLoc) { + isPackage = false; + break; + } + dirname = nextLoc; + } + return { + filepath, + directories, + pkg, + isPackage + }; +} +0 && 0; + +//# sourceMappingURL=package.js.map diff --git a/node_modules/@babel/core/lib/config/files/package.js.map b/node_modules/@babel/core/lib/config/files/package.js.map new file mode 100644 index 0000000..bb4b162 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/package.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_path","data","require","_utils","_configError","PACKAGE_FILENAME","readConfigPackage","makeStaticFileCache","filepath","content","options","JSON","parse","err","ConfigError","message","Error","Array","isArray","dirname","path","findPackageData","pkg","directories","isPackage","basename","push","join","nextLoc"],"sources":["../../../src/config/files/package.ts"],"sourcesContent":["import path from \"path\";\nimport type { Handler } from \"gensync\";\nimport { makeStaticFileCache } from \"./utils.ts\";\n\nimport type { ConfigFile, FilePackageData } from \"./types.ts\";\n\nimport ConfigError from \"../../errors/config-error.ts\";\n\nconst PACKAGE_FILENAME = \"package.json\";\n\nconst readConfigPackage = makeStaticFileCache(\n (filepath, content): ConfigFile => {\n let options;\n try {\n options = JSON.parse(content) as unknown;\n } catch (err) {\n throw new ConfigError(\n `Error while parsing JSON - ${err.message}`,\n filepath,\n );\n }\n\n if (!options) throw new Error(`${filepath}: No config detected`);\n\n if (typeof options !== \"object\") {\n throw new ConfigError(\n `Config returned typeof ${typeof options}`,\n filepath,\n );\n }\n if (Array.isArray(options)) {\n throw new ConfigError(`Expected config object but found array`, filepath);\n }\n\n return {\n filepath,\n dirname: path.dirname(filepath),\n options,\n };\n },\n);\n\n/**\n * Find metadata about the package that this file is inside of. Resolution\n * of Babel's config requires general package information to decide when to\n * search for .babelrc files\n */\nexport function* findPackageData(filepath: string): Handler {\n let pkg = null;\n const directories = [];\n let isPackage = true;\n\n let dirname = path.dirname(filepath);\n while (!pkg && path.basename(dirname) !== \"node_modules\") {\n directories.push(dirname);\n\n pkg = yield* readConfigPackage(path.join(dirname, PACKAGE_FILENAME));\n\n const nextLoc = path.dirname(dirname);\n if (dirname === nextLoc) {\n isPackage = false;\n break;\n }\n dirname = nextLoc;\n }\n\n return { filepath, directories, pkg, isPackage };\n}\n"],"mappings":";;;;;;AAAA,SAAAA,MAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,KAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,IAAAE,MAAA,GAAAD,OAAA;AAIA,IAAAE,YAAA,GAAAF,OAAA;AAEA,MAAMG,gBAAgB,GAAG,cAAc;AAEvC,MAAMC,iBAAiB,GAAG,IAAAC,0BAAmB,EAC3C,CAACC,QAAQ,EAAEC,OAAO,KAAiB;EACjC,IAAIC,OAAO;EACX,IAAI;IACFA,OAAO,GAAGC,IAAI,CAACC,KAAK,CAACH,OAAO,CAAY;EAC1C,CAAC,CAAC,OAAOI,GAAG,EAAE;IACZ,MAAM,IAAIC,oBAAW,CACnB,8BAA8BD,GAAG,CAACE,OAAO,EAAE,EAC3CP,QACF,CAAC;EACH;EAEA,IAAI,CAACE,OAAO,EAAE,MAAM,IAAIM,KAAK,CAAC,GAAGR,QAAQ,sBAAsB,CAAC;EAEhE,IAAI,OAAOE,OAAO,KAAK,QAAQ,EAAE;IAC/B,MAAM,IAAII,oBAAW,CACnB,0BAA0B,OAAOJ,OAAO,EAAE,EAC1CF,QACF,CAAC;EACH;EACA,IAAIS,KAAK,CAACC,OAAO,CAACR,OAAO,CAAC,EAAE;IAC1B,MAAM,IAAII,oBAAW,CAAC,wCAAwC,EAAEN,QAAQ,CAAC;EAC3E;EAEA,OAAO;IACLA,QAAQ;IACRW,OAAO,EAAEC,MAAGA,CAAC,CAACD,OAAO,CAACX,QAAQ,CAAC;IAC/BE;EACF,CAAC;AACH,CACF,CAAC;AAOM,UAAUW,eAAeA,CAACb,QAAgB,EAA4B;EAC3E,IAAIc,GAAG,GAAG,IAAI;EACd,MAAMC,WAAW,GAAG,EAAE;EACtB,IAAIC,SAAS,GAAG,IAAI;EAEpB,IAAIL,OAAO,GAAGC,MAAGA,CAAC,CAACD,OAAO,CAACX,QAAQ,CAAC;EACpC,OAAO,CAACc,GAAG,IAAIF,MAAGA,CAAC,CAACK,QAAQ,CAACN,OAAO,CAAC,KAAK,cAAc,EAAE;IACxDI,WAAW,CAACG,IAAI,CAACP,OAAO,CAAC;IAEzBG,GAAG,GAAG,OAAOhB,iBAAiB,CAACc,MAAGA,CAAC,CAACO,IAAI,CAACR,OAAO,EAAEd,gBAAgB,CAAC,CAAC;IAEpE,MAAMuB,OAAO,GAAGR,MAAGA,CAAC,CAACD,OAAO,CAACA,OAAO,CAAC;IACrC,IAAIA,OAAO,KAAKS,OAAO,EAAE;MACvBJ,SAAS,GAAG,KAAK;MACjB;IACF;IACAL,OAAO,GAAGS,OAAO;EACnB;EAEA,OAAO;IAAEpB,QAAQ;IAAEe,WAAW;IAAED,GAAG;IAAEE;EAAU,CAAC;AAClD;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/plugins.js b/node_modules/@babel/core/lib/config/files/plugins.js new file mode 100644 index 0000000..25435ae --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/plugins.js @@ -0,0 +1,217 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.loadPlugin = loadPlugin; +exports.loadPreset = loadPreset; +exports.resolvePreset = exports.resolvePlugin = void 0; +function _debug() { + const data = require("debug"); + _debug = function () { + return data; + }; + return data; +} +function _path() { + const data = require("path"); + _path = function () { + return data; + }; + return data; +} +var _async = require("../../gensync-utils/async.js"); +var _moduleTypes = require("./module-types.js"); +function _url() { + const data = require("url"); + _url = function () { + return data; + }; + return data; +} +var _importMetaResolve = require("../../vendor/import-meta-resolve.js"); +function _fs() { + const data = require("fs"); + _fs = function () { + return data; + }; + return data; +} +const debug = _debug()("babel:config:loading:files:plugins"); +const EXACT_RE = /^module:/; +const BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-plugin-)/; +const BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-preset-)/; +const BABEL_PLUGIN_ORG_RE = /^(@babel\/)(?!plugin-|[^/]+\/)/; +const BABEL_PRESET_ORG_RE = /^(@babel\/)(?!preset-|[^/]+\/)/; +const OTHER_PLUGIN_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-plugin(?:-|\/|$)|[^/]+\/)/; +const OTHER_PRESET_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-preset(?:-|\/|$)|[^/]+\/)/; +const OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/; +const resolvePlugin = exports.resolvePlugin = resolveStandardizedName.bind(null, "plugin"); +const resolvePreset = exports.resolvePreset = resolveStandardizedName.bind(null, "preset"); +function* loadPlugin(name, dirname) { + const filepath = resolvePlugin(name, dirname, yield* (0, _async.isAsync)()); + const value = yield* requireModule("plugin", filepath); + debug("Loaded plugin %o from %o.", name, dirname); + return { + filepath, + value + }; +} +function* loadPreset(name, dirname) { + const filepath = resolvePreset(name, dirname, yield* (0, _async.isAsync)()); + const value = yield* requireModule("preset", filepath); + debug("Loaded preset %o from %o.", name, dirname); + return { + filepath, + value + }; +} +function standardizeName(type, name) { + if (_path().isAbsolute(name)) return name; + const isPreset = type === "preset"; + return name.replace(isPreset ? BABEL_PRESET_PREFIX_RE : BABEL_PLUGIN_PREFIX_RE, `babel-${type}-`).replace(isPreset ? BABEL_PRESET_ORG_RE : BABEL_PLUGIN_ORG_RE, `$1${type}-`).replace(isPreset ? OTHER_PRESET_ORG_RE : OTHER_PLUGIN_ORG_RE, `$1babel-${type}-`).replace(OTHER_ORG_DEFAULT_RE, `$1/babel-${type}`).replace(EXACT_RE, ""); +} +function* resolveAlternativesHelper(type, name) { + const standardizedName = standardizeName(type, name); + const { + error, + value + } = yield standardizedName; + if (!error) return value; + if (error.code !== "MODULE_NOT_FOUND") throw error; + if (standardizedName !== name && !(yield name).error) { + error.message += `\n- If you want to resolve "${name}", use "module:${name}"`; + } + if (!(yield standardizeName(type, "@babel/" + name)).error) { + error.message += `\n- Did you mean "@babel/${name}"?`; + } + const oppositeType = type === "preset" ? "plugin" : "preset"; + if (!(yield standardizeName(oppositeType, name)).error) { + error.message += `\n- Did you accidentally pass a ${oppositeType} as a ${type}?`; + } + if (type === "plugin") { + const transformName = standardizedName.replace("-proposal-", "-transform-"); + if (transformName !== standardizedName && !(yield transformName).error) { + error.message += `\n- Did you mean "${transformName}"?`; + } + } + error.message += `\n +Make sure that all the Babel plugins and presets you are using +are defined as dependencies or devDependencies in your package.json +file. It's possible that the missing plugin is loaded by a preset +you are using that forgot to add the plugin to its dependencies: you +can workaround this problem by explicitly adding the missing package +to your top-level package.json. +`; + throw error; +} +function tryRequireResolve(id, dirname) { + try { + if (dirname) { + return { + error: null, + value: (((v, w) => (v = v.split("."), w = w.split("."), +v[0] > +w[0] || v[0] == w[0] && +v[1] >= +w[1]))(process.versions.node, "8.9") ? require.resolve : (r, { + paths: [b] + }, M = require("module")) => { + let f = M._findPath(r, M._nodeModulePaths(b).concat(b)); + if (f) return f; + f = new Error(`Cannot resolve module '${r}'`); + f.code = "MODULE_NOT_FOUND"; + throw f; + })(id, { + paths: [dirname] + }) + }; + } else { + return { + error: null, + value: require.resolve(id) + }; + } + } catch (error) { + return { + error, + value: null + }; + } +} +function tryImportMetaResolve(id, options) { + try { + return { + error: null, + value: (0, _importMetaResolve.resolve)(id, options) + }; + } catch (error) { + return { + error, + value: null + }; + } +} +function resolveStandardizedNameForRequire(type, name, dirname) { + const it = resolveAlternativesHelper(type, name); + let res = it.next(); + while (!res.done) { + res = it.next(tryRequireResolve(res.value, dirname)); + } + return res.value; +} +function resolveStandardizedNameForImport(type, name, dirname) { + const parentUrl = (0, _url().pathToFileURL)(_path().join(dirname, "./babel-virtual-resolve-base.js")).href; + const it = resolveAlternativesHelper(type, name); + let res = it.next(); + while (!res.done) { + res = it.next(tryImportMetaResolve(res.value, parentUrl)); + } + return (0, _url().fileURLToPath)(res.value); +} +function resolveStandardizedName(type, name, dirname, resolveESM) { + if (!_moduleTypes.supportsESM || !resolveESM) { + return resolveStandardizedNameForRequire(type, name, dirname); + } + try { + const resolved = resolveStandardizedNameForImport(type, name, dirname); + if (!(0, _fs().existsSync)(resolved)) { + throw Object.assign(new Error(`Could not resolve "${name}" in file ${dirname}.`), { + type: "MODULE_NOT_FOUND" + }); + } + return resolved; + } catch (e) { + try { + return resolveStandardizedNameForRequire(type, name, dirname); + } catch (e2) { + if (e.type === "MODULE_NOT_FOUND") throw e; + if (e2.type === "MODULE_NOT_FOUND") throw e2; + throw e; + } + } +} +{ + var LOADING_MODULES = new Set(); +} +function* requireModule(type, name) { + { + if (!(yield* (0, _async.isAsync)()) && LOADING_MODULES.has(name)) { + throw new Error(`Reentrant ${type} detected trying to load "${name}". This module is not ignored ` + "and is trying to load itself while compiling itself, leading to a dependency cycle. " + 'We recommend adding it to your "ignore" list in your babelrc, or to a .babelignore.'); + } + } + try { + { + LOADING_MODULES.add(name); + } + { + return yield* (0, _moduleTypes.default)(name, `You appear to be using a native ECMAScript module ${type}, ` + "which is only supported when running Babel asynchronously.", true); + } + } catch (err) { + err.message = `[BABEL]: ${err.message} (While processing: ${name})`; + throw err; + } finally { + { + LOADING_MODULES.delete(name); + } + } +} +0 && 0; + +//# sourceMappingURL=plugins.js.map diff --git a/node_modules/@babel/core/lib/config/files/plugins.js.map b/node_modules/@babel/core/lib/config/files/plugins.js.map new file mode 100644 index 0000000..e6fe3ff --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/plugins.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_debug","data","require","_path","_async","_moduleTypes","_url","_importMetaResolve","_fs","debug","buildDebug","EXACT_RE","BABEL_PLUGIN_PREFIX_RE","BABEL_PRESET_PREFIX_RE","BABEL_PLUGIN_ORG_RE","BABEL_PRESET_ORG_RE","OTHER_PLUGIN_ORG_RE","OTHER_PRESET_ORG_RE","OTHER_ORG_DEFAULT_RE","resolvePlugin","exports","resolveStandardizedName","bind","resolvePreset","loadPlugin","name","dirname","filepath","isAsync","value","requireModule","loadPreset","standardizeName","type","path","isAbsolute","isPreset","replace","resolveAlternativesHelper","standardizedName","error","code","message","oppositeType","transformName","tryRequireResolve","id","v","w","split","process","versions","node","resolve","r","paths","b","M","f","_findPath","_nodeModulePaths","concat","Error","tryImportMetaResolve","options","importMetaResolve","resolveStandardizedNameForRequire","it","res","next","done","resolveStandardizedNameForImport","parentUrl","pathToFileURL","join","href","fileURLToPath","resolveESM","supportsESM","resolved","existsSync","Object","assign","e","e2","LOADING_MODULES","Set","has","add","loadCodeDefault","err","delete"],"sources":["../../../src/config/files/plugins.ts"],"sourcesContent":["/**\n * This file handles all logic for converting string-based configuration references into loaded objects.\n */\n\nimport buildDebug from \"debug\";\nimport path from \"path\";\nimport type { Handler } from \"gensync\";\nimport { isAsync } from \"../../gensync-utils/async.ts\";\nimport loadCodeDefault, { supportsESM } from \"./module-types.ts\";\nimport { fileURLToPath, pathToFileURL } from \"url\";\n\nimport { resolve as importMetaResolve } from \"../../vendor/import-meta-resolve.js\";\n\nimport { createRequire } from \"module\";\nimport { existsSync } from \"fs\";\nconst require = createRequire(import.meta.url);\n\nconst debug = buildDebug(\"babel:config:loading:files:plugins\");\n\nconst EXACT_RE = /^module:/;\nconst BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\\/|babel-plugin-)/;\nconst BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\\/|babel-preset-)/;\nconst BABEL_PLUGIN_ORG_RE = /^(@babel\\/)(?!plugin-|[^/]+\\/)/;\nconst BABEL_PRESET_ORG_RE = /^(@babel\\/)(?!preset-|[^/]+\\/)/;\nconst OTHER_PLUGIN_ORG_RE =\n /^(@(?!babel\\/)[^/]+\\/)(?![^/]*babel-plugin(?:-|\\/|$)|[^/]+\\/)/;\nconst OTHER_PRESET_ORG_RE =\n /^(@(?!babel\\/)[^/]+\\/)(?![^/]*babel-preset(?:-|\\/|$)|[^/]+\\/)/;\nconst OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/;\n\nexport const resolvePlugin = resolveStandardizedName.bind(null, \"plugin\");\nexport const resolvePreset = resolveStandardizedName.bind(null, \"preset\");\n\nexport function* loadPlugin(\n name: string,\n dirname: string,\n): Handler<{ filepath: string; value: unknown }> {\n const filepath = resolvePlugin(name, dirname, yield* isAsync());\n\n const value = yield* requireModule(\"plugin\", filepath);\n debug(\"Loaded plugin %o from %o.\", name, dirname);\n\n return { filepath, value };\n}\n\nexport function* loadPreset(\n name: string,\n dirname: string,\n): Handler<{ filepath: string; value: unknown }> {\n const filepath = resolvePreset(name, dirname, yield* isAsync());\n\n const value = yield* requireModule(\"preset\", filepath);\n\n debug(\"Loaded preset %o from %o.\", name, dirname);\n\n return { filepath, value };\n}\n\nfunction standardizeName(type: \"plugin\" | \"preset\", name: string) {\n // Let absolute and relative paths through.\n if (path.isAbsolute(name)) return name;\n\n const isPreset = type === \"preset\";\n\n return (\n name\n // foo -> babel-preset-foo\n .replace(\n isPreset ? BABEL_PRESET_PREFIX_RE : BABEL_PLUGIN_PREFIX_RE,\n `babel-${type}-`,\n )\n // @babel/es2015 -> @babel/preset-es2015\n .replace(\n isPreset ? BABEL_PRESET_ORG_RE : BABEL_PLUGIN_ORG_RE,\n `$1${type}-`,\n )\n // @foo/mypreset -> @foo/babel-preset-mypreset\n .replace(\n isPreset ? OTHER_PRESET_ORG_RE : OTHER_PLUGIN_ORG_RE,\n `$1babel-${type}-`,\n )\n // @foo -> @foo/babel-preset\n .replace(OTHER_ORG_DEFAULT_RE, `$1/babel-${type}`)\n // module:mypreset -> mypreset\n .replace(EXACT_RE, \"\")\n );\n}\n\ntype Result = { error: Error; value: null } | { error: null; value: T };\n\nfunction* resolveAlternativesHelper(\n type: \"plugin\" | \"preset\",\n name: string,\n): Iterator> {\n const standardizedName = standardizeName(type, name);\n const { error, value } = yield standardizedName;\n if (!error) return value;\n\n // @ts-expect-error code may not index error\n if (error.code !== \"MODULE_NOT_FOUND\") throw error;\n\n if (standardizedName !== name && !(yield name).error) {\n error.message += `\\n- If you want to resolve \"${name}\", use \"module:${name}\"`;\n }\n\n if (!(yield standardizeName(type, \"@babel/\" + name)).error) {\n error.message += `\\n- Did you mean \"@babel/${name}\"?`;\n }\n\n const oppositeType = type === \"preset\" ? \"plugin\" : \"preset\";\n if (!(yield standardizeName(oppositeType, name)).error) {\n error.message += `\\n- Did you accidentally pass a ${oppositeType} as a ${type}?`;\n }\n\n if (type === \"plugin\") {\n const transformName = standardizedName.replace(\"-proposal-\", \"-transform-\");\n if (transformName !== standardizedName && !(yield transformName).error) {\n error.message += `\\n- Did you mean \"${transformName}\"?`;\n }\n }\n\n error.message += `\\n\nMake sure that all the Babel plugins and presets you are using\nare defined as dependencies or devDependencies in your package.json\nfile. It's possible that the missing plugin is loaded by a preset\nyou are using that forgot to add the plugin to its dependencies: you\ncan workaround this problem by explicitly adding the missing package\nto your top-level package.json.\n`;\n\n throw error;\n}\n\nfunction tryRequireResolve(\n id: string,\n dirname: string | undefined,\n): Result {\n try {\n if (dirname) {\n return { error: null, value: require.resolve(id, { paths: [dirname] }) };\n } else {\n return { error: null, value: require.resolve(id) };\n }\n } catch (error) {\n return { error, value: null };\n }\n}\n\nfunction tryImportMetaResolve(\n id: Parameters[0],\n options: Parameters[1],\n): Result {\n try {\n return { error: null, value: importMetaResolve(id, options) };\n } catch (error) {\n return { error, value: null };\n }\n}\n\nfunction resolveStandardizedNameForRequire(\n type: \"plugin\" | \"preset\",\n name: string,\n dirname: string,\n) {\n const it = resolveAlternativesHelper(type, name);\n let res = it.next();\n while (!res.done) {\n res = it.next(tryRequireResolve(res.value, dirname));\n }\n return res.value;\n}\nfunction resolveStandardizedNameForImport(\n type: \"plugin\" | \"preset\",\n name: string,\n dirname: string,\n) {\n const parentUrl = pathToFileURL(\n path.join(dirname, \"./babel-virtual-resolve-base.js\"),\n ).href;\n\n const it = resolveAlternativesHelper(type, name);\n let res = it.next();\n while (!res.done) {\n res = it.next(tryImportMetaResolve(res.value, parentUrl));\n }\n return fileURLToPath(res.value);\n}\n\nfunction resolveStandardizedName(\n type: \"plugin\" | \"preset\",\n name: string,\n dirname: string,\n resolveESM: boolean,\n) {\n if (!supportsESM || !resolveESM) {\n return resolveStandardizedNameForRequire(type, name, dirname);\n }\n\n try {\n const resolved = resolveStandardizedNameForImport(type, name, dirname);\n // import-meta-resolve 4.0 does not throw if the module is not found.\n if (!existsSync(resolved)) {\n throw Object.assign(\n new Error(`Could not resolve \"${name}\" in file ${dirname}.`),\n { type: \"MODULE_NOT_FOUND\" },\n );\n }\n return resolved;\n } catch (e) {\n try {\n return resolveStandardizedNameForRequire(type, name, dirname);\n } catch (e2) {\n if (e.type === \"MODULE_NOT_FOUND\") throw e;\n if (e2.type === \"MODULE_NOT_FOUND\") throw e2;\n throw e;\n }\n }\n}\n\nif (!process.env.BABEL_8_BREAKING) {\n // eslint-disable-next-line no-var\n var LOADING_MODULES = new Set();\n}\nfunction* requireModule(type: string, name: string): Handler {\n if (!process.env.BABEL_8_BREAKING) {\n if (!(yield* isAsync()) && LOADING_MODULES.has(name)) {\n throw new Error(\n `Reentrant ${type} detected trying to load \"${name}\". This module is not ignored ` +\n \"and is trying to load itself while compiling itself, leading to a dependency cycle. \" +\n 'We recommend adding it to your \"ignore\" list in your babelrc, or to a .babelignore.',\n );\n }\n }\n\n try {\n if (!process.env.BABEL_8_BREAKING) {\n LOADING_MODULES.add(name);\n }\n\n if (process.env.BABEL_8_BREAKING) {\n return yield* loadCodeDefault(\n name,\n `You appear to be using a native ECMAScript module ${type}, ` +\n \"which is only supported when running Babel asynchronously.\",\n );\n } else {\n return yield* loadCodeDefault(\n name,\n `You appear to be using a native ECMAScript module ${type}, ` +\n \"which is only supported when running Babel asynchronously.\",\n // For backward compatibility, we need to support malformed presets\n // defined as separate named exports rather than a single default\n // export.\n // See packages/babel-core/test/fixtures/option-manager/presets/es2015_named.js\n // @ts-ignore(Babel 7 vs Babel 8) This param has been removed\n true,\n );\n }\n } catch (err) {\n err.message = `[BABEL]: ${err.message} (While processing: ${name})`;\n throw err;\n } finally {\n if (!process.env.BABEL_8_BREAKING) {\n LOADING_MODULES.delete(name);\n }\n }\n}\n"],"mappings":";;;;;;;;AAIA,SAAAA,OAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,MAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,MAAA;EAAA,MAAAF,IAAA,GAAAC,OAAA;EAAAC,KAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,IAAAG,MAAA,GAAAF,OAAA;AACA,IAAAG,YAAA,GAAAH,OAAA;AACA,SAAAI,KAAA;EAAA,MAAAL,IAAA,GAAAC,OAAA;EAAAI,IAAA,YAAAA,CAAA;IAAA,OAAAL,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,IAAAM,kBAAA,GAAAL,OAAA;AAGA,SAAAM,IAAA;EAAA,MAAAP,IAAA,GAAAC,OAAA;EAAAM,GAAA,YAAAA,CAAA;IAAA,OAAAP,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAGA,MAAMQ,KAAK,GAAGC,OAASA,CAAC,CAAC,oCAAoC,CAAC;AAE9D,MAAMC,QAAQ,GAAG,UAAU;AAC3B,MAAMC,sBAAsB,GAAG,sCAAsC;AACrE,MAAMC,sBAAsB,GAAG,sCAAsC;AACrE,MAAMC,mBAAmB,GAAG,gCAAgC;AAC5D,MAAMC,mBAAmB,GAAG,gCAAgC;AAC5D,MAAMC,mBAAmB,GACvB,+DAA+D;AACjE,MAAMC,mBAAmB,GACvB,+DAA+D;AACjE,MAAMC,oBAAoB,GAAG,sBAAsB;AAE5C,MAAMC,aAAa,GAAAC,OAAA,CAAAD,aAAA,GAAGE,uBAAuB,CAACC,IAAI,CAAC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,OAAO,IAAAgE,oBAAe,EAC3BhE,IAAI,EACJ,qDAAqDQ,IAAI,IAAI,GAC3D,4DAA4D,EAM9D,IACF,CAAC;IACH;EACF,CAAC,CAAC,OAAOyD,GAAG,EAAE;IACZA,GAAG,CAAChD,OAAO,GAAG,YAAYgD,GAAG,CAAChD,OAAO,uBAAuBjB,IAAI,GAAG;IACnE,MAAMiE,GAAG;EACX,CAAC,SAAS;IAC2B;MACjCL,eAAe,CAACM,MAAM,CAAClE,IAAI,CAAC;IAC9B;EACF;AACF;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/types.js b/node_modules/@babel/core/lib/config/files/types.js new file mode 100644 index 0000000..c03b5a6 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/types.js @@ -0,0 +1,3 @@ +0 && 0; + +//# sourceMappingURL=types.js.map diff --git a/node_modules/@babel/core/lib/config/files/types.js.map b/node_modules/@babel/core/lib/config/files/types.js.map new file mode 100644 index 0000000..bce052a --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/types.js.map @@ -0,0 +1 @@ +{"version":3,"names":[],"sources":["../../../src/config/files/types.ts"],"sourcesContent":["import type { InputOptions } from \"../index.ts\";\n\nexport type ConfigFile = {\n filepath: string;\n dirname: string;\n options: InputOptions & { babel?: unknown };\n};\n\nexport type IgnoreFile = {\n filepath: string;\n dirname: string;\n ignore: Array;\n};\n\nexport type RelativeConfig = {\n // The actual config, either from package.json#babel, .babelrc, or\n // .babelrc.js, if there was one.\n config: ConfigFile | null;\n // The .babelignore, if there was one.\n ignore: IgnoreFile | null;\n};\n\nexport type FilePackageData = {\n // The file in the package.\n filepath: string;\n // Any ancestor directories of the file that are within the package.\n directories: Array;\n // The contents of the package.json. May not be found if the package just\n // terminated at a node_modules folder without finding one.\n pkg: ConfigFile | null;\n // True if a package.json or node_modules folder was found while traversing\n // the directory structure.\n isPackage: boolean;\n};\n"],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/utils.js b/node_modules/@babel/core/lib/config/files/utils.js new file mode 100644 index 0000000..406aab9 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/utils.js @@ -0,0 +1,36 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.makeStaticFileCache = makeStaticFileCache; +var _caching = require("../caching.js"); +var fs = require("../../gensync-utils/fs.js"); +function _fs2() { + const data = require("fs"); + _fs2 = function () { + return data; + }; + return data; +} +function makeStaticFileCache(fn) { + return (0, _caching.makeStrongCache)(function* (filepath, cache) { + const cached = cache.invalidate(() => fileMtime(filepath)); + if (cached === null) { + return null; + } + return fn(filepath, yield* fs.readFile(filepath, "utf8")); + }); +} +function fileMtime(filepath) { + if (!_fs2().existsSync(filepath)) return null; + try { + return +_fs2().statSync(filepath).mtime; + } catch (e) { + if (e.code !== "ENOENT" && e.code !== "ENOTDIR") throw e; + } + return null; +} +0 && 0; + +//# sourceMappingURL=utils.js.map diff --git a/node_modules/@babel/core/lib/config/files/utils.js.map b/node_modules/@babel/core/lib/config/files/utils.js.map new file mode 100644 index 0000000..d496903 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/utils.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_caching","require","fs","_fs2","data","makeStaticFileCache","fn","makeStrongCache","filepath","cache","cached","invalidate","fileMtime","readFile","nodeFs","existsSync","statSync","mtime","e","code"],"sources":["../../../src/config/files/utils.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\n\nimport { makeStrongCache } from \"../caching.ts\";\nimport type { CacheConfigurator } from \"../caching.ts\";\nimport * as fs from \"../../gensync-utils/fs.ts\";\nimport nodeFs from \"fs\";\n\nexport function makeStaticFileCache(\n fn: (filepath: string, contents: string) => T,\n) {\n return makeStrongCache(function* (\n filepath: string,\n cache: CacheConfigurator,\n ): Handler {\n const cached = cache.invalidate(() => fileMtime(filepath));\n\n if (cached === null) {\n return null;\n }\n\n return fn(filepath, yield* fs.readFile(filepath, \"utf8\"));\n });\n}\n\nfunction fileMtime(filepath: string): number | null {\n if (!nodeFs.existsSync(filepath)) return null;\n\n try {\n return +nodeFs.statSync(filepath).mtime;\n } catch (e) {\n if (e.code !== \"ENOENT\" && e.code !== \"ENOTDIR\") throw e;\n }\n\n return null;\n}\n"],"mappings":";;;;;;AAEA,IAAAA,QAAA,GAAAC,OAAA;AAEA,IAAAC,EAAA,GAAAD,OAAA;AACA,SAAAE,KAAA;EAAA,MAAAC,IAAA,GAAAH,OAAA;EAAAE,IAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEO,SAASC,mBAAmBA,CACjCC,EAA6C,EAC7C;EACA,OAAO,IAAAC,wBAAe,EAAC,WACrBC,QAAgB,EAChBC,KAA8B,EACX;IACnB,MAAMC,MAAM,GAAGD,KAAK,CAACE,UAAU,CAAC,MAAMC,SAAS,CAACJ,QAAQ,CAAC,CAAC;IAE1D,IAAIE,MAAM,KAAK,IAAI,EAAE;MACnB,OAAO,IAAI;IACb;IAEA,OAAOJ,EAAE,CAACE,QAAQ,EAAE,OAAON,EAAE,CAACW,QAAQ,CAACL,QAAQ,EAAE,MAAM,CAAC,CAAC;EAC3D,CAAC,CAAC;AACJ;AAEA,SAASI,SAASA,CAACJ,QAAgB,EAAiB;EAClD,IAAI,CAACM,KAAKA,CAAC,CAACC,UAAU,CAACP,QAAQ,CAAC,EAAE,OAAO,IAAI;EAE7C,IAAI;IACF,OAAO,CAACM,KAAKA,CAAC,CAACE,QAAQ,CAACR,QAAQ,CAAC,CAACS,KAAK;EACzC,CAAC,CAAC,OAAOC,CAAC,EAAE;IACV,IAAIA,CAAC,CAACC,IAAI,KAAK,QAAQ,IAAID,CAAC,CAACC,IAAI,KAAK,SAAS,EAAE,MAAMD,CAAC;EAC1D;EAEA,OAAO,IAAI;AACb;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/full.js b/node_modules/@babel/core/lib/config/full.js new file mode 100644 index 0000000..6b8c295 --- /dev/null +++ b/node_modules/@babel/core/lib/config/full.js @@ -0,0 +1,310 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +function _gensync() { + const data = require("gensync"); + _gensync = function () { + return data; + }; + return data; +} +var _async = require("../gensync-utils/async.js"); +var _util = require("./util.js"); +var context = require("../index.js"); +var _plugin = require("./plugin.js"); +var _item = require("./item.js"); +var _configChain = require("./config-chain.js"); +var _deepArray = require("./helpers/deep-array.js"); +function _traverse() { + const data = require("@babel/traverse"); + _traverse = function () { + return data; + }; + return data; +} +var _caching = require("./caching.js"); +var _options = require("./validation/options.js"); +var _plugins = require("./validation/plugins.js"); +var _configApi = require("./helpers/config-api.js"); +var _partial = require("./partial.js"); +var _configError = require("../errors/config-error.js"); +var _default = exports.default = _gensync()(function* loadFullConfig(inputOpts) { + var _opts$assumptions; + const result = yield* (0, _partial.default)(inputOpts); + if (!result) { + return null; + } + const { + options, + context, + fileHandling + } = result; + if (fileHandling === "ignored") { + return null; + } + const optionDefaults = {}; + const { + plugins, + presets + } = options; + if (!plugins || !presets) { + throw new Error("Assertion failure - plugins and presets exist"); + } + const presetContext = Object.assign({}, context, { + targets: options.targets + }); + const toDescriptor = item => { + const desc = (0, _item.getItemDescriptor)(item); + if (!desc) { + throw new Error("Assertion failure - must be config item"); + } + return desc; + }; + const presetsDescriptors = presets.map(toDescriptor); + const initialPluginsDescriptors = plugins.map(toDescriptor); + const pluginDescriptorsByPass = [[]]; + const passes = []; + const externalDependencies = []; + const ignored = yield* enhanceError(context, function* recursePresetDescriptors(rawPresets, pluginDescriptorsPass) { + const presets = []; + for (let i = 0; i < rawPresets.length; i++) { + const descriptor = rawPresets[i]; + if (descriptor.options !== false) { + try { + var preset = yield* loadPresetDescriptor(descriptor, presetContext); + } catch (e) { + if (e.code === "BABEL_UNKNOWN_OPTION") { + (0, _options.checkNoUnwrappedItemOptionPairs)(rawPresets, i, "preset", e); + } + throw e; + } + externalDependencies.push(preset.externalDependencies); + if (descriptor.ownPass) { + presets.push({ + preset: preset.chain, + pass: [] + }); + } else { + presets.unshift({ + preset: preset.chain, + pass: pluginDescriptorsPass + }); + } + } + } + if (presets.length > 0) { + pluginDescriptorsByPass.splice(1, 0, ...presets.map(o => o.pass).filter(p => p !== pluginDescriptorsPass)); + for (const { + preset, + pass + } of presets) { + if (!preset) return true; + pass.push(...preset.plugins); + const ignored = yield* recursePresetDescriptors(preset.presets, pass); + if (ignored) return true; + preset.options.forEach(opts => { + (0, _util.mergeOptions)(optionDefaults, opts); + }); + } + } + })(presetsDescriptors, pluginDescriptorsByPass[0]); + if (ignored) return null; + const opts = optionDefaults; + (0, _util.mergeOptions)(opts, options); + const pluginContext = Object.assign({}, presetContext, { + assumptions: (_opts$assumptions = opts.assumptions) != null ? _opts$assumptions : {} + }); + yield* enhanceError(context, function* loadPluginDescriptors() { + pluginDescriptorsByPass[0].unshift(...initialPluginsDescriptors); + for (const descs of pluginDescriptorsByPass) { + const pass = []; + passes.push(pass); + for (let i = 0; i < descs.length; i++) { + const descriptor = descs[i]; + if (descriptor.options !== false) { + try { + var plugin = yield* loadPluginDescriptor(descriptor, pluginContext); + } catch (e) { + if (e.code === "BABEL_UNKNOWN_PLUGIN_PROPERTY") { + (0, _options.checkNoUnwrappedItemOptionPairs)(descs, i, "plugin", e); + } + throw e; + } + pass.push(plugin); + externalDependencies.push(plugin.externalDependencies); + } + } + } + })(); + opts.plugins = passes[0]; + opts.presets = passes.slice(1).filter(plugins => plugins.length > 0).map(plugins => ({ + plugins + })); + opts.passPerPreset = opts.presets.length > 0; + return { + options: opts, + passes: passes, + externalDependencies: (0, _deepArray.finalize)(externalDependencies) + }; +}); +function enhanceError(context, fn) { + return function* (arg1, arg2) { + try { + return yield* fn(arg1, arg2); + } catch (e) { + if (!/^\[BABEL\]/.test(e.message)) { + var _context$filename; + e.message = `[BABEL] ${(_context$filename = context.filename) != null ? _context$filename : "unknown file"}: ${e.message}`; + } + throw e; + } + }; +} +const makeDescriptorLoader = apiFactory => (0, _caching.makeWeakCache)(function* ({ + value, + options, + dirname, + alias +}, cache) { + if (options === false) throw new Error("Assertion failure"); + options = options || {}; + const externalDependencies = []; + let item = value; + if (typeof value === "function") { + const factory = (0, _async.maybeAsync)(value, `You appear to be using an async plugin/preset, but Babel has been called synchronously`); + const api = Object.assign({}, context, apiFactory(cache, externalDependencies)); + try { + item = yield* factory(api, options, dirname); + } catch (e) { + if (alias) { + e.message += ` (While processing: ${JSON.stringify(alias)})`; + } + throw e; + } + } + if (!item || typeof item !== "object") { + throw new Error("Plugin/Preset did not return an object."); + } + if ((0, _async.isThenable)(item)) { + yield* []; + throw new Error(`You appear to be using a promise as a plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version. ` + `As an alternative, you can prefix the promise with "await". ` + `(While processing: ${JSON.stringify(alias)})`); + } + if (externalDependencies.length > 0 && (!cache.configured() || cache.mode() === "forever")) { + let error = `A plugin/preset has external untracked dependencies ` + `(${externalDependencies[0]}), but the cache `; + if (!cache.configured()) { + error += `has not been configured to be invalidated when the external dependencies change. `; + } else { + error += ` has been configured to never be invalidated. `; + } + error += `Plugins/presets should configure their cache to be invalidated when the external ` + `dependencies change, for example using \`api.cache.invalidate(() => ` + `statSync(filepath).mtimeMs)\` or \`api.cache.never()\`\n` + `(While processing: ${JSON.stringify(alias)})`; + throw new Error(error); + } + return { + value: item, + options, + dirname, + alias, + externalDependencies: (0, _deepArray.finalize)(externalDependencies) + }; +}); +const pluginDescriptorLoader = makeDescriptorLoader(_configApi.makePluginAPI); +const presetDescriptorLoader = makeDescriptorLoader(_configApi.makePresetAPI); +const instantiatePlugin = (0, _caching.makeWeakCache)(function* ({ + value, + options, + dirname, + alias, + externalDependencies +}, cache) { + const pluginObj = (0, _plugins.validatePluginObject)(value); + const plugin = Object.assign({}, pluginObj); + if (plugin.visitor) { + plugin.visitor = _traverse().default.explode(Object.assign({}, plugin.visitor)); + } + if (plugin.inherits) { + const inheritsDescriptor = { + name: undefined, + alias: `${alias}$inherits`, + value: plugin.inherits, + options, + dirname + }; + const inherits = yield* (0, _async.forwardAsync)(loadPluginDescriptor, run => { + return cache.invalidate(data => run(inheritsDescriptor, data)); + }); + plugin.pre = chain(inherits.pre, plugin.pre); + plugin.post = chain(inherits.post, plugin.post); + plugin.manipulateOptions = chain(inherits.manipulateOptions, plugin.manipulateOptions); + plugin.visitor = _traverse().default.visitors.merge([inherits.visitor || {}, plugin.visitor || {}]); + if (inherits.externalDependencies.length > 0) { + if (externalDependencies.length === 0) { + externalDependencies = inherits.externalDependencies; + } else { + externalDependencies = (0, _deepArray.finalize)([externalDependencies, inherits.externalDependencies]); + } + } + } + return new _plugin.default(plugin, options, alias, externalDependencies); +}); +function* loadPluginDescriptor(descriptor, context) { + if (descriptor.value instanceof _plugin.default) { + if (descriptor.options) { + throw new Error("Passed options to an existing Plugin instance will not work."); + } + return descriptor.value; + } + return yield* instantiatePlugin(yield* pluginDescriptorLoader(descriptor, context), context); +} +const needsFilename = val => val && typeof val !== "function"; +const validateIfOptionNeedsFilename = (options, descriptor) => { + if (needsFilename(options.test) || needsFilename(options.include) || needsFilename(options.exclude)) { + const formattedPresetName = descriptor.name ? `"${descriptor.name}"` : "/* your preset */"; + throw new _configError.default([`Preset ${formattedPresetName} requires a filename to be set when babel is called directly,`, `\`\`\``, `babel.transformSync(code, { filename: 'file.ts', presets: [${formattedPresetName}] });`, `\`\`\``, `See https://babeljs.io/docs/en/options#filename for more information.`].join("\n")); + } +}; +const validatePreset = (preset, context, descriptor) => { + if (!context.filename) { + var _options$overrides; + const { + options + } = preset; + validateIfOptionNeedsFilename(options, descriptor); + (_options$overrides = options.overrides) == null || _options$overrides.forEach(overrideOptions => validateIfOptionNeedsFilename(overrideOptions, descriptor)); + } +}; +const instantiatePreset = (0, _caching.makeWeakCacheSync)(({ + value, + dirname, + alias, + externalDependencies +}) => { + return { + options: (0, _options.validate)("preset", value), + alias, + dirname, + externalDependencies + }; +}); +function* loadPresetDescriptor(descriptor, context) { + const preset = instantiatePreset(yield* presetDescriptorLoader(descriptor, context)); + validatePreset(preset, context, descriptor); + return { + chain: yield* (0, _configChain.buildPresetChain)(preset, context), + externalDependencies: preset.externalDependencies + }; +} +function chain(a, b) { + const fns = [a, b].filter(Boolean); + if (fns.length <= 1) return fns[0]; + return function (...args) { + for (const fn of fns) { + fn.apply(this, args); + } + }; +} +0 && 0; + +//# sourceMappingURL=full.js.map diff --git a/node_modules/@babel/core/lib/config/full.js.map b/node_modules/@babel/core/lib/config/full.js.map new file mode 100644 index 0000000..63b3741 --- /dev/null +++ b/node_modules/@babel/core/lib/config/full.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_gensync","data","require","_async","_util","context","_plugin","_item","_configChain","_deepArray","_traverse","_caching","_options","_plugins","_configApi","_partial","_configError","_default","exports","default","gensync","loadFullConfig","inputOpts","_opts$assumptions","result","loadPrivatePartialConfig","options","fileHandling","optionDefaults","plugins","presets","Error","presetContext","Object","assign","targets","toDescriptor","item","desc","getItemDescriptor","presetsDescriptors","map","initialPluginsDescriptors","pluginDescriptorsByPass","passes","externalDependencies","ignored","enhanceError","recursePresetDescriptors","rawPresets","pluginDescriptorsPass","i","length","descriptor","preset","loadPresetDescriptor","e","code","checkNoUnwrappedItemOptionPairs","push","ownPass","chain","pass","unshift","splice","o","filter","p","forEach","opts","mergeOptions","pluginContext","assumptions","loadPluginDescriptors","descs","plugin","loadPluginDescriptor","slice","passPerPreset","freezeDeepArray","fn","arg1","arg2","test","message","_context$filename","filename","makeDescriptorLoader","apiFactory","makeWeakCache","value","dirname","alias","cache","factory","maybeAsync","api","JSON","stringify","isThenable","configured","mode","error","pluginDescriptorLoader","makePluginAPI","presetDescriptorLoader","makePresetAPI","instantiatePlugin","pluginObj","validatePluginObject","visitor","traverse","explode","inherits","inheritsDescriptor","name","undefined","forwardAsync","run","invalidate","pre","post","manipulateOptions","visitors","merge","Plugin","needsFilename","val","validateIfOptionNeedsFilename","include","exclude","formattedPresetName","ConfigError","join","validatePreset","_options$overrides","overrides","overrideOptions","instantiatePreset","makeWeakCacheSync","validate","buildPresetChain","a","b","fns","Boolean","args","apply"],"sources":["../../src/config/full.ts"],"sourcesContent":["import gensync, { type Handler } from \"gensync\";\nimport {\n forwardAsync,\n maybeAsync,\n isThenable,\n} from \"../gensync-utils/async.ts\";\n\nimport { mergeOptions } from \"./util.ts\";\nimport * as context from \"../index.ts\";\nimport Plugin from \"./plugin.ts\";\nimport { getItemDescriptor } from \"./item.ts\";\nimport { buildPresetChain } from \"./config-chain.ts\";\nimport { finalize as freezeDeepArray } from \"./helpers/deep-array.ts\";\nimport type { DeepArray, ReadonlyDeepArray } from \"./helpers/deep-array.ts\";\nimport type {\n ConfigContext,\n ConfigChain,\n PresetInstance,\n} from \"./config-chain.ts\";\nimport type { UnloadedDescriptor } from \"./config-descriptors.ts\";\nimport traverse from \"@babel/traverse\";\nimport { makeWeakCache, makeWeakCacheSync } from \"./caching.ts\";\nimport type { CacheConfigurator } from \"./caching.ts\";\nimport {\n validate,\n checkNoUnwrappedItemOptionPairs,\n} from \"./validation/options.ts\";\nimport type { PluginItem } from \"./validation/options.ts\";\nimport { validatePluginObject } from \"./validation/plugins.ts\";\nimport { makePluginAPI, makePresetAPI } from \"./helpers/config-api.ts\";\nimport type { PluginAPI, PresetAPI } from \"./helpers/config-api.ts\";\n\nimport loadPrivatePartialConfig from \"./partial.ts\";\nimport type { ValidatedOptions } from \"./validation/options.ts\";\n\nimport type * as Context from \"./cache-contexts.ts\";\nimport ConfigError from \"../errors/config-error.ts\";\n\ntype LoadedDescriptor = {\n value: any;\n options: object;\n dirname: string;\n alias: string;\n externalDependencies: ReadonlyDeepArray;\n};\n\nexport type { InputOptions } from \"./validation/options.ts\";\n\nexport type ResolvedConfig = {\n options: any;\n passes: PluginPasses;\n externalDependencies: ReadonlyDeepArray;\n};\n\nexport type { Plugin };\nexport type PluginPassList = Array;\nexport type PluginPasses = Array;\n\nexport default gensync(function* loadFullConfig(\n inputOpts: unknown,\n): Handler {\n const result = yield* loadPrivatePartialConfig(inputOpts);\n if (!result) {\n return null;\n }\n const { options, context, fileHandling } = result;\n\n if (fileHandling === \"ignored\") {\n return null;\n }\n\n const optionDefaults = {};\n\n const { plugins, presets } = options;\n\n if (!plugins || !presets) {\n throw new Error(\"Assertion failure - plugins and presets exist\");\n }\n\n const presetContext: Context.FullPreset = {\n ...context,\n targets: options.targets,\n };\n\n const toDescriptor = (item: PluginItem) => {\n const desc = getItemDescriptor(item);\n if (!desc) {\n throw new Error(\"Assertion failure - must be config item\");\n }\n\n return desc;\n };\n\n const presetsDescriptors = presets.map(toDescriptor);\n const initialPluginsDescriptors = plugins.map(toDescriptor);\n const pluginDescriptorsByPass: Array>> = [\n [],\n ];\n const passes: Array> = [];\n\n const externalDependencies: DeepArray = [];\n\n const ignored = yield* enhanceError(\n context,\n function* recursePresetDescriptors(\n rawPresets: Array>,\n pluginDescriptorsPass: Array>,\n ): Handler {\n const presets: Array<{\n preset: ConfigChain | null;\n pass: Array>;\n }> = [];\n\n for (let i = 0; i < rawPresets.length; i++) {\n const descriptor = rawPresets[i];\n if (descriptor.options !== false) {\n try {\n // eslint-disable-next-line no-var\n var preset = yield* loadPresetDescriptor(descriptor, presetContext);\n } catch (e) {\n if (e.code === \"BABEL_UNKNOWN_OPTION\") {\n checkNoUnwrappedItemOptionPairs(rawPresets, i, \"preset\", e);\n }\n throw e;\n }\n\n externalDependencies.push(preset.externalDependencies);\n\n // Presets normally run in reverse order, but if they\n // have their own pass they run after the presets\n // in the previous pass.\n if (descriptor.ownPass) {\n presets.push({ preset: preset.chain, pass: [] });\n } else {\n presets.unshift({\n preset: preset.chain,\n pass: pluginDescriptorsPass,\n });\n }\n }\n }\n\n // resolve presets\n if (presets.length > 0) {\n // The passes are created in the same order as the preset list, but are inserted before any\n // existing additional passes.\n pluginDescriptorsByPass.splice(\n 1,\n 0,\n ...presets.map(o => o.pass).filter(p => p !== pluginDescriptorsPass),\n );\n\n for (const { preset, pass } of presets) {\n if (!preset) return true;\n\n pass.push(...preset.plugins);\n\n const ignored = yield* recursePresetDescriptors(preset.presets, pass);\n if (ignored) return true;\n\n preset.options.forEach(opts => {\n mergeOptions(optionDefaults, opts);\n });\n }\n }\n },\n )(presetsDescriptors, pluginDescriptorsByPass[0]);\n\n if (ignored) return null;\n\n const opts: any = optionDefaults;\n mergeOptions(opts, options);\n\n const pluginContext: Context.FullPlugin = {\n ...presetContext,\n assumptions: opts.assumptions ?? {},\n };\n\n yield* enhanceError(context, function* loadPluginDescriptors() {\n pluginDescriptorsByPass[0].unshift(...initialPluginsDescriptors);\n\n for (const descs of pluginDescriptorsByPass) {\n const pass: Plugin[] = [];\n passes.push(pass);\n\n for (let i = 0; i < descs.length; i++) {\n const descriptor = descs[i];\n if (descriptor.options !== false) {\n try {\n // eslint-disable-next-line no-var\n var plugin = yield* loadPluginDescriptor(descriptor, pluginContext);\n } catch (e) {\n if (e.code === \"BABEL_UNKNOWN_PLUGIN_PROPERTY\") {\n // print special message for `plugins: [\"@babel/foo\", { foo: \"option\" }]`\n checkNoUnwrappedItemOptionPairs(descs, i, \"plugin\", e);\n }\n throw e;\n }\n pass.push(plugin);\n\n externalDependencies.push(plugin.externalDependencies);\n }\n }\n }\n })();\n\n opts.plugins = passes[0];\n opts.presets = passes\n .slice(1)\n .filter(plugins => plugins.length > 0)\n .map(plugins => ({ plugins }));\n opts.passPerPreset = opts.presets.length > 0;\n\n return {\n options: opts,\n passes: passes,\n externalDependencies: freezeDeepArray(externalDependencies),\n };\n});\n\nfunction enhanceError(context: ConfigContext, fn: T): T {\n return function* (arg1: unknown, arg2: unknown) {\n try {\n return yield* fn(arg1, arg2);\n } catch (e) {\n // There are a few case where thrown errors will try to annotate themselves multiple times, so\n // to keep things simple we just bail out if re-wrapping the message.\n if (!/^\\[BABEL\\]/.test(e.message)) {\n e.message = `[BABEL] ${context.filename ?? \"unknown file\"}: ${\n e.message\n }`;\n }\n\n throw e;\n }\n } as any;\n}\n\n/**\n * Load a generic plugin/preset from the given descriptor loaded from the config object.\n */\nconst makeDescriptorLoader = (\n apiFactory: (\n cache: CacheConfigurator,\n externalDependencies: Array,\n ) => API,\n) =>\n makeWeakCache(function* (\n { value, options, dirname, alias }: UnloadedDescriptor,\n cache: CacheConfigurator,\n ): Handler {\n // Disabled presets should already have been filtered out\n if (options === false) throw new Error(\"Assertion failure\");\n\n options = options || {};\n\n const externalDependencies: Array = [];\n\n let item: unknown = value;\n if (typeof value === \"function\") {\n const factory = maybeAsync(\n value as (api: API, options: object, dirname: string) => unknown,\n `You appear to be using an async plugin/preset, but Babel has been called synchronously`,\n );\n\n const api = {\n ...context,\n ...apiFactory(cache, externalDependencies),\n };\n try {\n item = yield* factory(api, options, dirname);\n } catch (e) {\n if (alias) {\n e.message += ` (While processing: ${JSON.stringify(alias)})`;\n }\n throw e;\n }\n }\n\n if (!item || typeof item !== \"object\") {\n throw new Error(\"Plugin/Preset did not return an object.\");\n }\n\n if (isThenable(item)) {\n // @ts-expect-error - if we want to support async plugins\n yield* [];\n\n throw new Error(\n `You appear to be using a promise as a plugin, ` +\n `which your current version of Babel does not support. ` +\n `If you're using a published plugin, ` +\n `you may need to upgrade your @babel/core version. ` +\n `As an alternative, you can prefix the promise with \"await\". ` +\n `(While processing: ${JSON.stringify(alias)})`,\n );\n }\n\n if (\n externalDependencies.length > 0 &&\n (!cache.configured() || cache.mode() === \"forever\")\n ) {\n let error =\n `A plugin/preset has external untracked dependencies ` +\n `(${externalDependencies[0]}), but the cache `;\n if (!cache.configured()) {\n error += `has not been configured to be invalidated when the external dependencies change. `;\n } else {\n error += ` has been configured to never be invalidated. `;\n }\n error +=\n `Plugins/presets should configure their cache to be invalidated when the external ` +\n `dependencies change, for example using \\`api.cache.invalidate(() => ` +\n `statSync(filepath).mtimeMs)\\` or \\`api.cache.never()\\`\\n` +\n `(While processing: ${JSON.stringify(alias)})`;\n\n throw new Error(error);\n }\n\n return {\n value: item,\n options,\n dirname,\n alias,\n externalDependencies: freezeDeepArray(externalDependencies),\n };\n });\n\nconst pluginDescriptorLoader = makeDescriptorLoader<\n Context.SimplePlugin,\n PluginAPI\n>(makePluginAPI);\nconst presetDescriptorLoader = makeDescriptorLoader<\n Context.SimplePreset,\n PresetAPI\n>(makePresetAPI);\n\nconst instantiatePlugin = makeWeakCache(function* (\n { value, options, dirname, alias, externalDependencies }: LoadedDescriptor,\n cache: CacheConfigurator,\n): Handler {\n const pluginObj = validatePluginObject(value);\n\n const plugin = {\n ...pluginObj,\n };\n if (plugin.visitor) {\n plugin.visitor = traverse.explode({\n ...plugin.visitor,\n });\n }\n\n if (plugin.inherits) {\n const inheritsDescriptor: UnloadedDescriptor = {\n name: undefined,\n alias: `${alias}$inherits`,\n value: plugin.inherits,\n options,\n dirname,\n };\n\n const inherits = yield* forwardAsync(loadPluginDescriptor, run => {\n // If the inherited plugin changes, reinstantiate this plugin.\n return cache.invalidate(data => run(inheritsDescriptor, data));\n });\n\n plugin.pre = chain(inherits.pre, plugin.pre);\n plugin.post = chain(inherits.post, plugin.post);\n plugin.manipulateOptions = chain(\n inherits.manipulateOptions,\n plugin.manipulateOptions,\n );\n plugin.visitor = traverse.visitors.merge([\n inherits.visitor || {},\n plugin.visitor || {},\n ]);\n\n if (inherits.externalDependencies.length > 0) {\n if (externalDependencies.length === 0) {\n externalDependencies = inherits.externalDependencies;\n } else {\n externalDependencies = freezeDeepArray([\n externalDependencies,\n inherits.externalDependencies,\n ]);\n }\n }\n }\n\n return new Plugin(plugin, options, alias, externalDependencies);\n});\n\n/**\n * Instantiate a plugin for the given descriptor, returning the plugin/options pair.\n */\nfunction* loadPluginDescriptor(\n descriptor: UnloadedDescriptor,\n context: Context.SimplePlugin,\n): Handler {\n if (descriptor.value instanceof Plugin) {\n if (descriptor.options) {\n throw new Error(\n \"Passed options to an existing Plugin instance will not work.\",\n );\n }\n\n return descriptor.value;\n }\n\n return yield* instantiatePlugin(\n yield* pluginDescriptorLoader(descriptor, context),\n context,\n );\n}\n\nconst needsFilename = (val: unknown) => val && typeof val !== \"function\";\n\nconst validateIfOptionNeedsFilename = (\n options: ValidatedOptions,\n descriptor: UnloadedDescriptor,\n): void => {\n if (\n needsFilename(options.test) ||\n needsFilename(options.include) ||\n needsFilename(options.exclude)\n ) {\n const formattedPresetName = descriptor.name\n ? `\"${descriptor.name}\"`\n : \"/* your preset */\";\n throw new ConfigError(\n [\n `Preset ${formattedPresetName} requires a filename to be set when babel is called directly,`,\n `\\`\\`\\``,\n `babel.transformSync(code, { filename: 'file.ts', presets: [${formattedPresetName}] });`,\n `\\`\\`\\``,\n `See https://babeljs.io/docs/en/options#filename for more information.`,\n ].join(\"\\n\"),\n );\n }\n};\n\nconst validatePreset = (\n preset: PresetInstance,\n context: ConfigContext,\n descriptor: UnloadedDescriptor,\n): void => {\n if (!context.filename) {\n const { options } = preset;\n validateIfOptionNeedsFilename(options, descriptor);\n options.overrides?.forEach(overrideOptions =>\n validateIfOptionNeedsFilename(overrideOptions, descriptor),\n );\n }\n};\n\nconst instantiatePreset = makeWeakCacheSync(\n ({\n value,\n dirname,\n alias,\n externalDependencies,\n }: LoadedDescriptor): PresetInstance => {\n return {\n options: validate(\"preset\", value),\n alias,\n dirname,\n externalDependencies,\n };\n },\n);\n\n/**\n * Generate a config object that will act as the root of a new nested config.\n */\nfunction* loadPresetDescriptor(\n descriptor: UnloadedDescriptor,\n context: Context.FullPreset,\n): Handler<{\n chain: ConfigChain | null;\n externalDependencies: ReadonlyDeepArray;\n}> {\n const preset = instantiatePreset(\n yield* presetDescriptorLoader(descriptor, context),\n );\n validatePreset(preset, context, descriptor);\n return {\n chain: yield* buildPresetChain(preset, context),\n externalDependencies: preset.externalDependencies,\n };\n}\n\nfunction chain(\n a: undefined | ((...args: Args) => void),\n b: undefined | ((...args: Args) => void),\n) {\n const fns = [a, b].filter(Boolean);\n if (fns.length <= 1) return fns[0];\n\n return function (this: unknown, ...args: unknown[]) {\n for (const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;AACgB,CAAC,KAAqB;EACtC,OAAO;IACLnB,OAAO,EAAE,IAAAkH,iBAAQ,EAAC,QAAQ,EAAElD,KAAK,CAAC;IAClCE,KAAK;IACLD,OAAO;IACP9C;EACF,CAAC;AACH,CACF,CAAC;AAKD,UAAUU,oBAAoBA,CAC5BF,UAAyC,EACzChD,OAA2B,EAI1B;EACD,MAAMiD,MAAM,GAAGoF,iBAAiB,CAC9B,OAAOjC,sBAAsB,CAACpD,UAAU,EAAEhD,OAAO,CACnD,CAAC;EACDiI,cAAc,CAAChF,MAAM,EAAEjD,OAAO,EAAEgD,UAAU,CAAC;EAC3C,OAAO;IACLQ,KAAK,EAAE,OAAO,IAAAgF,6BAAgB,EAACvF,MAAM,EAAEjD,OAAO,CAAC;IAC/CwC,oBAAoB,EAAES,MAAM,CAACT;EAC/B,CAAC;AACH;AAEA,SAASgB,KAAKA,CACZiF,CAAwC,EACxCC,CAAwC,EACxC;EACA,MAAMC,GAAG,GAAG,CAACF,CAAC,EAAEC,CAAC,CAAC,CAAC7E,MAAM,CAAC+E,OAAO,CAAC;EAClC,IAAID,GAAG,CAAC5F,MAAM,IAAI,CAAC,EAAE,OAAO4F,GAAG,CAAC,CAAC,CAAC;EAElC,OAAO,UAAyB,GAAGE,IAAe,EAAE;IAClD,KAAK,MAAMlE,EAAE,IAAIgE,GAAG,EAAE;MACpBhE,EAAE,CAACmE,KAAK,CAAC,IAAI,EAAED,IAAI,CAAC;IACtB;EACF,CAAC;AACH;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/helpers/config-api.js b/node_modules/@babel/core/lib/config/helpers/config-api.js new file mode 100644 index 0000000..3a80653 --- /dev/null +++ b/node_modules/@babel/core/lib/config/helpers/config-api.js @@ -0,0 +1,84 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.makeConfigAPI = makeConfigAPI; +exports.makePluginAPI = makePluginAPI; +exports.makePresetAPI = makePresetAPI; +function _semver() { + const data = require("semver"); + _semver = function () { + return data; + }; + return data; +} +var _index = require("../../index.js"); +var _caching = require("../caching.js"); +function makeConfigAPI(cache) { + const env = value => cache.using(data => { + if (typeof value === "undefined") return data.envName; + if (typeof value === "function") { + return (0, _caching.assertSimpleType)(value(data.envName)); + } + return (Array.isArray(value) ? value : [value]).some(entry => { + if (typeof entry !== "string") { + throw new Error("Unexpected non-string value"); + } + return entry === data.envName; + }); + }); + const caller = cb => cache.using(data => (0, _caching.assertSimpleType)(cb(data.caller))); + return { + version: _index.version, + cache: cache.simple(), + env, + async: () => false, + caller, + assertVersion + }; +} +function makePresetAPI(cache, externalDependencies) { + const targets = () => JSON.parse(cache.using(data => JSON.stringify(data.targets))); + const addExternalDependency = ref => { + externalDependencies.push(ref); + }; + return Object.assign({}, makeConfigAPI(cache), { + targets, + addExternalDependency + }); +} +function makePluginAPI(cache, externalDependencies) { + const assumption = name => cache.using(data => data.assumptions[name]); + return Object.assign({}, makePresetAPI(cache, externalDependencies), { + assumption + }); +} +function assertVersion(range) { + if (typeof range === "number") { + if (!Number.isInteger(range)) { + throw new Error("Expected string or integer value."); + } + range = `^${range}.0.0-0`; + } + if (typeof range !== "string") { + throw new Error("Expected string or integer value."); + } + if (range === "*" || _semver().satisfies(_index.version, range)) return; + const limit = Error.stackTraceLimit; + if (typeof limit === "number" && limit < 25) { + Error.stackTraceLimit = 25; + } + const err = new Error(`Requires Babel "${range}", but was loaded with "${_index.version}". ` + `If you are sure you have a compatible version of @babel/core, ` + `it is likely that something in your build process is loading the ` + `wrong version. Inspect the stack trace of this error to look for ` + `the first entry that doesn't mention "@babel/core" or "babel-core" ` + `to see what is calling Babel.`); + if (typeof limit === "number") { + Error.stackTraceLimit = limit; + } + throw Object.assign(err, { + code: "BABEL_VERSION_UNSUPPORTED", + version: _index.version, + range + }); +} +0 && 0; + +//# sourceMappingURL=config-api.js.map diff --git a/node_modules/@babel/core/lib/config/helpers/config-api.js.map b/node_modules/@babel/core/lib/config/helpers/config-api.js.map new file mode 100644 index 0000000..5677896 --- /dev/null +++ b/node_modules/@babel/core/lib/config/helpers/config-api.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_semver","data","require","_index","_caching","makeConfigAPI","cache","env","value","using","envName","assertSimpleType","Array","isArray","some","entry","Error","caller","cb","version","coreVersion","simple","async","assertVersion","makePresetAPI","externalDependencies","targets","JSON","parse","stringify","addExternalDependency","ref","push","Object","assign","makePluginAPI","assumption","name","assumptions","range","Number","isInteger","semver","satisfies","limit","stackTraceLimit","err","code"],"sources":["../../../src/config/helpers/config-api.ts"],"sourcesContent":["import semver from \"semver\";\nimport type { Targets } from \"@babel/helper-compilation-targets\";\n\nimport { version as coreVersion } from \"../../index.ts\";\nimport { assertSimpleType } from \"../caching.ts\";\nimport type {\n CacheConfigurator,\n SimpleCacheConfigurator,\n SimpleType,\n} from \"../caching.ts\";\n\nimport type { AssumptionName, CallerMetadata } from \"../validation/options.ts\";\n\nimport type * as Context from \"../cache-contexts\";\n\ntype EnvFunction = {\n (): string;\n (extractor: (babelEnv: string) => T): T;\n (envVar: string): boolean;\n (envVars: Array): boolean;\n};\n\ntype CallerFactory = {\n (\n extractor: (callerMetadata: CallerMetadata | undefined) => T,\n ): T;\n (\n extractor: (callerMetadata: CallerMetadata | undefined) => unknown,\n ): SimpleType;\n};\ntype TargetsFunction = () => Targets;\ntype AssumptionFunction = (name: AssumptionName) => boolean | undefined;\n\nexport type ConfigAPI = {\n version: string;\n cache: SimpleCacheConfigurator;\n env: EnvFunction;\n async: () => boolean;\n assertVersion: typeof assertVersion;\n caller?: CallerFactory;\n};\n\nexport type PresetAPI = {\n targets: TargetsFunction;\n addExternalDependency: (ref: string) => void;\n} & ConfigAPI;\n\nexport type PluginAPI = {\n assumption: AssumptionFunction;\n} & PresetAPI;\n\nexport function makeConfigAPI(\n cache: CacheConfigurator,\n): ConfigAPI {\n // TODO(@nicolo-ribaudo): If we remove the explicit type from `value`\n // and the `as any` type cast, TypeScript crashes in an infinite\n // recursion. After upgrading to TS4.7 and finishing the noImplicitAny\n // PR, we should check if it still crashes and report it to the TS team.\n const env: EnvFunction = ((\n value: string | string[] | ((babelEnv: string) => T),\n ) =>\n cache.using(data => {\n if (typeof value === \"undefined\") return data.envName;\n if (typeof value === \"function\") {\n return assertSimpleType(value(data.envName));\n }\n return (Array.isArray(value) ? value : [value]).some(entry => {\n if (typeof entry !== \"string\") {\n throw new Error(\"Unexpected non-string value\");\n }\n return entry === data.envName;\n });\n })) as any;\n\n const caller = (\n cb: (CallerMetadata: CallerMetadata | undefined) => SimpleType,\n ) => cache.using(data => assertSimpleType(cb(data.caller)));\n\n return {\n version: coreVersion,\n cache: cache.simple(),\n // Expose \".env()\" so people can easily get the same env that we expose using the \"env\" key.\n env,\n async: () => false,\n caller,\n assertVersion,\n };\n}\n\nexport function makePresetAPI(\n cache: CacheConfigurator,\n externalDependencies: Array,\n): PresetAPI {\n const targets = () =>\n // We are using JSON.parse/JSON.stringify because it's only possible to cache\n // primitive values. We can safely stringify the targets object because it\n // only contains strings as its properties.\n // Please make the Record and Tuple proposal happen!\n JSON.parse(cache.using(data => JSON.stringify(data.targets)));\n\n const addExternalDependency = (ref: string) => {\n externalDependencies.push(ref);\n };\n\n return { ...makeConfigAPI(cache), targets, addExternalDependency };\n}\n\nexport function makePluginAPI(\n cache: CacheConfigurator,\n externalDependencies: Array,\n): PluginAPI {\n const assumption = (name: string) =>\n cache.using(data => data.assumptions[name]);\n\n return { ...makePresetAPI(cache, externalDependencies), assumption };\n}\n\nfunction assertVersion(range: string | number): void {\n if (typeof range === \"number\") {\n if (!Number.isInteger(range)) {\n throw new Error(\"Expected string or integer value.\");\n }\n range = `^${range}.0.0-0`;\n }\n if (typeof range !== \"string\") {\n throw new Error(\"Expected string or integer value.\");\n }\n\n // We want \"*\" to also allow any pre-release, but we do not pass\n // the includePrerelease option to semver.satisfies because we\n // do not want ^7.0.0 to match 8.0.0-alpha.1.\n if (range === \"*\" || semver.satisfies(coreVersion, range)) return;\n\n const limit = Error.stackTraceLimit;\n\n if (typeof limit === \"number\" && limit < 25) {\n // Bump up the limit if needed so that users are more likely\n // to be able to see what is calling Babel.\n Error.stackTraceLimit = 25;\n }\n\n const err = new Error(\n `Requires Babel \"${range}\", but was loaded with \"${coreVersion}\". ` +\n `If you are sure you have a compatible version of @babel/core, ` +\n `it is likely that something in your build process is loading the ` +\n `wrong version. Inspect the stack trace of this error to look for ` +\n `the first entry that doesn't mention \"@babel/core\" or \"babel-core\" ` +\n `to see what is calling Babel.`,\n );\n\n if (typeof limit === \"number\") {\n Error.stackTraceLimit = limit;\n }\n\n throw Object.assign(err, {\n code: \"BABEL_VERSION_UNSUPPORTED\",\n version: coreVersion,\n range,\n });\n}\n"],"mappings":";;;;;;;;AAAA,SAAAA,QAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,OAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAGA,IAAAE,MAAA,GAAAD,OAAA;AACA,IAAAE,QAAA,GAAAF,OAAA;AA+CO,SAASG,aAAaA,CAC3BC,KAAqC,EAC1B;EAKX,MAAMC,GAAgB,GACpBC,KAAuD,IAEvDF,KAAK,CAACG,KAAK,CAACR,IAAI,IAAI;IAClB,IAAI,OAAOO,KAAK,KAAK,WAAW,EAAE,OAAOP,IAAI,CAACS,OAAO;IACrD,IAAI,OAAOF,KAAK,KAAK,UAAU,EAAE;MAC/B,OAAO,IAAAG,yBAAgB,EAACH,KAAK,CAACP,IAAI,CAACS,OAAO,CAAC,CAAC;IAC9C;IACA,OAAO,CAACE,KAAK,CAACC,OAAO,CAACL,KAAK,CAAC,GAAGA,KAAK,GAAG,CAACA,KAAK,CAAC,EAAEM,IAAI,CAACC,KAAK,IAAI;MAC5D,IAAI,OAAOA,KAAK,KAAK,QAAQ,EAAE;QAC7B,MAAM,IAAIC,KAAK,CAAC,6BAA6B,CAAC;MAChD;MACA,OAAOD,KAAK,KAAKd,IAAI,CAACS,OAA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M,IAAIvB,KAAK,CAAC,mCAAmC,CAAC;IACtD;IACAuB,KAAK,GAAG,IAAIA,KAAK,QAAQ;EAC3B;EACA,IAAI,OAAOA,KAAK,KAAK,QAAQ,EAAE;IAC7B,MAAM,IAAIvB,KAAK,CAAC,mCAAmC,CAAC;EACtD;EAKA,IAAIuB,KAAK,KAAK,GAAG,IAAIG,QAAKA,CAAC,CAACC,SAAS,CAACvB,cAAW,EAAEmB,KAAK,CAAC,EAAE;EAE3D,MAAMK,KAAK,GAAG5B,KAAK,CAAC6B,eAAe;EAEnC,IAAI,OAAOD,KAAK,KAAK,QAAQ,IAAIA,KAAK,GAAG,EAAE,EAAE;IAG3C5B,KAAK,CAAC6B,eAAe,GAAG,EAAE;EAC5B;EAEA,MAAMC,GAAG,GAAG,IAAI9B,KAAK,CACnB,mBAAmBuB,KAAK,2BAA2BnB,cAAW,KAAK,GACjE,gEAAgE,GAChE,mEAAmE,GACnE,mEAAmE,GACnE,qEAAqE,GACrE,+BACJ,CAAC;EAED,IAAI,OAAOwB,KAAK,KAAK,QAAQ,EAAE;IAC7B5B,KAAK,CAAC6B,eAAe,GAAGD,KAAK;EAC/B;EAEA,MAAMX,MAAM,CAACC,MAAM,CAACY,GAAG,EAAE;IACvBC,IAAI,EAAE,2BAA2B;IACjC5B,OAAO,EAAEC,cAAW;IACpBmB;EACF,CAAC,CAAC;AACJ;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/helpers/deep-array.js b/node_modules/@babel/core/lib/config/helpers/deep-array.js new file mode 100644 index 0000000..c611db2 --- /dev/null +++ b/node_modules/@babel/core/lib/config/helpers/deep-array.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.finalize = finalize; +exports.flattenToSet = flattenToSet; +function finalize(deepArr) { + return Object.freeze(deepArr); +} +function flattenToSet(arr) { + const result = new Set(); + const stack = [arr]; + while (stack.length > 0) { + for (const el of stack.pop()) { + if (Array.isArray(el)) stack.push(el);else result.add(el); + } + } + return result; +} +0 && 0; + +//# sourceMappingURL=deep-array.js.map diff --git a/node_modules/@babel/core/lib/config/helpers/deep-array.js.map b/node_modules/@babel/core/lib/config/helpers/deep-array.js.map new file mode 100644 index 0000000..d8c7819 --- /dev/null +++ b/node_modules/@babel/core/lib/config/helpers/deep-array.js.map @@ -0,0 +1 @@ +{"version":3,"names":["finalize","deepArr","Object","freeze","flattenToSet","arr","result","Set","stack","length","el","pop","Array","isArray","push","add"],"sources":["../../../src/config/helpers/deep-array.ts"],"sourcesContent":["export type DeepArray = Array>;\n\n// Just to make sure that DeepArray is not assignable to ReadonlyDeepArray\ndeclare const __marker: unique symbol;\nexport type ReadonlyDeepArray = ReadonlyArray> & {\n [__marker]: true;\n};\n\nexport function finalize(deepArr: DeepArray): ReadonlyDeepArray {\n return Object.freeze(deepArr) as ReadonlyDeepArray;\n}\n\nexport function flattenToSet(\n arr: ReadonlyDeepArray,\n): Set {\n const result = new Set();\n const stack = [arr];\n while (stack.length > 0) {\n for (const el of stack.pop()) {\n if (Array.isArray(el)) stack.push(el as ReadonlyDeepArray);\n else result.add(el as T);\n }\n }\n return result;\n}\n"],"mappings":";;;;;;;AAQO,SAASA,QAAQA,CAAIC,OAAqB,EAAwB;EACvE,OAAOC,MAAM,CAACC,MAAM,CAACF,OAAO,CAAC;AAC/B;AAEO,SAASG,YAAYA,CAC1BC,GAAyB,EACjB;EACR,MAAMC,MAAM,GAAG,IAAIC,GAAG,CAAI,CAAC;EAC3B,MAAMC,KAAK,GAAG,CAACH,GAAG,CAAC;EACnB,OAAOG,KAAK,CAACC,MAAM,GAAG,CAAC,EAAE;IACvB,KAAK,MAAMC,EAAE,IAAIF,KAAK,CAACG,GAAG,CAAC,CAAC,EAAE;MAC5B,IAAIC,KAAK,CAACC,OAAO,CAACH,EAAE,CAAC,EAAEF,KAAK,CAACM,IAAI,CAACJ,EAA0B,CAAC,CAAC,KACzDJ,MAAM,CAACS,GAAG,CAACL,EAAO,CAAC;IAC1B;EACF;EACA,OAAOJ,MAAM;AACf;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/helpers/environment.js b/node_modules/@babel/core/lib/config/helpers/environment.js new file mode 100644 index 0000000..a23b80b --- /dev/null +++ b/node_modules/@babel/core/lib/config/helpers/environment.js @@ -0,0 +1,12 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getEnv = getEnv; +function getEnv(defaultValue = "development") { + return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue; +} +0 && 0; + +//# sourceMappingURL=environment.js.map diff --git a/node_modules/@babel/core/lib/config/helpers/environment.js.map b/node_modules/@babel/core/lib/config/helpers/environment.js.map new file mode 100644 index 0000000..c34fc17 --- /dev/null +++ b/node_modules/@babel/core/lib/config/helpers/environment.js.map @@ -0,0 +1 @@ +{"version":3,"names":["getEnv","defaultValue","process","env","BABEL_ENV","NODE_ENV"],"sources":["../../../src/config/helpers/environment.ts"],"sourcesContent":["export function getEnv(defaultValue: string = \"development\"): string {\n return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue;\n}\n"],"mappings":";;;;;;AAAO,SAASA,MAAMA,CAACC,YAAoB,GAAG,aAAa,EAAU;EACnE,OAAOC,OAAO,CAACC,GAAG,CAACC,SAAS,IAAIF,OAAO,CAACC,GAAG,CAACE,QAAQ,IAAIJ,YAAY;AACtE;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/index.js b/node_modules/@babel/core/lib/config/index.js new file mode 100644 index 0000000..b2262b2 --- /dev/null +++ b/node_modules/@babel/core/lib/config/index.js @@ -0,0 +1,93 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createConfigItem = createConfigItem; +exports.createConfigItemAsync = createConfigItemAsync; +exports.createConfigItemSync = createConfigItemSync; +Object.defineProperty(exports, "default", { + enumerable: true, + get: function () { + return _full.default; + } +}); +exports.loadOptions = loadOptions; +exports.loadOptionsAsync = loadOptionsAsync; +exports.loadOptionsSync = loadOptionsSync; +exports.loadPartialConfig = loadPartialConfig; +exports.loadPartialConfigAsync = loadPartialConfigAsync; +exports.loadPartialConfigSync = loadPartialConfigSync; +function _gensync() { + const data = require("gensync"); + _gensync = function () { + return data; + }; + return data; +} +var _full = require("./full.js"); +var _partial = require("./partial.js"); +var _item = require("./item.js"); +var _rewriteStackTrace = require("../errors/rewrite-stack-trace.js"); +const loadPartialConfigRunner = _gensync()(_partial.loadPartialConfig); +function loadPartialConfigAsync(...args) { + return (0, _rewriteStackTrace.beginHiddenCallStack)(loadPartialConfigRunner.async)(...args); +} +function loadPartialConfigSync(...args) { + return (0, _rewriteStackTrace.beginHiddenCallStack)(loadPartialConfigRunner.sync)(...args); +} +function loadPartialConfig(opts, callback) { + if (callback !== undefined) { + (0, _rewriteStackTrace.beginHiddenCallStack)(loadPartialConfigRunner.errback)(opts, callback); + } else if (typeof opts === "function") { + (0, _rewriteStackTrace.beginHiddenCallStack)(loadPartialConfigRunner.errback)(undefined, opts); + } else { + { + return loadPartialConfigSync(opts); + } + } +} +function* loadOptionsImpl(opts) { + var _config$options; + const config = yield* (0, _full.default)(opts); + return (_config$options = config == null ? void 0 : config.options) != null ? _config$options : null; +} +const loadOptionsRunner = _gensync()(loadOptionsImpl); +function loadOptionsAsync(...args) { + return (0, _rewriteStackTrace.beginHiddenCallStack)(loadOptionsRunner.async)(...args); +} +function loadOptionsSync(...args) { + return (0, _rewriteStackTrace.beginHiddenCallStack)(loadOptionsRunner.sync)(...args); +} +function loadOptions(opts, callback) { + if (callback !== undefined) { + (0, _rewriteStackTrace.beginHiddenCallStack)(loadOptionsRunner.errback)(opts, callback); + } else if (typeof opts === "function") { + (0, _rewriteStackTrace.beginHiddenCallStack)(loadOptionsRunner.errback)(undefined, opts); + } else { + { + return loadOptionsSync(opts); + } + } +} +const createConfigItemRunner = _gensync()(_item.createConfigItem); +function createConfigItemAsync(...args) { + return (0, _rewriteStackTrace.beginHiddenCallStack)(createConfigItemRunner.async)(...args); +} +function createConfigItemSync(...args) { + return (0, _rewriteStackTrace.beginHiddenCallStack)(createConfigItemRunner.sync)(...args); +} +function createConfigItem(target, options, callback) { + if (callback !== undefined) { + (0, _rewriteStackTrace.beginHiddenCallStack)(createConfigItemRunner.errback)(target, options, callback); + } else if (typeof options === "function") { + (0, _rewriteStackTrace.beginHiddenCallStack)(createConfigItemRunner.errback)(target, undefined, callback); + } else { + { + return createConfigItemSync(target, options); + } + } +} +0 && 0; + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/core/lib/config/index.js.map b/node_modules/@babel/core/lib/config/index.js.map new file mode 100644 index 0000000..2abf03c --- /dev/null +++ b/node_modules/@babel/core/lib/config/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_gensync","data","require","_full","_partial","_item","_rewriteStackTrace","loadPartialConfigRunner","gensync","loadPartialConfigImpl","loadPartialConfigAsync","args","beginHiddenCallStack","async","loadPartialConfigSync","sync","loadPartialConfig","opts","callback","undefined","errback","loadOptionsImpl","_config$options","config","loadFullConfig","options","loadOptionsRunner","loadOptionsAsync","loadOptionsSync","loadOptions","createConfigItemRunner","createConfigItemImpl","createConfigItemAsync","createConfigItemSync","createConfigItem","target"],"sources":["../../src/config/index.ts"],"sourcesContent":["import gensync, { type Handler } from \"gensync\";\n\nexport type {\n ResolvedConfig,\n InputOptions,\n PluginPasses,\n Plugin,\n} from \"./full.ts\";\n\nimport type { PluginTarget } from \"./validation/options.ts\";\n\nimport type {\n PluginAPI as basePluginAPI,\n PresetAPI as basePresetAPI,\n} from \"./helpers/config-api.ts\";\nexport type { PluginObject } from \"./validation/plugins.ts\";\ntype PluginAPI = basePluginAPI & typeof import(\"..\");\ntype PresetAPI = basePresetAPI & typeof import(\"..\");\nexport type { PluginAPI, PresetAPI };\n// todo: may need to refine PresetObject to be a subset of ValidatedOptions\nexport type {\n CallerMetadata,\n ValidatedOptions as PresetObject,\n} from \"./validation/options.ts\";\n\nimport loadFullConfig, { type ResolvedConfig } from \"./full.ts\";\nimport {\n type PartialConfig,\n loadPartialConfig as loadPartialConfigImpl,\n} from \"./partial.ts\";\n\nexport { loadFullConfig as default };\nexport type { PartialConfig } from \"./partial.ts\";\n\nimport { createConfigItem as createConfigItemImpl } from \"./item.ts\";\nimport type { ConfigItem } from \"./item.ts\";\nexport type { ConfigItem };\n\nimport { beginHiddenCallStack } from \"../errors/rewrite-stack-trace.ts\";\n\nconst loadPartialConfigRunner = gensync(loadPartialConfigImpl);\nexport function loadPartialConfigAsync(\n ...args: Parameters\n) {\n return beginHiddenCallStack(loadPartialConfigRunner.async)(...args);\n}\nexport function loadPartialConfigSync(\n ...args: Parameters\n) {\n return beginHiddenCallStack(loadPartialConfigRunner.sync)(...args);\n}\nexport function loadPartialConfig(\n opts: Parameters[0],\n callback?: (err: Error, val: PartialConfig | null) => void,\n) {\n if (callback !== undefined) {\n beginHiddenCallStack(loadPartialConfigRunner.errback)(opts, callback);\n } else if (typeof opts === \"function\") {\n beginHiddenCallStack(loadPartialConfigRunner.errback)(\n undefined,\n opts as (err: Error, val: PartialConfig | null) => void,\n );\n } else {\n if (process.env.BABEL_8_BREAKING) {\n throw new Error(\n \"Starting from Babel 8.0.0, the 'loadPartialConfig' function expects a callback. If you need to call it synchronously, please use 'loadPartialConfigSync'.\",\n );\n } else {\n return loadPartialConfigSync(opts);\n }\n }\n}\n\nfunction* loadOptionsImpl(opts: unknown): Handler {\n const config = yield* loadFullConfig(opts);\n // NOTE: We want to return \"null\" explicitly, while ?. alone returns undefined\n return config?.options ?? null;\n}\nconst loadOptionsRunner = gensync(loadOptionsImpl);\nexport function loadOptionsAsync(\n ...args: Parameters\n) {\n return beginHiddenCallStack(loadOptionsRunner.async)(...args);\n}\nexport function loadOptionsSync(\n ...args: Parameters\n) {\n return beginHiddenCallStack(loadOptionsRunner.sync)(...args);\n}\nexport function loadOptions(\n opts: Parameters[0],\n callback?: (err: Error, val: ResolvedConfig | null) => void,\n) {\n if (callback !== undefined) {\n beginHiddenCallStack(loadOptionsRunner.errback)(opts, callback);\n } else if (typeof opts === \"function\") {\n beginHiddenCallStack(loadOptionsRunner.errback)(\n undefined,\n opts as (err: Error, val: ResolvedConfig | null) => void,\n );\n } else {\n if (process.env.BABEL_8_BREAKING) {\n throw new Error(\n \"Starting from Babel 8.0.0, the 'loadOptions' function expects a callback. If you need to call it synchronously, please use 'loadOptionsSync'.\",\n );\n } else {\n return loadOptionsSync(opts);\n }\n }\n}\n\nconst createConfigItemRunner = gensync(createConfigItemImpl);\nexport function createConfigItemAsync(\n ...args: Parameters\n) {\n return beginHiddenCallStack(createConfigItemRunner.async)(...args);\n}\nexport function createConfigItemSync(\n ...args: Parameters\n) {\n return beginHiddenCallStack(createConfigItemRunner.sync)(...args);\n}\nexport function createConfigItem(\n target: PluginTarget,\n options: Parameters[1],\n callback?: (err: Error, val: ConfigItem | null) => void,\n) {\n if (callback !== undefined) {\n beginHiddenCallStack(createConfigItemRunner.errback)(\n target,\n options,\n callback,\n );\n } else if (typeof options === \"function\") {\n beginHiddenCallStack(createConfigItemRunner.errback)(\n target,\n undefined,\n callback,\n );\n } else {\n if (process.env.BABEL_8_BREAKING) {\n throw new Error(\n \"Starting from Babel 8.0.0, the 'createConfigItem' function expects a callback. If you need to call it synchronously, please use 'createConfigItemSync'.\",\n );\n } else {\n return createConfigItemSync(target, options);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAAA,SAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,QAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAyBA,IAAAE,KAAA,GAAAD,OAAA;AACA,IAAAE,QAAA,GAAAF,OAAA;AAQA,IAAAG,KAAA,GAAAH,OAAA;AAIA,IAAAI,kBAAA,GAAAJ,OAAA;AAEA,MAAMK,uBAAuB,GAAGC,SAAMA,CAAC,CAACC,0BAAqB,CAAC;AACvD,SA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a/node_modules/@babel/core/lib/config/item.js b/node_modules/@babel/core/lib/config/item.js new file mode 100644 index 0000000..69cf01f --- /dev/null +++ b/node_modules/@babel/core/lib/config/item.js @@ -0,0 +1,67 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createConfigItem = createConfigItem; +exports.createItemFromDescriptor = createItemFromDescriptor; +exports.getItemDescriptor = getItemDescriptor; +function _path() { + const data = require("path"); + _path = function () { + return data; + }; + return data; +} +var _configDescriptors = require("./config-descriptors.js"); +function createItemFromDescriptor(desc) { + return new ConfigItem(desc); +} +function* createConfigItem(value, { + dirname = ".", + type +} = {}) { + const descriptor = yield* (0, _configDescriptors.createDescriptor)(value, _path().resolve(dirname), { + type, + alias: "programmatic item" + }); + return createItemFromDescriptor(descriptor); +} +const CONFIG_ITEM_BRAND = Symbol.for("@babel/core@7 - ConfigItem"); +function getItemDescriptor(item) { + if (item != null && item[CONFIG_ITEM_BRAND]) { + return item._descriptor; + } + return undefined; +} +class ConfigItem { + constructor(descriptor) { + this._descriptor = void 0; + this[CONFIG_ITEM_BRAND] = true; + this.value = void 0; + this.options = void 0; + this.dirname = void 0; + this.name = void 0; + this.file = void 0; + this._descriptor = descriptor; + Object.defineProperty(this, "_descriptor", { + enumerable: false + }); + Object.defineProperty(this, CONFIG_ITEM_BRAND, { + enumerable: false + }); + this.value = this._descriptor.value; + this.options = this._descriptor.options; + this.dirname = this._descriptor.dirname; + this.name = this._descriptor.name; + this.file = this._descriptor.file ? { + request: this._descriptor.file.request, + resolved: this._descriptor.file.resolved + } : undefined; + Object.freeze(this); + } +} +Object.freeze(ConfigItem.prototype); +0 && 0; + +//# sourceMappingURL=item.js.map diff --git a/node_modules/@babel/core/lib/config/item.js.map b/node_modules/@babel/core/lib/config/item.js.map new file mode 100644 index 0000000..ca12785 --- /dev/null +++ b/node_modules/@babel/core/lib/config/item.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_path","data","require","_configDescriptors","createItemFromDescriptor","desc","ConfigItem","createConfigItem","value","dirname","type","descriptor","createDescriptor","path","resolve","alias","CONFIG_ITEM_BRAND","Symbol","for","getItemDescriptor","item","_descriptor","undefined","constructor","options","name","file","Object","defineProperty","enumerable","request","resolved","freeze","prototype"],"sources":["../../src/config/item.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\nimport type { PluginTarget, PluginOptions } from \"./validation/options.ts\";\n\nimport path from \"path\";\nimport { createDescriptor } from \"./config-descriptors.ts\";\n\nimport type { UnloadedDescriptor } from \"./config-descriptors.ts\";\n\nexport function createItemFromDescriptor(\n desc: UnloadedDescriptor,\n): ConfigItem {\n return new ConfigItem(desc);\n}\n\n/**\n * Create a config item using the same value format used in Babel's config\n * files. Items returned from this function should be cached by the caller\n * ideally, as recreating the config item will mean re-resolving the item\n * and re-evaluating the plugin/preset function.\n */\nexport function* createConfigItem(\n value:\n | PluginTarget\n | [PluginTarget, PluginOptions]\n | [PluginTarget, PluginOptions, string | void],\n {\n dirname = \".\",\n type,\n }: {\n dirname?: string;\n type?: \"preset\" | \"plugin\";\n } = {},\n): Handler> {\n const descriptor = yield* createDescriptor(value, path.resolve(dirname), {\n type,\n alias: \"programmatic item\",\n });\n\n return createItemFromDescriptor(descriptor);\n}\n\nconst CONFIG_ITEM_BRAND = Symbol.for(\"@babel/core@7 - ConfigItem\");\n\nexport function getItemDescriptor(\n item: unknown,\n): UnloadedDescriptor | void {\n if ((item as any)?.[CONFIG_ITEM_BRAND]) {\n return (item as ConfigItem)._descriptor;\n }\n\n return undefined;\n}\n\nexport type { ConfigItem };\n\n/**\n * A public representation of a plugin/preset that will _eventually_ be load.\n * Users can use this to interact with the results of a loaded Babel\n * configuration.\n *\n * Any changes to public properties of this class should be considered a\n * breaking change to Babel's API.\n */\nclass ConfigItem {\n /**\n * The private underlying descriptor that Babel actually cares about.\n * If you access this, you are a bad person.\n */\n _descriptor: UnloadedDescriptor;\n\n // TODO(Babel 9): Check if this symbol needs to be updated\n /**\n * Used to detect ConfigItem instances from other Babel instances.\n */\n [CONFIG_ITEM_BRAND] = true;\n\n /**\n * The resolved value of the item itself.\n */\n value: object | Function;\n\n /**\n * The options, if any, that were passed to the item.\n * Mutating this will lead to undefined behavior.\n *\n * \"false\" means that this item has been disabled.\n */\n options: object | void | false;\n\n /**\n * The directory that the options for this item are relative to.\n */\n dirname: string;\n\n /**\n * Get the name of the plugin, if the user gave it one.\n */\n name: string | void;\n\n /**\n * Data about the file that the item was loaded from, if Babel knows it.\n */\n file: {\n // The requested path, e.g. \"@babel/env\".\n request: string;\n // The resolved absolute path of the file.\n resolved: string;\n } | void;\n\n constructor(descriptor: UnloadedDescriptor) {\n // Make people less likely to stumble onto this if they are exploring\n // programmatically, and also make sure that if people happen to\n // pass the item through JSON.stringify, it doesn't show up.\n this._descriptor = descriptor;\n Object.defineProperty(this, \"_descriptor\", { enumerable: false });\n\n Object.defineProperty(this, CONFIG_ITEM_BRAND, { enumerable: false });\n\n this.value = this._descriptor.value;\n this.options = this._descriptor.options;\n this.dirname = this._descriptor.dirname;\n this.name = this._descriptor.name;\n this.file = this._descriptor.file\n ? {\n request: this._descriptor.file.request,\n resolved: this._descriptor.file.resolved,\n }\n : undefined;\n\n // Freeze the object to make it clear that people shouldn't expect mutating\n // this object to do anything. A new item should be created if they want\n // to change something.\n Object.freeze(this);\n }\n}\n\nObject.freeze(ConfigItem.prototype);\n"],"mappings":";;;;;;;;AAGA,SAAAA,MAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,KAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,IAAAE,kBAAA,GAAAD,OAAA;AAIO,SAASE,wBAAwBA,CACtCC,IAA6B,EACZ;EACjB,OAAO,IAAIC,UAAU,CAACD,IAAI,CAAC;AAC7B;AAQO,UAAUE,gBAAgBA,CAC/BC,KAGgD,EAChD;EACEC,OAAO,GAAG,GAAG;EACbC;AAIF,CAAC,GAAG,CAAC,CAAC,EACoB;EAC1B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I,CAACT,WAAW,CAACK,IAAI,CAACI,OAAO;MACtCC,QAAQ,EAAE,IAAI,CAACV,WAAW,CAACK,IAAI,CAACK;IAClC,CAAC,GACDT,SAAS;IAKbK,MAAM,CAACK,MAAM,CAAC,IAAI,CAAC;EACrB;AACF;AAEAL,MAAM,CAACK,MAAM,CAAC1B,UAAU,CAAC2B,SAAS,CAAC;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/partial.js b/node_modules/@babel/core/lib/config/partial.js new file mode 100644 index 0000000..5874ad9 --- /dev/null +++ b/node_modules/@babel/core/lib/config/partial.js @@ -0,0 +1,158 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = loadPrivatePartialConfig; +exports.loadPartialConfig = loadPartialConfig; +function _path() { + const data = require("path"); + _path = function () { + return data; + }; + return data; +} +var _plugin = require("./plugin.js"); +var _util = require("./util.js"); +var _item = require("./item.js"); +var _configChain = require("./config-chain.js"); +var _environment = require("./helpers/environment.js"); +var _options = require("./validation/options.js"); +var _index = require("./files/index.js"); +var _resolveTargets = require("./resolve-targets.js"); +const _excluded = ["showIgnoredFiles"]; +function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } +function resolveRootMode(rootDir, rootMode) { + switch (rootMode) { + case "root": + return rootDir; + case "upward-optional": + { + const upwardRootDir = (0, _index.findConfigUpwards)(rootDir); + return upwardRootDir === null ? rootDir : upwardRootDir; + } + case "upward": + { + const upwardRootDir = (0, _index.findConfigUpwards)(rootDir); + if (upwardRootDir !== null) return upwardRootDir; + throw Object.assign(new Error(`Babel was run with rootMode:"upward" but a root could not ` + `be found when searching upward from "${rootDir}".\n` + `One of the following config files must be in the directory tree: ` + `"${_index.ROOT_CONFIG_FILENAMES.join(", ")}".`), { + code: "BABEL_ROOT_NOT_FOUND", + dirname: rootDir + }); + } + default: + throw new Error(`Assertion failure - unknown rootMode value.`); + } +} +function* loadPrivatePartialConfig(inputOpts) { + if (inputOpts != null && (typeof inputOpts !== "object" || Array.isArray(inputOpts))) { + throw new Error("Babel options must be an object, null, or undefined"); + } + const args = inputOpts ? (0, _options.validate)("arguments", inputOpts) : {}; + const { + envName = (0, _environment.getEnv)(), + cwd = ".", + root: rootDir = ".", + rootMode = "root", + caller, + cloneInputAst = true + } = args; + const absoluteCwd = _path().resolve(cwd); + const absoluteRootDir = resolveRootMode(_path().resolve(absoluteCwd, rootDir), rootMode); + const filename = typeof args.filename === "string" ? _path().resolve(cwd, args.filename) : undefined; + const showConfigPath = yield* (0, _index.resolveShowConfigPath)(absoluteCwd); + const context = { + filename, + cwd: absoluteCwd, + root: absoluteRootDir, + envName, + caller, + showConfig: showConfigPath === filename + }; + const configChain = yield* (0, _configChain.buildRootChain)(args, context); + if (!configChain) return null; + const merged = { + assumptions: {} + }; + configChain.options.forEach(opts => { + (0, _util.mergeOptions)(merged, opts); + }); + const options = Object.assign({}, merged, { + targets: (0, _resolveTargets.resolveTargets)(merged, absoluteRootDir), + cloneInputAst, + babelrc: false, + configFile: false, + browserslistConfigFile: false, + passPerPreset: false, + envName: context.envName, + cwd: context.cwd, + root: context.root, + rootMode: "root", + filename: typeof context.filename === "string" ? context.filename : undefined, + plugins: configChain.plugins.map(descriptor => (0, _item.createItemFromDescriptor)(descriptor)), + presets: configChain.presets.map(descriptor => (0, _item.createItemFromDescriptor)(descriptor)) + }); + return { + options, + context, + fileHandling: configChain.fileHandling, + ignore: configChain.ignore, + babelrc: configChain.babelrc, + config: configChain.config, + files: configChain.files + }; +} +function* loadPartialConfig(opts) { + let showIgnoredFiles = false; + if (typeof opts === "object" && opts !== null && !Array.isArray(opts)) { + var _opts = opts; + ({ + showIgnoredFiles + } = _opts); + opts = _objectWithoutPropertiesLoose(_opts, _excluded); + _opts; + } + const result = yield* loadPrivatePartialConfig(opts); + if (!result) return null; + const { + options, + babelrc, + ignore, + config, + fileHandling, + files + } = result; + if (fileHandling === "ignored" && !showIgnoredFiles) { + return null; + } + (options.plugins || []).forEach(item => { + if (item.value instanceof _plugin.default) { + throw new Error("Passing cached plugin instances is not supported in " + "babel.loadPartialConfig()"); + } + }); + return new PartialConfig(options, babelrc ? babelrc.filepath : undefined, ignore ? ignore.filepath : undefined, config ? config.filepath : undefined, fileHandling, files); +} +class PartialConfig { + constructor(options, babelrc, ignore, config, fileHandling, files) { + this.options = void 0; + this.babelrc = void 0; + this.babelignore = void 0; + this.config = void 0; + this.fileHandling = void 0; + this.files = void 0; + this.options = options; + this.babelignore = ignore; + this.babelrc = babelrc; + this.config = config; + this.fileHandling = fileHandling; + this.files = files; + Object.freeze(this); + } + hasFilesystemConfig() { + return this.babelrc !== undefined || this.config !== undefined; + } +} +Object.freeze(PartialConfig.prototype); +0 && 0; + +//# sourceMappingURL=partial.js.map diff --git a/node_modules/@babel/core/lib/config/partial.js.map b/node_modules/@babel/core/lib/config/partial.js.map new file mode 100644 index 0000000..de50fdb --- /dev/null +++ b/node_modules/@babel/core/lib/config/partial.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_path","data","require","_plugin","_util","_item","_configChain","_environment","_options","_index","_resolveTargets","_excluded","_objectWithoutPropertiesLoose","source","excluded","target","sourceKeys","Object","keys","key","i","length","indexOf","resolveRootMode","rootDir","rootMode","upwardRootDir","findConfigUpwards","assign","Error","ROOT_CONFIG_FILENAMES","join","code","dirname","loadPrivatePartialConfig","inputOpts","Array","isArray","args","validate","envName","getEnv","cwd","root","caller","cloneInputAst","absoluteCwd","path","resolve","absoluteRootDir","filename","undefined","showConfigPath","resolveShowConfigPath","context","showConfig","configChain","buildRootChain","merged","assumptions","options","forEach","opts","mergeOptions","targets","resolveTargets","babelrc","configFile","browserslistConfigFile","passPerPreset","plugins","map","descriptor","createItemFromDescriptor","presets","fileHandling","ignore","config","files","loadPartialConfig","showIgnoredFiles","_opts","result","item","value","Plugin","PartialConfig","filepath","constructor","babelignore","freeze","hasFilesystemConfig","prototype"],"sources":["../../src/config/partial.ts"],"sourcesContent":["import path from \"path\";\nimport type { Handler } from \"gensync\";\nimport Plugin from \"./plugin.ts\";\nimport { mergeOptions } from \"./util.ts\";\nimport { createItemFromDescriptor } from \"./item.ts\";\nimport { buildRootChain } from \"./config-chain.ts\";\nimport type { ConfigContext, FileHandling } from \"./config-chain.ts\";\nimport { getEnv } from \"./helpers/environment.ts\";\nimport { validate } from \"./validation/options.ts\";\n\nimport type {\n ValidatedOptions,\n NormalizedOptions,\n RootMode,\n} from \"./validation/options.ts\";\n\nimport {\n findConfigUpwards,\n resolveShowConfigPath,\n ROOT_CONFIG_FILENAMES,\n} from \"./files/index.ts\";\nimport type { ConfigFile, IgnoreFile } from \"./files/index.ts\";\nimport { resolveTargets } from \"./resolve-targets.ts\";\n\nfunction resolveRootMode(rootDir: string, rootMode: RootMode): string {\n switch (rootMode) {\n case \"root\":\n return rootDir;\n\n case \"upward-optional\": {\n const upwardRootDir = findConfigUpwards(rootDir);\n return upwardRootDir === null ? rootDir : upwardRootDir;\n }\n\n case \"upward\": {\n const upwardRootDir = findConfigUpwards(rootDir);\n if (upwardRootDir !== null) return upwardRootDir;\n\n throw Object.assign(\n new Error(\n `Babel was run with rootMode:\"upward\" but a root could not ` +\n `be found when searching upward from \"${rootDir}\".\\n` +\n `One of the following config files must be in the directory tree: ` +\n `\"${ROOT_CONFIG_FILENAMES.join(\", \")}\".`,\n ) as any,\n {\n code: \"BABEL_ROOT_NOT_FOUND\",\n dirname: rootDir,\n },\n );\n }\n default:\n throw new Error(`Assertion failure - unknown rootMode value.`);\n }\n}\n\ntype PrivPartialConfig = {\n options: NormalizedOptions;\n context: ConfigContext;\n fileHandling: FileHandling;\n ignore: IgnoreFile | void;\n babelrc: ConfigFile | void;\n config: ConfigFile | void;\n files: Set;\n};\n\nexport default function* loadPrivatePartialConfig(\n inputOpts: unknown,\n): Handler {\n if (\n inputOpts != null &&\n (typeof inputOpts !== \"object\" || Array.isArray(inputOpts))\n ) {\n throw new Error(\"Babel options must be an object, null, or undefined\");\n }\n\n const args = inputOpts ? validate(\"arguments\", inputOpts) : {};\n\n const {\n envName = getEnv(),\n cwd = \".\",\n root: rootDir = \".\",\n rootMode = \"root\",\n caller,\n cloneInputAst = true,\n } = args;\n const absoluteCwd = path.resolve(cwd);\n const absoluteRootDir = resolveRootMode(\n path.resolve(absoluteCwd, rootDir),\n rootMode,\n );\n\n const filename =\n typeof args.filename === \"string\"\n ? path.resolve(cwd, args.filename)\n : undefined;\n\n const showConfigPath = yield* resolveShowConfigPath(absoluteCwd);\n\n const context: ConfigContext = {\n filename,\n cwd: absoluteCwd,\n root: absoluteRootDir,\n envName,\n caller,\n showConfig: showConfigPath === filename,\n };\n\n const configChain = yield* buildRootChain(args, context);\n if (!configChain) return null;\n\n const merged: ValidatedOptions = {\n assumptions: {},\n };\n configChain.options.forEach(opts => {\n mergeOptions(merged as any, opts);\n });\n\n const options: NormalizedOptions = {\n ...merged,\n targets: resolveTargets(merged, absoluteRootDir),\n\n // Tack the passes onto the object itself so that, if this object is\n // passed back to Babel a second time, it will be in the right structure\n // to not change behavior.\n cloneInputAst,\n babelrc: false,\n configFile: false,\n browserslistConfigFile: false,\n passPerPreset: false,\n envName: context.envName,\n cwd: context.cwd,\n root: context.root,\n rootMode: \"root\",\n filename:\n typeof context.filename === \"string\" ? context.filename : undefined,\n\n plugins: configChain.plugins.map(descriptor =>\n createItemFromDescriptor(descriptor),\n ),\n presets: configChain.presets.map(descriptor =>\n createItemFromDescriptor(descriptor),\n ),\n };\n\n return {\n options,\n context,\n fileHandling: configChain.fileHandling,\n ignore: configChain.ignore,\n babelrc: configChain.babelrc,\n config: configChain.config,\n files: configChain.files,\n };\n}\n\ntype LoadPartialConfigOpts = {\n showIgnoredFiles?: boolean;\n};\n\nexport function* loadPartialConfig(\n opts?: LoadPartialConfigOpts,\n): Handler {\n let showIgnoredFiles = false;\n // We only extract showIgnoredFiles if opts is an object, so that\n // loadPrivatePartialConfig can throw the appropriate error if it's not.\n if (typeof opts === \"object\" && opts !== null && !Array.isArray(opts)) {\n ({ showIgnoredFiles, ...opts } = opts);\n }\n\n const result: PrivPartialConfig | undefined | null =\n yield* loadPrivatePartialConfig(opts);\n if (!result) return null;\n\n const { options, babelrc, ignore, config, fileHandling, files } = result;\n\n if (fileHandling === \"ignored\" && !showIgnoredFiles) {\n return null;\n }\n\n (options.plugins || []).forEach(item => {\n // @ts-expect-error todo(flow->ts): better type annotation for `item.value`\n if (item.value instanceof Plugin) {\n throw new Error(\n \"Passing cached plugin instances is not supported in \" +\n \"babel.loadPartialConfig()\",\n );\n }\n });\n\n return new PartialConfig(\n options,\n babelrc ? babelrc.filepath : undefined,\n ignore ? ignore.filepath : undefined,\n config ? config.filepath : undefined,\n fileHandling,\n files,\n );\n}\n\nexport type { PartialConfig };\n\nclass PartialConfig {\n /**\n * These properties are public, so any changes to them should be considered\n * a breaking change to Babel's API.\n */\n options: NormalizedOptions;\n babelrc: string | void;\n babelignore: string | void;\n config: string | void;\n fileHandling: FileHandling;\n files: Set;\n\n constructor(\n options: NormalizedOptions,\n babelrc: string | void,\n ignore: string | void,\n config: string | void,\n fileHandling: FileHandling,\n files: Set,\n ) {\n this.options = options;\n this.babelignore = ignore;\n this.babelrc = babelrc;\n this.config = config;\n this.fileHandling = fileHandling;\n this.files = files;\n\n // Freeze since this is a public API and it should be extremely obvious that\n // reassigning properties on here does nothing.\n Object.freeze(this);\n }\n\n /**\n * Returns true if there is a config file in the filesystem for this config.\n */\n hasFilesystemConfig(): boolean {\n return this.babelrc !== undefined || this.config !== undefined;\n }\n}\nObject.freeze(PartialConfig.prototype);\n"],"mappings":";;;;;;;AAAA,SAAAA,MAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,KAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,IAAAE,OAA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0B,EAC1BG,KAAkB,EAClB;IAAA,KAdFlB,OAAO;IAAA,KACPM,OAAO;IAAA,KACPuB,WAAW;IAAA,KACXZ,MAAM;IAAA,KACNF,YAAY;IAAA,KACZG,KAAK;IAUH,IAAI,CAAClB,OAAO,GAAGA,OAAO;IACtB,IAAI,CAAC6B,WAAW,GAAGb,MAAM;IACzB,IAAI,CAACV,OAAO,GAAGA,OAAO;IACtB,IAAI,CAACW,MAAM,GAAGA,MAAM;IACpB,IAAI,CAACF,YAAY,GAAGA,YAAY;IAChC,IAAI,CAACG,KAAK,GAAGA,KAAK;IAIlB7D,MAAM,CAACyE,MAAM,CAAC,IAAI,CAAC;EACrB;EAKAC,mBAAmBA,CAAA,EAAY;IAC7B,OAAO,IAAI,CAACzB,OAAO,KAAKf,SAAS,IAAI,IAAI,CAAC0B,MAAM,KAAK1B,SAAS;EAChE;AACF;AACAlC,MAAM,CAACyE,MAAM,CAACJ,aAAa,CAACM,SAAS,CAAC;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/pattern-to-regex.js b/node_modules/@babel/core/lib/config/pattern-to-regex.js new file mode 100644 index 0000000..e061f79 --- /dev/null +++ b/node_modules/@babel/core/lib/config/pattern-to-regex.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = pathToPattern; +function _path() { + const data = require("path"); + _path = function () { + return data; + }; + return data; +} +const sep = `\\${_path().sep}`; +const endSep = `(?:${sep}|$)`; +const substitution = `[^${sep}]+`; +const starPat = `(?:${substitution}${sep})`; +const starPatLast = `(?:${substitution}${endSep})`; +const starStarPat = `${starPat}*?`; +const starStarPatLast = `${starPat}*?${starPatLast}?`; +function escapeRegExp(string) { + return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&"); +} +function pathToPattern(pattern, dirname) { + const parts = _path().resolve(dirname, pattern).split(_path().sep); + return new RegExp(["^", ...parts.map((part, i) => { + const last = i === parts.length - 1; + if (part === "**") return last ? starStarPatLast : starStarPat; + if (part === "*") return last ? starPatLast : starPat; + if (part.indexOf("*.") === 0) { + return substitution + escapeRegExp(part.slice(1)) + (last ? endSep : sep); + } + return escapeRegExp(part) + (last ? endSep : sep); + })].join("")); +} +0 && 0; + +//# sourceMappingURL=pattern-to-regex.js.map diff --git a/node_modules/@babel/core/lib/config/pattern-to-regex.js.map b/node_modules/@babel/core/lib/config/pattern-to-regex.js.map new file mode 100644 index 0000000..ed93e42 --- /dev/null +++ b/node_modules/@babel/core/lib/config/pattern-to-regex.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_path","data","require","sep","path","endSep","substitution","starPat","starPatLast","starStarPat","starStarPatLast","escapeRegExp","string","replace","pathToPattern","pattern","dirname","parts","resolve","split","RegExp","map","part","i","last","length","indexOf","slice","join"],"sources":["../../src/config/pattern-to-regex.ts"],"sourcesContent":["import path from \"path\";\n\nconst sep = `\\\\${path.sep}`;\nconst endSep = `(?:${sep}|$)`;\n\nconst substitution = `[^${sep}]+`;\n\nconst starPat = `(?:${substitution}${sep})`;\nconst starPatLast = `(?:${substitution}${endSep})`;\n\nconst starStarPat = `${starPat}*?`;\nconst starStarPatLast = `${starPat}*?${starPatLast}?`;\n\nfunction escapeRegExp(string: string) {\n return string.replace(/[|\\\\{}()[\\]^$+*?.]/g, \"\\\\$&\");\n}\n\n/**\n * Implement basic pattern matching that will allow users to do the simple\n * tests with * and **. If users want full complex pattern matching, then can\n * always use regex matching, or function validation.\n */\nexport default function pathToPattern(\n pattern: string,\n dirname: string,\n): RegExp {\n const parts = path.resolve(dirname, pattern).split(path.sep);\n\n return new RegExp(\n [\n \"^\",\n ...parts.map((part, i) => {\n const last = i === parts.length - 1;\n\n // ** matches 0 or more path parts.\n if (part === \"**\") return last ? starStarPatLast : starStarPat;\n\n // * matches 1 path part.\n if (part === \"*\") return last ? starPatLast : starPat;\n\n // *.ext matches a wildcard with an extension.\n if (part.indexOf(\"*.\") === 0) {\n return (\n substitution + escapeRegExp(part.slice(1)) + (last ? endSep : sep)\n );\n }\n\n // Otherwise match the pattern text.\n return escapeRegExp(part) + (last ? endSep : sep);\n }),\n ].join(\"\"),\n );\n}\n"],"mappings":";;;;;;AAAA,SAAAA,MAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,KAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,MAAME,GAAG,GAAG,KAAKC,MAAGA,CAAC,CAACD,GAAG,EAAE;AAC3B,MAAME,MAAM,GAAG,MAAMF,GAAG,KAAK;AAE7B,MAAMG,YAAY,GAAG,KAAKH,GAAG,IAAI;AAEjC,MAAMI,OAAO,GAAG,MAAMD,YAAY,GAAGH,GAAG,GAAG;AAC3C,MAAMK,WAAW,GAAG,MAAMF,YAAY,GAAGD,MAAM,GAAG;AAElD,MAAMI,WAAW,GAAG,GAAGF,OAAO,IAAI;AAClC,MAAMG,eAAe,GAAG,GAAGH,OAAO,KAAKC,WAAW,GAAG;AAErD,SAASG,YAAYA,CAACC,MAAc,EAAE;EACpC,OAAOA,MAAM,CAACC,OAAO,CAAC,qBAAqB,EAAE,MAAM,CAAC;AACtD;AAOe,SAASC,aAAaA,CACnCC,OAAe,EACfC,OAAe,EACP;EACR,MAAMC,KAAK,GAAGb,MAAGA,CAAC,CAACc,OAAO,CAACF,OAAO,EAAED,OAAO,CAAC,CAACI,KAAK,CAACf,MAAGA,CAAC,CAACD,GAAG,CAAC;EAE5D,OAAO,IAAIiB,MAAM,CACf,CACE,GAAG,EACH,GAAGH,KAAK,CAACI,GAAG,CAAC,CAACC,IAAI,EAAEC,CAAC,KAAK;IACxB,MAAMC,IAAI,GAAGD,CAAC,KAAKN,KAAK,CAACQ,MAAM,GAAG,CAAC;IAGnC,IAAIH,IAAI,KAAK,IAAI,EAAE,OAAOE,IAAI,GAAGd,eAAe,GAAGD,WAAW;IAG9D,IAAIa,IAAI,KAAK,GAAG,EAAE,OAAOE,IAAI,GAAGhB,WAAW,GAAGD,OAAO;IAGrD,IAAIe,IAAI,CAACI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;MAC5B,OACEpB,YAAY,GAAGK,YAAY,CAACW,IAAI,CAACK,KAAK,CAAC,CAAC,CAAC,CAAC,IAAIH,IAAI,GAAGnB,MAAM,GAAGF,GAAG,CAAC;IAEtE;IAGA,OAAOQ,YAAY,CAACW,IAAI,CAAC,IAAIE,IAAI,GAAGnB,MAAM,GAAGF,GAAG,CAAC;EACnD,CAAC,CAAC,CACH,CAACyB,IAAI,CAAC,EAAE,CACX,CAAC;AACH;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/plugin.js b/node_modules/@babel/core/lib/config/plugin.js new file mode 100644 index 0000000..21a28cd --- /dev/null +++ b/node_modules/@babel/core/lib/config/plugin.js @@ -0,0 +1,33 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _deepArray = require("./helpers/deep-array.js"); +class Plugin { + constructor(plugin, options, key, externalDependencies = (0, _deepArray.finalize)([])) { + this.key = void 0; + this.manipulateOptions = void 0; + this.post = void 0; + this.pre = void 0; + this.visitor = void 0; + this.parserOverride = void 0; + this.generatorOverride = void 0; + this.options = void 0; + this.externalDependencies = void 0; + this.key = plugin.name || key; + this.manipulateOptions = plugin.manipulateOptions; + this.post = plugin.post; + this.pre = plugin.pre; + this.visitor = plugin.visitor || {}; + this.parserOverride = plugin.parserOverride; + this.generatorOverride = plugin.generatorOverride; + this.options = options; + this.externalDependencies = externalDependencies; + } +} +exports.default = Plugin; +0 && 0; + +//# sourceMappingURL=plugin.js.map diff --git a/node_modules/@babel/core/lib/config/plugin.js.map b/node_modules/@babel/core/lib/config/plugin.js.map new file mode 100644 index 0000000..87acda8 --- /dev/null +++ b/node_modules/@babel/core/lib/config/plugin.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_deepArray","require","Plugin","constructor","plugin","options","key","externalDependencies","finalize","manipulateOptions","post","pre","visitor","parserOverride","generatorOverride","name","exports","default"],"sources":["../../src/config/plugin.ts"],"sourcesContent":["import { finalize } from \"./helpers/deep-array.ts\";\nimport type { ReadonlyDeepArray } from \"./helpers/deep-array.ts\";\nimport type { PluginObject } from \"./validation/plugins.ts\";\n\nexport default class Plugin {\n key: string | undefined | null;\n manipulateOptions?: (options: unknown, parserOpts: unknown) => void;\n post?: PluginObject[\"post\"];\n pre?: PluginObject[\"pre\"];\n visitor: PluginObject[\"visitor\"];\n\n parserOverride?: Function;\n generatorOverride?: Function;\n\n options: object;\n\n externalDependencies: ReadonlyDeepArray;\n\n constructor(\n plugin: PluginObject,\n options: object,\n key?: string,\n externalDependencies: ReadonlyDeepArray = finalize([]),\n ) {\n this.key = plugin.name || key;\n\n this.manipulateOptions = plugin.manipulateOptions;\n this.post = plugin.post;\n this.pre = plugin.pre;\n this.visitor = plugin.visitor || {};\n this.parserOverride = plugin.parserOverride;\n this.generatorOverride = plugin.generatorOverride;\n\n this.options = options;\n this.externalDependencies = externalDependencies;\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,UAAA,GAAAC,OAAA;AAIe,MAAMC,MAAM,CAAC;EAc1BC,WAAWA,CACTC,MAAoB,EACpBC,OAAe,EACfC,GAAY,EACZC,oBAA+C,GAAG,IAAAC,mBAAQ,EAAC,EAAE,CAAC,EAC9D;IAAA,KAlBFF,GAAG;IAAA,KACHG,iBAAiB;IAAA,KACjBC,IAAI;IAAA,KACJC,GAAG;IAAA,KACHC,OAAO;IAAA,KAEPC,cAAc;IAAA,KACdC,iBAAiB;IAAA,KAEjBT,OAAO;IAAA,KAEPE,oBAAoB;IAQlB,IAAI,CAACD,GAAG,GAAGF,MAAM,CAACW,IAAI,IAAIT,GAAG;IAE7B,IAAI,CAACG,iBAAiB,GAAGL,MAAM,CAACK,iBAAiB;IACjD,IAAI,CAACC,IAAI,GAAGN,MAAM,CAACM,IAAI;IACvB,IAAI,CAACC,GAAG,GAAGP,MAAM,CAACO,GAAG;IACrB,IAAI,CAACC,OAAO,GAAGR,MAAM,CAACQ,OAAO,IAAI,CAAC,CAAC;IACnC,IAAI,CAACC,cAAc,GAAGT,MAAM,CAACS,cAAc;IAC3C,IAAI,CAACC,iBAAiB,GAAGV,MAAM,CAACU,iBAAiB;IAEjD,IAAI,CAACT,OAAO,GAAGA,OAAO;IACtB,IAAI,CAACE,oBAAoB,GAAGA,oBAAoB;EAClD;AACF;AAACS,OAAA,CAAAC,OAAA,GAAAf,MAAA;AAAA","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/printer.js b/node_modules/@babel/core/lib/config/printer.js new file mode 100644 index 0000000..3ac2c07 --- /dev/null +++ b/node_modules/@babel/core/lib/config/printer.js @@ -0,0 +1,113 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ConfigPrinter = exports.ChainFormatter = void 0; +function _gensync() { + const data = require("gensync"); + _gensync = function () { + return data; + }; + return data; +} +const ChainFormatter = exports.ChainFormatter = { + Programmatic: 0, + Config: 1 +}; +const Formatter = { + title(type, callerName, filepath) { + let title = ""; + if (type === ChainFormatter.Programmatic) { + title = "programmatic options"; + if (callerName) { + title += " from " + callerName; + } + } else { + title = "config " + filepath; + } + return title; + }, + loc(index, envName) { + let loc = ""; + if (index != null) { + loc += `.overrides[${index}]`; + } + if (envName != null) { + loc += `.env["${envName}"]`; + } + return loc; + }, + *optionsAndDescriptors(opt) { + const content = Object.assign({}, opt.options); + delete content.overrides; + delete content.env; + const pluginDescriptors = [...(yield* opt.plugins())]; + if (pluginDescriptors.length) { + content.plugins = pluginDescriptors.map(d => descriptorToConfig(d)); + } + const presetDescriptors = [...(yield* opt.presets())]; + if (presetDescriptors.length) { + content.presets = [...presetDescriptors].map(d => descriptorToConfig(d)); + } + return JSON.stringify(content, undefined, 2); + } +}; +function descriptorToConfig(d) { + var _d$file; + let name = (_d$file = d.file) == null ? void 0 : _d$file.request; + if (name == null) { + if (typeof d.value === "object") { + name = d.value; + } else if (typeof d.value === "function") { + name = `[Function: ${d.value.toString().slice(0, 50)} ... ]`; + } + } + if (name == null) { + name = "[Unknown]"; + } + if (d.options === undefined) { + return name; + } else if (d.name == null) { + return [name, d.options]; + } else { + return [name, d.options, d.name]; + } +} +class ConfigPrinter { + constructor() { + this._stack = []; + } + configure(enabled, type, { + callerName, + filepath + }) { + if (!enabled) return () => {}; + return (content, index, envName) => { + this._stack.push({ + type, + callerName, + filepath, + content, + index, + envName + }); + }; + } + static *format(config) { + let title = Formatter.title(config.type, config.callerName, config.filepath); + const loc = Formatter.loc(config.index, config.envName); + if (loc) title += ` ${loc}`; + const content = yield* Formatter.optionsAndDescriptors(config.content); + return `${title}\n${content}`; + } + *output() { + if (this._stack.length === 0) return ""; + const configs = yield* _gensync().all(this._stack.map(s => ConfigPrinter.format(s))); + return configs.join("\n\n"); + } +} +exports.ConfigPrinter = ConfigPrinter; +0 && 0; + +//# sourceMappingURL=printer.js.map diff --git a/node_modules/@babel/core/lib/config/printer.js.map b/node_modules/@babel/core/lib/config/printer.js.map new file mode 100644 index 0000000..5a55940 --- /dev/null +++ b/node_modules/@babel/core/lib/config/printer.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_gensync","data","require","ChainFormatter","exports","Programmatic","Config","Formatter","title","type","callerName","filepath","loc","index","envName","optionsAndDescriptors","opt","content","Object","assign","options","overrides","env","pluginDescriptors","plugins","length","map","d","descriptorToConfig","presetDescriptors","presets","JSON","stringify","undefined","_d$file","name","file","request","value","toString","slice","ConfigPrinter","constructor","_stack","configure","enabled","push","format","config","output","configs","gensync","all","s","join"],"sources":["../../src/config/printer.ts"],"sourcesContent":["import gensync from \"gensync\";\n\nimport type { Handler } from \"gensync\";\n\nimport type {\n OptionsAndDescriptors,\n UnloadedDescriptor,\n} from \"./config-descriptors.ts\";\n\n// todo: Use flow enums when @babel/transform-flow-types supports it\nexport const ChainFormatter = {\n Programmatic: 0,\n Config: 1,\n};\n\ntype PrintableConfig = {\n content: OptionsAndDescriptors;\n type: (typeof ChainFormatter)[keyof typeof ChainFormatter];\n callerName: string | undefined | null;\n filepath: string | undefined | null;\n index: number | undefined | null;\n envName: string | undefined | null;\n};\n\nconst Formatter = {\n title(\n type: (typeof ChainFormatter)[keyof typeof ChainFormatter],\n callerName?: string | null,\n filepath?: string | null,\n ): string {\n let title = \"\";\n if (type === ChainFormatter.Programmatic) {\n title = \"programmatic options\";\n if (callerName) {\n title += \" from \" + callerName;\n }\n } else {\n title = \"config \" + filepath;\n }\n return title;\n },\n loc(index?: number | null, envName?: string | null): string {\n let loc = \"\";\n if (index != null) {\n loc += `.overrides[${index}]`;\n }\n if (envName != null) {\n loc += `.env[\"${envName}\"]`;\n }\n return loc;\n },\n\n *optionsAndDescriptors(opt: OptionsAndDescriptors) {\n const content = { ...opt.options };\n // overrides and env will be printed as separated config items\n delete content.overrides;\n delete content.env;\n // resolve to descriptors\n const pluginDescriptors = [...(yield* opt.plugins())];\n if (pluginDescriptors.length) {\n content.plugins = pluginDescriptors.map(d => descriptorToConfig(d));\n }\n const presetDescriptors = [...(yield* opt.presets())];\n if (presetDescriptors.length) {\n content.presets = [...presetDescriptors].map(d => descriptorToConfig(d));\n }\n return JSON.stringify(content, undefined, 2);\n },\n};\n\nfunction descriptorToConfig(\n d: UnloadedDescriptor,\n): object | string | [string, unknown] | [string, unknown, string] {\n let name: object | string = d.file?.request;\n if (name == null) {\n if (typeof d.value === \"object\") {\n name = d.value;\n } else if (typeof d.value === \"function\") {\n // If the unloaded descriptor is a function, i.e. `plugins: [ require(\"my-plugin\") ]`,\n // we print the first 50 characters of the function source code and hopefully we can see\n // `name: 'my-plugin'` in the source\n name = `[Function: ${d.value.toString().slice(0, 50)} ... ]`;\n }\n }\n if (name == null) {\n name = \"[Unknown]\";\n }\n if (d.options === undefined) {\n return name;\n } else if (d.name == null) {\n return [name, d.options];\n } else {\n return [name, d.options, d.name];\n }\n}\n\nexport class ConfigPrinter {\n _stack: Array = [];\n configure(\n enabled: boolean,\n type: (typeof ChainFormatter)[keyof typeof ChainFormatter],\n {\n callerName,\n filepath,\n }: {\n callerName?: string;\n filepath?: string;\n },\n ) {\n if (!enabled) return () => {};\n return (\n content: OptionsAndDescriptors,\n index?: number | null,\n envName?: string | null,\n ) => {\n this._stack.push({\n type,\n callerName,\n filepath,\n content,\n index,\n envName,\n });\n };\n }\n static *format(config: PrintableConfig): Handler {\n let title = Formatter.title(\n config.type,\n config.callerName,\n config.filepath,\n );\n const loc = Formatter.loc(config.index, config.envName);\n if (loc) title += ` ${loc}`;\n const content = yield* Formatter.optionsAndDescriptors(config.content);\n return `${title}\\n${content}`;\n }\n\n *output(): Handler {\n if (this._stack.length === 0) return \"\";\n const configs = yield* gensync.all(\n this._stack.map(s => ConfigPrinter.format(s)),\n );\n return configs.join(\"\\n\\n\");\n }\n}\n"],"mappings":";;;;;;AAAA,SAAAA,SAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,QAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAUO,MAAME,cAAc,GAAAC,OAAA,CAAAD,cAAA,GAAG;EAC5BE,YAAY,EAAE,CAAC;EACfC,MAAM,EAAE;AACV,CAAC;AAWD,MAAMC,SAAS,GAAG;EAChBC,KAAKA,CACHC,IAA0D,EAC1DC,UAA0B,EAC1BC,QAAwB,EAChB;IACR,IAAIH,KAAK,GAAG,EAAE;IACd,IAAIC,IAAI,KAAKN,cAAc,CAACE,YAAY,EAAE;MACxCG,KAAK,GAAG,sBAAsB;MAC9B,IAAIE,UAAU,EAAE;QACdF,KAAK,IAAI,QAAQ,GAAGE,UAAU;MAChC;IACF,CAAC,MAAM;MACLF,KAAK,GAAG,SAAS,GAAGG,QAAQ;IAC9B;IACA,OAAOH,KAAK;EACd,CAAC;EACDI,GAAGA,CAACC,KAAqB,EAAEC,OAAuB,EAAU;IAC1D,IAAIF,GAAG,GAAG,EAAE;IACZ,IAAIC,KAAK,IAAI,I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,CAAClC,OAAO,CAAC;IACvD,IAAIF,GAAG,EAAEJ,KAAK,IAAI,IAAII,GAAG,EAAE;IAC3B,MAAMK,OAAO,GAAG,OAAOV,SAAS,CAACQ,qBAAqB,CAACiC,MAAM,CAAC/B,OAAO,CAAC;IACtE,OAAO,GAAGT,KAAK,KAAKS,OAAO,EAAE;EAC/B;EAEA,CAACgC,MAAMA,CAAA,EAAoB;IACzB,IAAI,IAAI,CAACN,MAAM,CAAClB,MAAM,KAAK,CAAC,EAAE,OAAO,EAAE;IACvC,MAAMyB,OAAO,GAAG,OAAOC,SAAMA,CAAC,CAACC,GAAG,CAChC,IAAI,CAACT,MAAM,CAACjB,GAAG,CAAC2B,CAAC,IAAIZ,aAAa,CAACM,MAAM,CAACM,CAAC,CAAC,CAC9C,CAAC;IACD,OAAOH,OAAO,CAACI,IAAI,CAAC,MAAM,CAAC;EAC7B;AACF;AAAClD,OAAA,CAAAqC,aAAA,GAAAA,aAAA;AAAA","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/resolve-targets-browser.js b/node_modules/@babel/core/lib/config/resolve-targets-browser.js new file mode 100644 index 0000000..3fdbd88 --- /dev/null +++ b/node_modules/@babel/core/lib/config/resolve-targets-browser.js @@ -0,0 +1,41 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.resolveBrowserslistConfigFile = resolveBrowserslistConfigFile; +exports.resolveTargets = resolveTargets; +function _helperCompilationTargets() { + const data = require("@babel/helper-compilation-targets"); + _helperCompilationTargets = function () { + return data; + }; + return data; +} +function resolveBrowserslistConfigFile(browserslistConfigFile, configFilePath) { + return undefined; +} +function resolveTargets(options, root) { + const optTargets = options.targets; + let targets; + if (typeof optTargets === "string" || Array.isArray(optTargets)) { + targets = { + browsers: optTargets + }; + } else if (optTargets) { + if ("esmodules" in optTargets) { + targets = Object.assign({}, optTargets, { + esmodules: "intersect" + }); + } else { + targets = optTargets; + } + } + return (0, _helperCompilationTargets().default)(targets, { + ignoreBrowserslistConfig: true, + browserslistEnv: options.browserslistEnv + }); +} +0 && 0; + +//# sourceMappingURL=resolve-targets-browser.js.map diff --git a/node_modules/@babel/core/lib/config/resolve-targets-browser.js.map b/node_modules/@babel/core/lib/config/resolve-targets-browser.js.map new file mode 100644 index 0000000..839585d --- /dev/null +++ b/node_modules/@babel/core/lib/config/resolve-targets-browser.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_helperCompilationTargets","data","require","resolveBrowserslistConfigFile","browserslistConfigFile","configFilePath","undefined","resolveTargets","options","root","optTargets","targets","Array","isArray","browsers","Object","assign","esmodules","getTargets","ignoreBrowserslistConfig","browserslistEnv"],"sources":["../../src/config/resolve-targets-browser.ts"],"sourcesContent":["import type { ValidatedOptions } from \"./validation/options.ts\";\nimport getTargets, {\n type InputTargets,\n} from \"@babel/helper-compilation-targets\";\n\nimport type { Targets } from \"@babel/helper-compilation-targets\";\n\nexport function resolveBrowserslistConfigFile(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n browserslistConfigFile: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n configFilePath: string,\n): string | void {\n return undefined;\n}\n\nexport function resolveTargets(\n options: ValidatedOptions,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n root: string,\n): Targets {\n const optTargets = options.targets;\n let targets: InputTargets;\n\n if (typeof optTargets === \"string\" || Array.isArray(optTargets)) {\n targets = { browsers: optTargets };\n } else if (optTargets) {\n if (\"esmodules\" in optTargets) {\n targets = { ...optTargets, esmodules: \"intersect\" };\n } else {\n // https://github.com/microsoft/TypeScript/issues/17002\n targets = optTargets as InputTargets;\n }\n }\n\n return getTargets(targets, {\n ignoreBrowserslistConfig: true,\n browserslistEnv: options.browserslistEnv,\n });\n}\n"],"mappings":";;;;;;;AACA,SAAAA,0BAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,yBAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAMO,SAASE,6BAA6BA,CAE3CC,sBAA8B,EAE9BC,cAAsB,EACP;EACf,OAAOC,SAAS;AAClB;AAEO,SAASC,cAAcA,CAC5BC,OAAyB,EAEzBC,IAAY,EACH;EACT,MAAMC,UAAU,GAAGF,OAAO,CAACG,OAAO;EAClC,IAAIA,OAAqB;EAEzB,IAAI,OAAOD,UAAU,KAAK,QAAQ,IAAIE,KAAK,CAACC,OAAO,CAACH,UAAU,CAAC,EAAE;IAC/DC,OAAO,GAAG;MAAEG,QAAQ,EAAEJ;IAAW,CAAC;EACpC,CAAC,MAAM,IAAIA,UAAU,EAAE;IACrB,IAAI,WAAW,IAAIA,UAAU,EAAE;MAC7BC,OAAO,GAAAI,MAAA,CAAAC,MAAA,KAAQN,UAAU;QAAEO,SAAS,EAAE;MAAW,EAAE;IACrD,CAAC,MAAM;MAELN,OAAO,GAAGD,UAA0B;IACtC;EACF;EAEA,OAAO,IAAAQ,mCAAU,EAACP,OAAO,EAAE;IACzBQ,wBAAwB,EAAE,IAAI;IAC9BC,eAAe,EAAEZ,OAAO,CAACY;EAC3B,CAAC,CAAC;AACJ;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/resolve-targets.js b/node_modules/@babel/core/lib/config/resolve-targets.js new file mode 100644 index 0000000..1fc539a --- /dev/null +++ b/node_modules/@babel/core/lib/config/resolve-targets.js @@ -0,0 +1,61 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.resolveBrowserslistConfigFile = resolveBrowserslistConfigFile; +exports.resolveTargets = resolveTargets; +function _path() { + const data = require("path"); + _path = function () { + return data; + }; + return data; +} +function _helperCompilationTargets() { + const data = require("@babel/helper-compilation-targets"); + _helperCompilationTargets = function () { + return data; + }; + return data; +} +({}); +function resolveBrowserslistConfigFile(browserslistConfigFile, configFileDir) { + return _path().resolve(configFileDir, browserslistConfigFile); +} +function resolveTargets(options, root) { + const optTargets = options.targets; + let targets; + if (typeof optTargets === "string" || Array.isArray(optTargets)) { + targets = { + browsers: optTargets + }; + } else if (optTargets) { + if ("esmodules" in optTargets) { + targets = Object.assign({}, optTargets, { + esmodules: "intersect" + }); + } else { + targets = optTargets; + } + } + const { + browserslistConfigFile + } = options; + let configFile; + let ignoreBrowserslistConfig = false; + if (typeof browserslistConfigFile === "string") { + configFile = browserslistConfigFile; + } else { + ignoreBrowserslistConfig = browserslistConfigFile === false; + } + return (0, _helperCompilationTargets().default)(targets, { + ignoreBrowserslistConfig, + configFile, + configPath: root, + browserslistEnv: options.browserslistEnv + }); +} +0 && 0; + +//# sourceMappingURL=resolve-targets.js.map diff --git a/node_modules/@babel/core/lib/config/resolve-targets.js.map b/node_modules/@babel/core/lib/config/resolve-targets.js.map new file mode 100644 index 0000000..0fada4e --- /dev/null +++ b/node_modules/@babel/core/lib/config/resolve-targets.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_path","data","require","_helperCompilationTargets","resolveBrowserslistConfigFile","browserslistConfigFile","configFileDir","path","resolve","resolveTargets","options","root","optTargets","targets","Array","isArray","browsers","Object","assign","esmodules","configFile","ignoreBrowserslistConfig","getTargets","configPath","browserslistEnv"],"sources":["../../src/config/resolve-targets.ts"],"sourcesContent":["type browserType = typeof import(\"./resolve-targets-browser\");\ntype nodeType = typeof import(\"./resolve-targets\");\n\n// Kind of gross, but essentially asserting that the exports of this module are the same as the\n// exports of index-browser, since this file may be replaced at bundle time with index-browser.\n({}) as any as browserType as nodeType;\n\nimport type { ValidatedOptions } from \"./validation/options.ts\";\nimport path from \"path\";\nimport getTargets, {\n type InputTargets,\n} from \"@babel/helper-compilation-targets\";\n\nimport type { Targets } from \"@babel/helper-compilation-targets\";\n\nexport function resolveBrowserslistConfigFile(\n browserslistConfigFile: string,\n configFileDir: string,\n): string | undefined {\n return path.resolve(configFileDir, browserslistConfigFile);\n}\n\nexport function resolveTargets(\n options: ValidatedOptions,\n root: string,\n): Targets {\n const optTargets = options.targets;\n let targets: InputTargets;\n\n if (typeof optTargets === \"string\" || Array.isArray(optTargets)) {\n targets = { browsers: optTargets };\n } else if (optTargets) {\n if (\"esmodules\" in optTargets) {\n targets = { ...optTargets, esmodules: \"intersect\" };\n } else {\n // https://github.com/microsoft/TypeScript/issues/17002\n targets = optTargets as InputTargets;\n }\n }\n\n const { browserslistConfigFile } = options;\n let configFile;\n let ignoreBrowserslistConfig = false;\n if (typeof browserslistConfigFile === \"string\") {\n configFile = browserslistConfigFile;\n } else {\n ignoreBrowserslistConfig = browserslistConfigFile === false;\n }\n\n return getTargets(targets, {\n ignoreBrowserslistConfig,\n configFile,\n configPath: root,\n browserslistEnv: options.browserslistEnv,\n });\n}\n"],"mappings":";;;;;;;AAQA,SAAAA,MAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,KAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,0BAAA;EAAA,MAAAF,IAAA,GAAAC,OAAA;EAAAC,yBAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAJA,CAAC,CAAC,CAAC;AAUI,SAASG,6BAA6BA,CAC3CC,sBAA8B,EAC9BC,aAAqB,EACD;EACpB,OAAOC,MAAGA,CAAC,CAACC,OAAO,CAACF,aAAa,EAAED,sBAAsB,CAAC;AAC5D;AAEO,SAASI,cAAcA,CAC5BC,OAAyB,EACzBC,IAAY,EACH;EACT,MAAMC,UAAU,GAAGF,OAAO,CAACG,OAAO;EAClC,IAAIA,OAAqB;EAEzB,IAAI,OAAOD,UAAU,KAAK,QAAQ,IAAIE,KAAK,CAACC,OAAO,CAACH,UAAU,CAAC,EAAE;IAC/DC,OAAO,GAAG;MAAEG,QAAQ,EAAEJ;IAAW,CAAC;EACpC,CAAC,MAAM,IAAIA,UAAU,EAAE;IACrB,IAAI,WAAW,IAAIA,UAAU,EAAE;MAC7BC,OAAO,GAAAI,MAAA,CAAAC,MAAA,KAAQN,UAAU;QAAEO,SAAS,EAAE;MAAW,EAAE;IACrD,CAAC,MAAM;MAELN,OAAO,GAAGD,UAA0B;IACtC;EACF;EAEA,MAAM;IAAEP;EAAuB,CAAC,GAAGK,OAAO;EAC1C,IAAIU,UAAU;EACd,IAAIC,wBAAwB,GAAG,KAAK;EACpC,IAAI,OAAOhB,sBAAsB,KAAK,QAAQ,EAAE;IAC9Ce,UAAU,GAAGf,sBAAsB;EACrC,CAAC,MAAM;IACLgB,wBAAwB,GAAGhB,sBAAsB,KAAK,KAAK;EAC7D;EAEA,OAAO,IAAAiB,mCAAU,EAACT,OAAO,EAAE;IACzBQ,wBAAwB;IACxBD,UAAU;IACVG,UAAU,EAAEZ,IAAI;IAChBa,eAAe,EAAEd,OAAO,CAACc;EAC3B,CAAC,CAAC;AACJ;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/util.js b/node_modules/@babel/core/lib/config/util.js new file mode 100644 index 0000000..077f1af --- /dev/null +++ b/node_modules/@babel/core/lib/config/util.js @@ -0,0 +1,31 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isIterableIterator = isIterableIterator; +exports.mergeOptions = mergeOptions; +function mergeOptions(target, source) { + for (const k of Object.keys(source)) { + if ((k === "parserOpts" || k === "generatorOpts" || k === "assumptions") && source[k]) { + const parserOpts = source[k]; + const targetObj = target[k] || (target[k] = {}); + mergeDefaultFields(targetObj, parserOpts); + } else { + const val = source[k]; + if (val !== undefined) target[k] = val; + } + } +} +function mergeDefaultFields(target, source) { + for (const k of Object.keys(source)) { + const val = source[k]; + if (val !== undefined) target[k] = val; + } +} +function isIterableIterator(value) { + return !!value && typeof value.next === "function" && typeof value[Symbol.iterator] === "function"; +} +0 && 0; + +//# sourceMappingURL=util.js.map diff --git a/node_modules/@babel/core/lib/config/util.js.map b/node_modules/@babel/core/lib/config/util.js.map new file mode 100644 index 0000000..696c28c --- /dev/null +++ b/node_modules/@babel/core/lib/config/util.js.map @@ -0,0 +1 @@ +{"version":3,"names":["mergeOptions","target","source","k","Object","keys","parserOpts","targetObj","mergeDefaultFields","val","undefined","isIterableIterator","value","next","Symbol","iterator"],"sources":["../../src/config/util.ts"],"sourcesContent":["import type {\n ValidatedOptions,\n NormalizedOptions,\n} from \"./validation/options.ts\";\n\nexport function mergeOptions(\n target: ValidatedOptions,\n source: ValidatedOptions | NormalizedOptions,\n): void {\n for (const k of Object.keys(source)) {\n if (\n (k === \"parserOpts\" || k === \"generatorOpts\" || k === \"assumptions\") &&\n source[k]\n ) {\n const parserOpts = source[k];\n const targetObj = target[k] || (target[k] = {});\n mergeDefaultFields(targetObj, parserOpts);\n } else {\n //@ts-expect-error k must index source\n const val = source[k];\n //@ts-expect-error assigning source to target\n if (val !== undefined) target[k] = val as any;\n }\n }\n}\n\nfunction mergeDefaultFields(target: T, source: T) {\n for (const k of Object.keys(source) as (keyof T)[]) {\n const val = source[k];\n if (val !== undefined) target[k] = val;\n }\n}\n\nexport function isIterableIterator(value: any): value is IterableIterator {\n return (\n !!value &&\n typeof value.next === \"function\" &&\n typeof value[Symbol.iterator] === \"function\"\n );\n}\n"],"mappings":";;;;;;;AAKO,SAASA,YAAYA,CAC1BC,MAAwB,EACxBC,MAA4C,EACtC;EACN,KAAK,MAAMC,CAAC,IAAIC,MAAM,CAACC,IAAI,CAACH,MAAM,CAAC,EAAE;IACnC,IACE,CAACC,CAAC,KAAK,YAAY,IAAIA,CAAC,KAAK,eAAe,IAAIA,CAAC,KAAK,aAAa,KACnED,MAAM,CAACC,CAAC,CAAC,EACT;MACA,MAAMG,UAAU,GAAGJ,MAAM,CAACC,CAAC,CAAC;MAC5B,MAAMI,SAAS,GAAGN,MAAM,CAACE,CAAC,CAAC,KAAKF,MAAM,CAACE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;MAC/CK,kBAAkB,CAACD,SAAS,EAAED,UAAU,CAAC;IAC3C,CAAC,MAAM;MAEL,MAAMG,GAAG,GAAGP,MAAM,CAACC,CAAC,CAAC;MAErB,IAAIM,GAAG,KAAKC,SAAS,EAAET,MAAM,CAACE,CAAC,CAAC,GAAGM,GAAU;IAC/C;EACF;AACF;AAEA,SAASD,kBAAkBA,CAAmBP,MAAS,EAAEC,MAAS,EAAE;EAClE,KAAK,MAAMC,CAAC,IAAIC,MAAM,CAACC,IAAI,CAACH,MAAM,CAAC,EAAiB;IAClD,MAAMO,GAAG,GAAGP,MAAM,CAACC,CAAC,CAAC;IACrB,IAAIM,GAAG,KAAKC,SAAS,EAAET,MAAM,CAACE,CAAC,CAAC,GAAGM,GAAG;EACxC;AACF;AAEO,SAASE,kBAAkBA,CAACC,KAAU,EAAkC;EAC7E,OACE,CAAC,CAACA,KAAK,IACP,OAAOA,KAAK,CAACC,IAAI,KAAK,UAAU,IAChC,OAAOD,KAAK,CAACE,MAAM,CAACC,QAAQ,CAAC,KAAK,UAAU;AAEhD;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/validation/option-assertions.js b/node_modules/@babel/core/lib/config/validation/option-assertions.js new file mode 100644 index 0000000..73d577c --- /dev/null +++ b/node_modules/@babel/core/lib/config/validation/option-assertions.js @@ -0,0 +1,277 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.access = access; +exports.assertArray = assertArray; +exports.assertAssumptions = assertAssumptions; +exports.assertBabelrcSearch = assertBabelrcSearch; +exports.assertBoolean = assertBoolean; +exports.assertCallerMetadata = assertCallerMetadata; +exports.assertCompact = assertCompact; +exports.assertConfigApplicableTest = assertConfigApplicableTest; +exports.assertConfigFileSearch = assertConfigFileSearch; +exports.assertFunction = assertFunction; +exports.assertIgnoreList = assertIgnoreList; +exports.assertInputSourceMap = assertInputSourceMap; +exports.assertObject = assertObject; +exports.assertPluginList = assertPluginList; +exports.assertRootMode = assertRootMode; +exports.assertSourceMaps = assertSourceMaps; +exports.assertSourceType = assertSourceType; +exports.assertString = assertString; +exports.assertTargets = assertTargets; +exports.msg = msg; +function _helperCompilationTargets() { + const data = require("@babel/helper-compilation-targets"); + _helperCompilationTargets = function () { + return data; + }; + return data; +} +var _options = require("./options.js"); +function msg(loc) { + switch (loc.type) { + case "root": + return ``; + case "env": + return `${msg(loc.parent)}.env["${loc.name}"]`; + case "overrides": + return `${msg(loc.parent)}.overrides[${loc.index}]`; + case "option": + return `${msg(loc.parent)}.${loc.name}`; + case "access": + return `${msg(loc.parent)}[${JSON.stringify(loc.name)}]`; + default: + throw new Error(`Assertion failure: Unknown type ${loc.type}`); + } +} +function access(loc, name) { + return { + type: "access", + name, + parent: loc + }; +} +function assertRootMode(loc, value) { + if (value !== undefined && value !== "root" && value !== "upward" && value !== "upward-optional") { + throw new Error(`${msg(loc)} must be a "root", "upward", "upward-optional" or undefined`); + } + return value; +} +function assertSourceMaps(loc, value) { + if (value !== undefined && typeof value !== "boolean" && value !== "inline" && value !== "both") { + throw new Error(`${msg(loc)} must be a boolean, "inline", "both", or undefined`); + } + return value; +} +function assertCompact(loc, value) { + if (value !== undefined && typeof value !== "boolean" && value !== "auto") { + throw new Error(`${msg(loc)} must be a boolean, "auto", or undefined`); + } + return value; +} +function assertSourceType(loc, value) { + if (value !== undefined && value !== "module" && value !== "script" && value !== "unambiguous") { + throw new Error(`${msg(loc)} must be "module", "script", "unambiguous", or undefined`); + } + return value; +} +function assertCallerMetadata(loc, value) { + const obj = assertObject(loc, value); + if (obj) { + if (typeof obj.name !== "string") { + throw new Error(`${msg(loc)} set but does not contain "name" property string`); + } + for (const prop of Object.keys(obj)) { + const propLoc = access(loc, prop); + const value = obj[prop]; + if (value != null && typeof value !== "boolean" && typeof value !== "string" && typeof value !== "number") { + throw new Error(`${msg(propLoc)} must be null, undefined, a boolean, a string, or a number.`); + } + } + } + return value; +} +function assertInputSourceMap(loc, value) { + if (value !== undefined && typeof value !== "boolean" && (typeof value !== "object" || !value)) { + throw new Error(`${msg(loc)} must be a boolean, object, or undefined`); + } + return value; +} +function assertString(loc, value) { + if (value !== undefined && typeof value !== "string") { + throw new Error(`${msg(loc)} must be a string, or undefined`); + } + return value; +} +function assertFunction(loc, value) { + if (value !== undefined && typeof value !== "function") { + throw new Error(`${msg(loc)} must be a function, or undefined`); + } + return value; +} +function assertBoolean(loc, value) { + if (value !== undefined && typeof value !== "boolean") { + throw new Error(`${msg(loc)} must be a boolean, or undefined`); + } + return value; +} +function assertObject(loc, value) { + if (value !== undefined && (typeof value !== "object" || Array.isArray(value) || !value)) { + throw new Error(`${msg(loc)} must be an object, or undefined`); + } + return value; +} +function assertArray(loc, value) { + if (value != null && !Array.isArray(value)) { + throw new Error(`${msg(loc)} must be an array, or undefined`); + } + return value; +} +function assertIgnoreList(loc, value) { + const arr = assertArray(loc, value); + arr == null || arr.forEach((item, i) => assertIgnoreItem(access(loc, i), item)); + return arr; +} +function assertIgnoreItem(loc, value) { + if (typeof value !== "string" && typeof value !== "function" && !(value instanceof RegExp)) { + throw new Error(`${msg(loc)} must be an array of string/Function/RegExp values, or undefined`); + } + return value; +} +function assertConfigApplicableTest(loc, value) { + if (value === undefined) { + return value; + } + if (Array.isArray(value)) { + value.forEach((item, i) => { + if (!checkValidTest(item)) { + throw new Error(`${msg(access(loc, i))} must be a string/Function/RegExp.`); + } + }); + } else if (!checkValidTest(value)) { + throw new Error(`${msg(loc)} must be a string/Function/RegExp, or an array of those`); + } + return value; +} +function checkValidTest(value) { + return typeof value === "string" || typeof value === "function" || value instanceof RegExp; +} +function assertConfigFileSearch(loc, value) { + if (value !== undefined && typeof value !== "boolean" && typeof value !== "string") { + throw new Error(`${msg(loc)} must be a undefined, a boolean, a string, ` + `got ${JSON.stringify(value)}`); + } + return value; +} +function assertBabelrcSearch(loc, value) { + if (value === undefined || typeof value === "boolean") { + return value; + } + if (Array.isArray(value)) { + value.forEach((item, i) => { + if (!checkValidTest(item)) { + throw new Error(`${msg(access(loc, i))} must be a string/Function/RegExp.`); + } + }); + } else if (!checkValidTest(value)) { + throw new Error(`${msg(loc)} must be a undefined, a boolean, a string/Function/RegExp ` + `or an array of those, got ${JSON.stringify(value)}`); + } + return value; +} +function assertPluginList(loc, value) { + const arr = assertArray(loc, value); + if (arr) { + arr.forEach((item, i) => assertPluginItem(access(loc, i), item)); + } + return arr; +} +function assertPluginItem(loc, value) { + if (Array.isArray(value)) { + if (value.length === 0) { + throw new Error(`${msg(loc)} must include an object`); + } + if (value.length > 3) { + throw new Error(`${msg(loc)} may only be a two-tuple or three-tuple`); + } + assertPluginTarget(access(loc, 0), value[0]); + if (value.length > 1) { + const opts = value[1]; + if (opts !== undefined && opts !== false && (typeof opts !== "object" || Array.isArray(opts) || opts === null)) { + throw new Error(`${msg(access(loc, 1))} must be an object, false, or undefined`); + } + } + if (value.length === 3) { + const name = value[2]; + if (name !== undefined && typeof name !== "string") { + throw new Error(`${msg(access(loc, 2))} must be a string, or undefined`); + } + } + } else { + assertPluginTarget(loc, value); + } + return value; +} +function assertPluginTarget(loc, value) { + if ((typeof value !== "object" || !value) && typeof value !== "string" && typeof value !== "function") { + throw new Error(`${msg(loc)} must be a string, object, function`); + } + return value; +} +function assertTargets(loc, value) { + if ((0, _helperCompilationTargets().isBrowsersQueryValid)(value)) return value; + if (typeof value !== "object" || !value || Array.isArray(value)) { + throw new Error(`${msg(loc)} must be a string, an array of strings or an object`); + } + const browsersLoc = access(loc, "browsers"); + const esmodulesLoc = access(loc, "esmodules"); + assertBrowsersList(browsersLoc, value.browsers); + assertBoolean(esmodulesLoc, value.esmodules); + for (const key of Object.keys(value)) { + const val = value[key]; + const subLoc = access(loc, key); + if (key === "esmodules") assertBoolean(subLoc, val);else if (key === "browsers") assertBrowsersList(subLoc, val);else if (!hasOwnProperty.call(_helperCompilationTargets().TargetNames, key)) { + const validTargets = Object.keys(_helperCompilationTargets().TargetNames).join(", "); + throw new Error(`${msg(subLoc)} is not a valid target. Supported targets are ${validTargets}`); + } else assertBrowserVersion(subLoc, val); + } + return value; +} +function assertBrowsersList(loc, value) { + if (value !== undefined && !(0, _helperCompilationTargets().isBrowsersQueryValid)(value)) { + throw new Error(`${msg(loc)} must be undefined, a string or an array of strings`); + } +} +function assertBrowserVersion(loc, value) { + if (typeof value === "number" && Math.round(value) === value) return; + if (typeof value === "string") return; + throw new Error(`${msg(loc)} must be a string or an integer number`); +} +function assertAssumptions(loc, value) { + if (value === undefined) return; + if (typeof value !== "object" || value === null) { + throw new Error(`${msg(loc)} must be an object or undefined.`); + } + let root = loc; + do { + root = root.parent; + } while (root.type !== "root"); + const inPreset = root.source === "preset"; + for (const name of Object.keys(value)) { + const subLoc = access(loc, name); + if (!_options.assumptionsNames.has(name)) { + throw new Error(`${msg(subLoc)} is not a supported assumption.`); + } + if (typeof value[name] !== "boolean") { + throw new Error(`${msg(subLoc)} must be a boolean.`); + } + if (inPreset && value[name] === false) { + throw new Error(`${msg(subLoc)} cannot be set to 'false' inside presets.`); + } + } + return value; +} +0 && 0; + +//# sourceMappingURL=option-assertions.js.map diff --git a/node_modules/@babel/core/lib/config/validation/option-assertions.js.map b/node_modules/@babel/core/lib/config/validation/option-assertions.js.map new file mode 100644 index 0000000..f68e0d3 --- /dev/null +++ b/node_modules/@babel/core/lib/config/validation/option-assertions.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_helperCompilationTargets","data","require","_options","msg","loc","type","parent","name","index","JSON","stringify","Error","access","assertRootMode","value","undefined","assertSourceMaps","assertCompact","assertSourceType","assertCallerMetadata","obj","assertObject","prop","Object","keys","propLoc","assertInputSourceMap","assertString","assertFunction","assertBoolean","Array","isArray","assertArray","assertIgnoreList","arr","forEach","item","i","assertIgnoreItem","RegExp","assertConfigApplicableTest","checkValidTest","assertConfigFileSearch","assertBabelrcSearch","assertPluginList","assertPluginItem","length","assertPluginTarget","opts","assertTargets","isBrowsersQueryValid","browsersLoc","esmodulesLoc","assertBrowsersList","browsers","esmodules","key","val","subLoc","hasOwnProperty","call","TargetNames","validTargets","join","assertBrowserVersion","Math","round","assertAssumptions","root","inPreset","source","assumptionsNames","has"],"sources":["../../../src/config/validation/option-assertions.ts"],"sourcesContent":["import {\n isBrowsersQueryValid,\n TargetNames,\n} from \"@babel/helper-compilation-targets\";\n\nimport type {\n ConfigFileSearch,\n BabelrcSearch,\n IgnoreList,\n IgnoreItem,\n PluginList,\n PluginItem,\n PluginTarget,\n ConfigApplicableTest,\n SourceMapsOption,\n SourceTypeOption,\n CompactOption,\n RootInputSourceMapOption,\n NestingPath,\n CallerMetadata,\n RootMode,\n TargetsListOrObject,\n AssumptionName,\n} from \"./options.ts\";\n\nimport { assumptionsNames } from \"./options.ts\";\n\nexport type { RootPath } from \"./options.ts\";\n\nexport type ValidatorSet = {\n [name: string]: Validator;\n};\n\nexport type Validator = (loc: OptionPath, value: unknown) => T;\n\nexport function msg(loc: NestingPath | GeneralPath): string {\n switch (loc.type) {\n case \"root\":\n return ``;\n case \"env\":\n return `${msg(loc.parent)}.env[\"${loc.name}\"]`;\n case \"overrides\":\n return `${msg(loc.parent)}.overrides[${loc.index}]`;\n case \"option\":\n return `${msg(loc.parent)}.${loc.name}`;\n case \"access\":\n return `${msg(loc.parent)}[${JSON.stringify(loc.name)}]`;\n default:\n // @ts-expect-error should not happen when code is type checked\n throw new Error(`Assertion failure: Unknown type ${loc.type}`);\n }\n}\n\nexport function access(loc: GeneralPath, name: string | number): AccessPath {\n return {\n type: \"access\",\n name,\n parent: loc,\n };\n}\n\nexport type OptionPath = Readonly<{\n type: \"option\";\n name: string;\n parent: NestingPath;\n}>;\ntype AccessPath = Readonly<{\n type: \"access\";\n name: string | number;\n parent: GeneralPath;\n}>;\ntype GeneralPath = OptionPath | AccessPath;\n\nexport function assertRootMode(\n loc: OptionPath,\n value: unknown,\n): RootMode | void {\n if (\n value !== undefined &&\n value !== \"root\" &&\n value !== \"upward\" &&\n value !== \"upward-optional\"\n ) {\n throw new Error(\n `${msg(loc)} must be a \"root\", \"upward\", \"upward-optional\" or undefined`,\n );\n }\n // @ts-expect-error: TS can only narrow down the type when \"strictNullCheck\" is true\n return value;\n}\n\nexport function assertSourceMaps(\n loc: OptionPath,\n value: unknown,\n): SourceMapsOption | void {\n if (\n value !== undefined &&\n typeof value !== \"boolean\" &&\n value !== \"inline\" &&\n value !== \"both\"\n ) {\n throw new Error(\n `${msg(loc)} must be a boolean, \"inline\", \"both\", or undefined`,\n );\n }\n // @ts-expect-error: TS can only narrow down the type when \"strictNullCheck\" is true\n return value;\n}\n\nexport function assertCompact(\n loc: OptionPath,\n value: unknown,\n): CompactOption | void {\n if (value !== undefined && typeof value !== \"boolean\" && value !== \"auto\") {\n throw new Error(`${msg(loc)} must be a boolean, \"auto\", or undefined`);\n }\n // @ts-expect-error: TS can only narrow down the type when \"strictNullCheck\" is true\n return value;\n}\n\nexport function assertSourceType(\n loc: OptionPath,\n value: unknown,\n): SourceTypeOption | void {\n if (\n value !== undefined &&\n value !== \"module\" &&\n value !== \"script\" &&\n value !== \"unambiguous\"\n ) {\n throw new Error(\n `${msg(loc)} must be \"module\", \"script\", \"unambiguous\", or undefined`,\n );\n }\n // @ts-expect-error: TS can only narrow down the type when \"strictNullCheck\" is true\n return value;\n}\n\nexport function assertCallerMetadata(\n loc: OptionPath,\n value: unknown,\n): CallerMetadata | undefined {\n const obj = assertObject(loc, value);\n if (obj) {\n if (typeof obj.name !== \"string\") {\n throw new Error(\n `${msg(loc)} set but does not contain \"name\" property string`,\n );\n }\n\n for (const prop of Object.keys(obj)) {\n const propLoc = access(loc, prop);\n const value = obj[prop];\n if (\n value != null &&\n typeof value !== \"boolean\" &&\n typeof value !== \"string\" &&\n typeof value !== \"number\"\n ) {\n // NOTE(logan): I'm limiting the type here so that we can guarantee that\n // the \"caller\" value will serialize to JSON nicely. We can always\n // allow more complex structures later though.\n throw new Error(\n `${msg(\n propLoc,\n )} must be null, undefined, a boolean, a string, or a number.`,\n );\n }\n }\n }\n // @ts-expect-error todo(flow->ts)\n return value;\n}\n\nexport function assertInputSourceMap(\n loc: OptionPath,\n value: unknown,\n): RootInputSourceMapOption {\n if (\n value !== undefined &&\n typeof value !== \"boolean\" &&\n (typeof value !== \"object\" || !value)\n ) {\n throw new Error(`${msg(loc)} must be a boolean, object, or undefined`);\n }\n return value as RootInputSourceMapOption;\n}\n\nexport function assertString(loc: GeneralPath, value: unknown): string | void {\n if (value !== undefined && typeof value !== \"string\") {\n throw new Error(`${msg(loc)} must be a string, or undefined`);\n }\n // @ts-expect-error: TS can only narrow down the type when \"strictNullCheck\" is true\n return value;\n}\n\nexport function assertFunction(\n loc: GeneralPath,\n value: unknown,\n): Function | void {\n if (value !== undefined && typeof value !== \"function\") {\n throw new Error(`${msg(loc)} must be a function, or undefined`);\n }\n // @ts-expect-error: TS can only narrow down the type when \"strictNullCheck\" is true\n return value;\n}\n\nexport function assertBoolean(\n loc: GeneralPath,\n value: unknown,\n): boolean | void {\n if (value !== undefined && typeof value !== \"boolean\") {\n throw new Error(`${msg(loc)} must be a boolean, or undefined`);\n }\n // @ts-expect-error: TS can only narrow down the type when \"strictNullCheck\" is true\n return value;\n}\n\nexport function assertObject(\n loc: GeneralPath,\n value: unknown,\n): { readonly [key: string]: unknown } | void {\n if (\n value !== undefined &&\n (typeof value !== \"object\" || Array.isArray(value) || !value)\n ) {\n throw new Error(`${msg(loc)} must be an object, or undefined`);\n }\n // @ts-expect-error todo(flow->ts) value is still typed as unknown, also assert function typically should not return a value\n return value;\n}\n\nexport function assertArray(\n loc: GeneralPath,\n value: Array | undefined | null,\n): ReadonlyArray | undefined | null {\n if (value != null && !Array.isArray(value)) {\n throw new Error(`${msg(loc)} must be an array, or undefined`);\n }\n return value;\n}\n\nexport function assertIgnoreList(\n loc: OptionPath,\n value: unknown[] | undefined,\n): IgnoreList | void {\n const arr = assertArray(loc, value);\n arr?.forEach((item, i) => assertIgnoreItem(access(loc, i), item));\n // @ts-expect-error todo(flow->ts)\n return arr;\n}\nfunction assertIgnoreItem(loc: GeneralPath, value: unknown): IgnoreItem {\n if (\n typeof value !== \"string\" &&\n typeof value !== \"function\" &&\n !(value instanceof RegExp)\n ) {\n throw new Error(\n `${msg(\n loc,\n )} must be an array of string/Function/RegExp values, or undefined`,\n );\n }\n return value as IgnoreItem;\n}\n\nexport function assertConfigApplicableTest(\n loc: OptionPath,\n value: unknown,\n): ConfigApplicableTest | void {\n if (value === undefined) {\n // @ts-expect-error: TS can only narrow down the type when \"strictNullCheck\" is true\n return value;\n }\n\n if (Array.isArray(value)) {\n value.forEach((item, i) => {\n if (!checkValidTest(item)) {\n throw new Error(\n `${msg(access(loc, i))} must be a string/Function/RegExp.`,\n );\n }\n });\n } else if (!checkValidTest(value)) {\n throw new Error(\n `${msg(loc)} must be a string/Function/RegExp, or an array of those`,\n );\n }\n return value as ConfigApplicableTest;\n}\n\nfunction checkValidTest(value: unknown): value is string | Function | RegExp {\n return (\n typeof value === \"string\" ||\n typeof value === \"function\" ||\n value instanceof RegExp\n );\n}\n\nexport function assertConfigFileSearch(\n loc: OptionPath,\n value: unknown,\n): ConfigFileSearch | void {\n if (\n value !== undefined &&\n typeof value !== \"boolean\" &&\n typeof value !== \"string\"\n ) {\n throw new Error(\n `${msg(loc)} must be a undefined, a boolean, a string, ` +\n `got ${JSON.stringify(value)}`,\n );\n }\n // @ts-expect-error: TS can only narrow down the type when \"strictNullCheck\" is true\n return value;\n}\n\nexport function assertBabelrcSearch(\n loc: OptionPath,\n value: unknown,\n): BabelrcSearch | void {\n if (value === undefined || typeof value === \"boolean\") {\n // @ts-expect-error: TS can only narrow down the type when \"strictNullCheck\" is true\n return value;\n }\n\n if (Array.isArray(value)) {\n value.forEach((item, i) => {\n if (!checkValidTest(item)) {\n throw new Error(\n `${msg(access(loc, i))} must be a string/Function/RegExp.`,\n );\n }\n });\n } else if (!checkValidTest(value)) {\n throw new Error(\n `${msg(loc)} must be a undefined, a boolean, a string/Function/RegExp ` +\n `or an array of those, got ${JSON.stringify(value as any)}`,\n );\n }\n return value as BabelrcSearch;\n}\n\nexport function assertPluginList(\n loc: OptionPath,\n value: unknown[] | null | undefined,\n): PluginList | void {\n const arr = assertArray(loc, value);\n if (arr) {\n // Loop instead of using `.map` in order to preserve object identity\n // for plugin array for use during config chain processing.\n arr.forEach((item, i) => assertPluginItem(access(loc, i), item));\n }\n return arr as any;\n}\nfunction assertPluginItem(loc: GeneralPath, value: unknown): PluginItem {\n if (Array.isArray(value)) {\n if (value.length === 0) {\n throw new Error(`${msg(loc)} must include an object`);\n }\n\n if (value.length > 3) {\n throw new Error(`${msg(loc)} may only be a two-tuple or three-tuple`);\n }\n\n assertPluginTarget(access(loc, 0), value[0]);\n\n if (value.length > 1) {\n const opts = value[1];\n if (\n opts !== undefined &&\n opts !== false &&\n (typeof opts !== \"object\" || Array.isArray(opts) || opts === null)\n ) {\n throw new Error(\n `${msg(access(loc, 1))} must be an object, false, or undefined`,\n );\n }\n }\n if (value.length === 3) {\n const name = value[2];\n if (name !== undefined && typeof name !== \"string\") {\n throw new Error(\n `${msg(access(loc, 2))} must be a string, or undefined`,\n );\n }\n }\n } else {\n assertPluginTarget(loc, value);\n }\n\n // @ts-expect-error todo(flow->ts)\n return value;\n}\nfunction assertPluginTarget(loc: GeneralPath, value: unknown): PluginTarget {\n if (\n (typeof value !== \"object\" || !value) &&\n typeof value !== \"string\" &&\n typeof value !== \"function\"\n ) {\n throw new Error(`${msg(loc)} must be a string, object, function`);\n }\n return value;\n}\n\nexport function assertTargets(\n loc: GeneralPath,\n value: any,\n): TargetsListOrObject {\n if (isBrowsersQueryValid(value)) return value;\n\n if (typeof value !== \"object\" || !value || Array.isArray(value)) {\n throw new Error(\n `${msg(loc)} must be a string, an array of strings or an object`,\n );\n }\n\n const browsersLoc = access(loc, \"browsers\");\n const esmodulesLoc = access(loc, \"esmodules\");\n\n assertBrowsersList(browsersLoc, value.browsers);\n assertBoolean(esmodulesLoc, value.esmodules);\n\n for (const key of Object.keys(value)) {\n const val = value[key];\n const subLoc = access(loc, key);\n\n if (key === \"esmodules\") assertBoolean(subLoc, val);\n else if (key === \"browsers\") assertBrowsersList(subLoc, val);\n else if (!Object.hasOwn(TargetNames, key)) {\n const validTargets = Object.keys(TargetNames).join(\", \");\n throw new Error(\n `${msg(\n subLoc,\n )} is not a valid target. Supported targets are ${validTargets}`,\n );\n } else assertBrowserVersion(subLoc, val);\n }\n\n return value;\n}\n\nfunction assertBrowsersList(loc: GeneralPath, value: unknown) {\n if (value !== undefined && !isBrowsersQueryValid(value)) {\n throw new Error(\n `${msg(loc)} must be undefined, a string or an array of strings`,\n );\n }\n}\n\nfunction assertBrowserVersion(loc: GeneralPath, value: unknown) {\n if (typeof value === \"number\" && Math.round(value) === value) return;\n if (typeof value === \"string\") return;\n\n throw new Error(`${msg(loc)} must be a string or an integer number`);\n}\n\nexport function assertAssumptions(\n loc: GeneralPath,\n value: { [key: string]: unknown },\n): { [name: string]: boolean } | void {\n if (value === undefined) return;\n\n if (typeof value !== \"object\" || value === null) {\n throw new Error(`${msg(loc)} must be an object or undefined.`);\n }\n\n // todo(flow->ts): remove any\n let root: any = loc;\n do {\n root = root.parent;\n } while (root.type !== \"root\");\n const inPreset = root.source === \"preset\";\n\n for (const name of Object.keys(value)) {\n const subLoc = access(loc, name);\n if (!assumptionsNames.has(name as AssumptionName)) {\n throw new Error(`${msg(subLoc)} is not a supported assumption.`);\n }\n if (typeof value[name] !== \"boolean\") {\n throw new Error(`${msg(subLoc)} must be a boolean.`);\n }\n if (inPreset && value[name] === false) {\n throw new Error(\n `${msg(subLoc)} cannot be set to 'false' inside presets.`,\n );\n }\n }\n\n // @ts-expect-error todo(flow->ts)\n return value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAAA,0BAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,yBAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAyBA,IAAAE,QAAA,GAAAD,OAAA;AAUO,SAASE,GAAGA,CAACC,GAA8B,EAAU;EAC1D,QAAQA,GAAG,CAACC,IAAI;IACd,KAAK,MAAM;MACT,OAAO,EAAE;I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el/core/lib/config/validation/options.js b/node_modules/@babel/core/lib/config/validation/options.js new file mode 100644 index 0000000..3b78ada --- /dev/null +++ b/node_modules/@babel/core/lib/config/validation/options.js @@ -0,0 +1,189 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.assumptionsNames = void 0; +exports.checkNoUnwrappedItemOptionPairs = checkNoUnwrappedItemOptionPairs; +exports.validate = validate; +var _removed = require("./removed.js"); +var _optionAssertions = require("./option-assertions.js"); +var _configError = require("../../errors/config-error.js"); +const ROOT_VALIDATORS = { + cwd: _optionAssertions.assertString, + root: _optionAssertions.assertString, + rootMode: _optionAssertions.assertRootMode, + configFile: _optionAssertions.assertConfigFileSearch, + caller: _optionAssertions.assertCallerMetadata, + filename: _optionAssertions.assertString, + filenameRelative: _optionAssertions.assertString, + code: _optionAssertions.assertBoolean, + ast: _optionAssertions.assertBoolean, + cloneInputAst: _optionAssertions.assertBoolean, + envName: _optionAssertions.assertString +}; +const BABELRC_VALIDATORS = { + babelrc: _optionAssertions.assertBoolean, + babelrcRoots: _optionAssertions.assertBabelrcSearch +}; +const NONPRESET_VALIDATORS = { + extends: _optionAssertions.assertString, + ignore: _optionAssertions.assertIgnoreList, + only: _optionAssertions.assertIgnoreList, + targets: _optionAssertions.assertTargets, + browserslistConfigFile: _optionAssertions.assertConfigFileSearch, + browserslistEnv: _optionAssertions.assertString +}; +const COMMON_VALIDATORS = { + inputSourceMap: _optionAssertions.assertInputSourceMap, + presets: _optionAssertions.assertPluginList, + plugins: _optionAssertions.assertPluginList, + passPerPreset: _optionAssertions.assertBoolean, + assumptions: _optionAssertions.assertAssumptions, + env: assertEnvSet, + overrides: assertOverridesList, + test: _optionAssertions.assertConfigApplicableTest, + include: _optionAssertions.assertConfigApplicableTest, + exclude: _optionAssertions.assertConfigApplicableTest, + retainLines: _optionAssertions.assertBoolean, + comments: _optionAssertions.assertBoolean, + shouldPrintComment: _optionAssertions.assertFunction, + compact: _optionAssertions.assertCompact, + minified: _optionAssertions.assertBoolean, + auxiliaryCommentBefore: _optionAssertions.assertString, + auxiliaryCommentAfter: _optionAssertions.assertString, + sourceType: _optionAssertions.assertSourceType, + wrapPluginVisitorMethod: _optionAssertions.assertFunction, + highlightCode: _optionAssertions.assertBoolean, + sourceMaps: _optionAssertions.assertSourceMaps, + sourceMap: _optionAssertions.assertSourceMaps, + sourceFileName: _optionAssertions.assertString, + sourceRoot: _optionAssertions.assertString, + parserOpts: _optionAssertions.assertObject, + generatorOpts: _optionAssertions.assertObject +}; +{ + Object.assign(COMMON_VALIDATORS, { + getModuleId: _optionAssertions.assertFunction, + moduleRoot: _optionAssertions.assertString, + moduleIds: _optionAssertions.assertBoolean, + moduleId: _optionAssertions.assertString + }); +} +const knownAssumptions = ["arrayLikeIsIterable", "constantReexports", "constantSuper", "enumerableModuleMeta", "ignoreFunctionLength", "ignoreToPrimitiveHint", "iterableIsArray", "mutableTemplateObject", "noClassCalls", "noDocumentAll", "noIncompleteNsImportDetection", "noNewArrows", "noUninitializedPrivateFieldAccess", "objectRestNoSymbols", "privateFieldsAsSymbols", "privateFieldsAsProperties", "pureGetters", "setClassMethods", "setComputedProperties", "setPublicClassFields", "setSpreadProperties", "skipForOfIteratorClosing", "superIsCallableConstructor"]; +const assumptionsNames = exports.assumptionsNames = new Set(knownAssumptions); +function getSource(loc) { + return loc.type === "root" ? loc.source : getSource(loc.parent); +} +function validate(type, opts, filename) { + try { + return validateNested({ + type: "root", + source: type + }, opts); + } catch (error) { + const configError = new _configError.default(error.message, filename); + if (error.code) configError.code = error.code; + throw configError; + } +} +function validateNested(loc, opts) { + const type = getSource(loc); + assertNoDuplicateSourcemap(opts); + Object.keys(opts).forEach(key => { + const optLoc = { + type: "option", + name: key, + parent: loc + }; + if (type === "preset" && NONPRESET_VALIDATORS[key]) { + throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is not allowed in preset options`); + } + if (type !== "arguments" && ROOT_VALIDATORS[key]) { + throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is only allowed in root programmatic options`); + } + if (type !== "arguments" && type !== "configfile" && BABELRC_VALIDATORS[key]) { + if (type === "babelrcfile" || type === "extendsfile") { + throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is not allowed in .babelrc or "extends"ed files, only in root programmatic options, ` + `or babel.config.js/config file options`); + } + throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is only allowed in root programmatic options, or babel.config.js/config file options`); + } + const validator = COMMON_VALIDATORS[key] || NONPRESET_VALIDATORS[key] || BABELRC_VALIDATORS[key] || ROOT_VALIDATORS[key] || throwUnknownError; + validator(optLoc, opts[key]); + }); + return opts; +} +function throwUnknownError(loc) { + const key = loc.name; + if (_removed.default[key]) { + const { + message, + version = 5 + } = _removed.default[key]; + throw new Error(`Using removed Babel ${version} option: ${(0, _optionAssertions.msg)(loc)} - ${message}`); + } else { + const unknownOptErr = new Error(`Unknown option: ${(0, _optionAssertions.msg)(loc)}. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.`); + unknownOptErr.code = "BABEL_UNKNOWN_OPTION"; + throw unknownOptErr; + } +} +function assertNoDuplicateSourcemap(opts) { + if (hasOwnProperty.call(opts, "sourceMap") && hasOwnProperty.call(opts, "sourceMaps")) { + throw new Error(".sourceMap is an alias for .sourceMaps, cannot use both"); + } +} +function assertEnvSet(loc, value) { + if (loc.parent.type === "env") { + throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside of another .env block`); + } + const parent = loc.parent; + const obj = (0, _optionAssertions.assertObject)(loc, value); + if (obj) { + for (const envName of Object.keys(obj)) { + const env = (0, _optionAssertions.assertObject)((0, _optionAssertions.access)(loc, envName), obj[envName]); + if (!env) continue; + const envLoc = { + type: "env", + name: envName, + parent + }; + validateNested(envLoc, env); + } + } + return obj; +} +function assertOverridesList(loc, value) { + if (loc.parent.type === "env") { + throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside an .env block`); + } + if (loc.parent.type === "overrides") { + throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside an .overrides block`); + } + const parent = loc.parent; + const arr = (0, _optionAssertions.assertArray)(loc, value); + if (arr) { + for (const [index, item] of arr.entries()) { + const objLoc = (0, _optionAssertions.access)(loc, index); + const env = (0, _optionAssertions.assertObject)(objLoc, item); + if (!env) throw new Error(`${(0, _optionAssertions.msg)(objLoc)} must be an object`); + const overridesLoc = { + type: "overrides", + index, + parent + }; + validateNested(overridesLoc, env); + } + } + return arr; +} +function checkNoUnwrappedItemOptionPairs(items, index, type, e) { + if (index === 0) return; + const lastItem = items[index - 1]; + const thisItem = items[index]; + if (lastItem.file && lastItem.options === undefined && typeof thisItem.value === "object") { + e.message += `\n- Maybe you meant to use\n` + `"${type}s": [\n ["${lastItem.file.request}", ${JSON.stringify(thisItem.value, undefined, 2)}]\n]\n` + `To be a valid ${type}, its name and options should be wrapped in a pair of brackets`; + } +} +0 && 0; + +//# sourceMappingURL=options.js.map diff --git a/node_modules/@babel/core/lib/config/validation/options.js.map b/node_modules/@babel/core/lib/config/validation/options.js.map new file mode 100644 index 0000000..7ad2016 --- /dev/null +++ b/node_modules/@babel/core/lib/config/validation/options.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_removed","require","_optionAssertions","_configError","ROOT_VALIDATORS","cwd","assertString","root","rootMode","assertRootMode","configFile","assertConfigFileSearch","caller","assertCallerMetadata","filename","filenameRelative","code","assertBoolean","ast","cloneInputAst","envName","BABELRC_VALIDATORS","babelrc","babelrcRoots","assertBabelrcSearch","NONPRESET_VALIDATORS","extends","ignore","assertIgnoreList","only","targets","assertTargets","browserslistConfigFile","browserslistEnv","COMMON_VALIDATORS","inputSourceMap","assertInputSourceMap","presets","assertPluginList","plugins","passPerPreset","assumptions","assertAssumptions","env","assertEnvSet","overrides","assertOverridesList","test","assertConfigApplicableTest","include","exclude","retainLines","comments","shouldPrintComment","assertFunction","compact","assertCompact","minified","auxiliaryCommentBefore","auxiliaryCommentAfter","sourceType","assertSourceType","wrapPluginVisitorMethod","highlightCode","sourceMaps","assertSourceMaps","sourceMap","sourceFileName","sourceRoot","parserOpts","assertObject","generatorOpts","Object","assign","getModuleId","moduleRoot","moduleIds","moduleId","knownAssumptions","assumptionsNames","exports","Set","getSource","loc","type","source","parent","validate","opts","validateNested","error","configError","ConfigError","message","assertNoDuplicateSourcemap","keys","forEach","key","optLoc","name","Error","msg","validator","throwUnknownError","removed","version","unknownOptErr","hasOwnProperty","call","value","obj","access","envLoc","arr","assertArray","index","item","entries","objLoc","overridesLoc","checkNoUnwrappedItemOptionPairs","items","e","lastItem","thisItem","file","options","undefined","request","JSON","stringify"],"sources":["../../../src/config/validation/options.ts"],"sourcesContent":["import type { InputTargets, Targets } from \"@babel/helper-compilation-targets\";\n\nimport type { ConfigItem } from \"../item.ts\";\nimport type Plugin from \"../plugin.ts\";\n\nimport removed from \"./removed.ts\";\nimport {\n msg,\n access,\n assertString,\n assertBoolean,\n assertObject,\n assertArray,\n assertCallerMetadata,\n assertInputSourceMap,\n assertIgnoreList,\n assertPluginList,\n assertConfigApplicableTest,\n assertConfigFileSearch,\n assertBabelrcSearch,\n assertFunction,\n assertRootMode,\n assertSourceMaps,\n assertCompact,\n assertSourceType,\n assertTargets,\n assertAssumptions,\n} from \"./option-assertions.ts\";\nimport type {\n ValidatorSet,\n Validator,\n OptionPath,\n} from \"./option-assertions.ts\";\nimport type { UnloadedDescriptor } from \"../config-descriptors.ts\";\nimport type { PluginAPI } from \"../helpers/config-api.ts\";\nimport type { ParserOptions } from \"@babel/parser\";\nimport type { GeneratorOptions } from \"@babel/generator\";\nimport ConfigError from \"../../errors/config-error.ts\";\n\nconst ROOT_VALIDATORS: ValidatorSet = {\n cwd: assertString as Validator,\n root: assertString as Validator,\n rootMode: assertRootMode as Validator,\n configFile: assertConfigFileSearch as Validator<\n ValidatedOptions[\"configFile\"]\n >,\n\n caller: assertCallerMetadata as Validator,\n filename: assertString as Validator,\n filenameRelative: assertString as Validator<\n ValidatedOptions[\"filenameRelative\"]\n >,\n code: assertBoolean as Validator,\n ast: assertBoolean as Validator,\n\n cloneInputAst: assertBoolean as Validator,\n\n envName: assertString as Validator,\n};\n\nconst BABELRC_VALIDATORS: ValidatorSet = {\n babelrc: assertBoolean as Validator,\n babelrcRoots: assertBabelrcSearch as Validator<\n ValidatedOptions[\"babelrcRoots\"]\n >,\n};\n\nconst NONPRESET_VALIDATORS: ValidatorSet = {\n extends: assertString as Validator,\n ignore: assertIgnoreList as Validator,\n only: assertIgnoreList as Validator,\n\n targets: assertTargets as Validator,\n browserslistConfigFile: assertConfigFileSearch as Validator<\n ValidatedOptions[\"browserslistConfigFile\"]\n >,\n browserslistEnv: assertString as Validator<\n ValidatedOptions[\"browserslistEnv\"]\n >,\n};\n\nconst COMMON_VALIDATORS: ValidatorSet = {\n // TODO: Should 'inputSourceMap' be moved to be a root-only option?\n // We may want a boolean-only version to be a common option, with the\n // object only allowed as a root config argument.\n inputSourceMap: assertInputSourceMap as Validator<\n ValidatedOptions[\"inputSourceMap\"]\n >,\n presets: assertPluginList as Validator,\n plugins: assertPluginList as Validator,\n passPerPreset: assertBoolean as Validator,\n assumptions: assertAssumptions as Validator,\n\n env: assertEnvSet as Validator,\n overrides: assertOverridesList as Validator,\n\n // We could limit these to 'overrides' blocks, but it's not clear why we'd\n // bother, when the ability to limit a config to a specific set of files\n // is a fairly general useful feature.\n test: assertConfigApplicableTest as Validator,\n include: assertConfigApplicableTest as Validator,\n exclude: assertConfigApplicableTest as Validator,\n\n retainLines: assertBoolean as Validator,\n comments: assertBoolean as Validator,\n shouldPrintComment: assertFunction as Validator<\n ValidatedOptions[\"shouldPrintComment\"]\n >,\n compact: assertCompact as Validator,\n minified: assertBoolean as Validator,\n auxiliaryCommentBefore: assertString as Validator<\n ValidatedOptions[\"auxiliaryCommentBefore\"]\n >,\n auxiliaryCommentAfter: assertString as Validator<\n ValidatedOptions[\"auxiliaryCommentAfter\"]\n >,\n sourceType: assertSourceType as Validator,\n wrapPluginVisitorMethod: assertFunction as Validator<\n ValidatedOptions[\"wrapPluginVisitorMethod\"]\n >,\n highlightCode: assertBoolean as Validator,\n sourceMaps: assertSourceMaps as Validator,\n sourceMap: assertSourceMaps as Validator,\n sourceFileName: assertString as Validator,\n sourceRoot: assertString as Validator,\n parserOpts: assertObject as Validator,\n generatorOpts: assertObject as Validator,\n};\nif (!process.env.BABEL_8_BREAKING) {\n Object.assign(COMMON_VALIDATORS, {\n getModuleId: assertFunction,\n moduleRoot: assertString,\n moduleIds: assertBoolean,\n moduleId: assertString,\n });\n}\n\nexport type InputOptions = ValidatedOptions;\n\nexport type ValidatedOptions = {\n cwd?: string;\n filename?: string;\n filenameRelative?: string;\n babelrc?: boolean;\n babelrcRoots?: BabelrcSearch;\n configFile?: ConfigFileSearch;\n root?: string;\n rootMode?: RootMode;\n code?: boolean;\n ast?: boolean;\n cloneInputAst?: boolean;\n inputSourceMap?: RootInputSourceMapOption;\n envName?: string;\n caller?: CallerMetadata;\n extends?: string;\n env?: EnvSet;\n ignore?: IgnoreList;\n only?: IgnoreList;\n overrides?: OverridesList;\n // Generally verify if a given config object should be applied to the given file.\n test?: ConfigApplicableTest;\n include?: ConfigApplicableTest;\n exclude?: ConfigApplicableTest;\n presets?: PluginList;\n plugins?: PluginList;\n passPerPreset?: boolean;\n assumptions?: {\n [name: string]: boolean;\n };\n // browserslists-related options\n targets?: TargetsListOrObject;\n browserslistConfigFile?: ConfigFileSearch;\n browserslistEnv?: string;\n // Options for @babel/generator\n retainLines?: boolean;\n comments?: boolean;\n shouldPrintComment?: Function;\n compact?: CompactOption;\n minified?: boolean;\n auxiliaryCommentBefore?: string;\n auxiliaryCommentAfter?: string;\n // Parser\n sourceType?: SourceTypeOption;\n wrapPluginVisitorMethod?: Function;\n highlightCode?: boolean;\n // Sourcemap generation options.\n sourceMaps?: SourceMapsOption;\n sourceMap?: SourceMapsOption;\n sourceFileName?: string;\n sourceRoot?: string;\n // Deprecate top level parserOpts\n parserOpts?: ParserOptions;\n // Deprecate top level generatorOpts\n generatorOpts?: GeneratorOptions;\n};\n\nexport type NormalizedOptions = {\n readonly targets: Targets;\n} & Omit;\n\nexport type CallerMetadata = {\n // If 'caller' is specified, require that the name is given for debugging\n // messages.\n name: string;\n};\nexport type EnvSet = {\n [x: string]: T;\n};\nexport type IgnoreItem =\n | string\n | RegExp\n | ((\n path: string | undefined,\n context: { dirname: string; caller: CallerMetadata; envName: string },\n ) => unknown);\nexport type IgnoreList = ReadonlyArray;\n\nexport type PluginOptions = object | void | false;\nexport type PluginTarget = string | object | Function;\nexport type PluginItem =\n | ConfigItem\n | Plugin\n | PluginTarget\n | [PluginTarget, PluginOptions]\n | [PluginTarget, PluginOptions, string | void];\nexport type PluginList = ReadonlyArray;\n\nexport type OverridesList = Array;\nexport type ConfigApplicableTest = IgnoreItem | Array;\n\nexport type ConfigFileSearch = string | boolean;\nexport type BabelrcSearch = boolean | IgnoreItem | IgnoreList;\nexport type SourceMapsOption = boolean | \"inline\" | \"both\";\nexport type SourceTypeOption = \"module\" | \"script\" | \"unambiguous\";\nexport type CompactOption = boolean | \"auto\";\nexport type RootInputSourceMapOption = object | boolean;\nexport type RootMode = \"root\" | \"upward\" | \"upward-optional\";\n\nexport type TargetsListOrObject =\n | Targets\n | InputTargets\n | InputTargets[\"browsers\"];\n\nexport type OptionsSource =\n | \"arguments\"\n | \"configfile\"\n | \"babelrcfile\"\n | \"extendsfile\"\n | \"preset\"\n | \"plugin\";\n\nexport type RootPath = Readonly<{\n type: \"root\";\n source: OptionsSource;\n}>;\n\ntype OverridesPath = Readonly<{\n type: \"overrides\";\n index: number;\n parent: RootPath;\n}>;\n\ntype EnvPath = Readonly<{\n type: \"env\";\n name: string;\n parent: RootPath | OverridesPath;\n}>;\n\nexport type NestingPath = RootPath | OverridesPath | EnvPath;\n\nconst knownAssumptions = [\n \"arrayLikeIsIterable\",\n \"constantReexports\",\n \"constantSuper\",\n \"enumerableModuleMeta\",\n \"ignoreFunctionLength\",\n \"ignoreToPrimitiveHint\",\n \"iterableIsArray\",\n \"mutableTemplateObject\",\n \"noClassCalls\",\n \"noDocumentAll\",\n \"noIncompleteNsImportDetection\",\n \"noNewArrows\",\n \"noUninitializedPrivateFieldAccess\",\n \"objectRestNoSymbols\",\n \"privateFieldsAsSymbols\",\n \"privateFieldsAsProperties\",\n \"pureGetters\",\n \"setClassMethods\",\n \"setComputedProperties\",\n \"setPublicClassFields\",\n \"setSpreadProperties\",\n \"skipForOfIteratorClosing\",\n \"superIsCallableConstructor\",\n] as const;\nexport type AssumptionName = (typeof knownAssumptions)[number];\nexport const assumptionsNames = new Set(knownAssumptions);\n\nfunction getSource(loc: NestingPath): OptionsSource {\n return loc.type === \"root\" ? loc.source : getSource(loc.parent);\n}\n\nexport function validate(\n type: OptionsSource,\n opts: any,\n filename?: string,\n): ValidatedOptions {\n try {\n return validateNested(\n {\n type: \"root\",\n source: type,\n },\n opts,\n );\n } catch (error) {\n const configError = new ConfigError(error.message, filename);\n // @ts-expect-error TODO: .code is not defined on ConfigError or Error\n if (error.code) configError.code = error.code;\n throw configError;\n }\n}\n\nfunction validateNested(loc: NestingPath, opts: { [key: string]: unknown }) {\n const type = getSource(loc);\n\n assertNoDuplicateSourcemap(opts);\n\n Object.keys(opts).forEach((key: string) => {\n const optLoc = {\n type: \"option\",\n name: key,\n parent: loc,\n } as const;\n\n if (type === \"preset\" && NONPRESET_VALIDATORS[key]) {\n throw new Error(`${msg(optLoc)} is not allowed in preset options`);\n }\n if (type !== \"arguments\" && ROOT_VALIDATORS[key]) {\n throw new Error(\n `${msg(optLoc)} is only allowed in root programmatic options`,\n );\n }\n if (\n type !== \"arguments\" &&\n type !== \"configfile\" &&\n BABELRC_VALIDATORS[key]\n ) {\n if (type === \"babelrcfile\" || type === \"extendsfile\") {\n throw new Error(\n `${msg(\n optLoc,\n )} is not allowed in .babelrc or \"extends\"ed files, only in root programmatic options, ` +\n `or babel.config.js/config file options`,\n );\n }\n\n throw new Error(\n `${msg(\n optLoc,\n )} is only allowed in root programmatic options, or babel.config.js/config file options`,\n );\n }\n\n const validator =\n COMMON_VALIDATORS[key] ||\n NONPRESET_VALIDATORS[key] ||\n BABELRC_VALIDATORS[key] ||\n ROOT_VALIDATORS[key] ||\n (throwUnknownError as Validator);\n\n validator(optLoc, opts[key]);\n });\n\n return opts;\n}\n\nfunction throwUnknownError(loc: OptionPath) {\n const key = loc.name;\n\n if (removed[key]) {\n const { message, version = 5 } = removed[key];\n\n throw new Error(\n `Using removed Babel ${version} option: ${msg(loc)} - ${message}`,\n );\n } else {\n const unknownOptErr = new Error(\n `Unknown option: ${msg(\n loc,\n )}. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.`,\n );\n // @ts-expect-error todo(flow->ts): consider creating something like BabelConfigError with code field in it\n unknownOptErr.code = \"BABEL_UNKNOWN_OPTION\";\n\n throw unknownOptErr;\n }\n}\n\nfunction assertNoDuplicateSourcemap(opts: any): void {\n if (Object.hasOwn(opts, \"sourceMap\") && Object.hasOwn(opts, \"sourceMaps\")) {\n throw new Error(\".sourceMap is an alias for .sourceMaps, cannot use both\");\n }\n}\n\nfunction assertEnvSet(\n loc: OptionPath,\n value: unknown,\n): void | EnvSet {\n if (loc.parent.type === \"env\") {\n throw new Error(`${msg(loc)} is not allowed inside of another .env block`);\n }\n const parent: RootPath | OverridesPath = loc.parent;\n\n const obj = assertObject(loc, value);\n if (obj) {\n // Validate but don't copy the .env object in order to preserve\n // object identity for use during config chain processing.\n for (const envName of Object.keys(obj)) {\n const env = assertObject(access(loc, envName), obj[envName]);\n if (!env) continue;\n\n const envLoc = {\n type: \"env\",\n name: envName,\n parent,\n } as const;\n validateNested(envLoc, env);\n }\n }\n return obj;\n}\n\nfunction assertOverridesList(\n loc: OptionPath,\n value: unknown[],\n): undefined | OverridesList {\n if (loc.parent.type === \"env\") {\n throw new Error(`${msg(loc)} is not allowed inside an .env block`);\n }\n if (loc.parent.type === \"overrides\") {\n throw new Error(`${msg(loc)} is not allowed inside an .overrides block`);\n }\n const parent: RootPath = loc.parent;\n\n const arr = assertArray(loc, value);\n if (arr) {\n for (const [index, item] of arr.entries()) {\n const objLoc = access(loc, index);\n const env = assertObject(objLoc, item);\n if (!env) throw new Error(`${msg(objLoc)} must be an object`);\n\n const overridesLoc = {\n type: \"overrides\",\n index,\n parent,\n } as const;\n validateNested(overridesLoc, env);\n }\n }\n return arr as OverridesList;\n}\n\nexport function checkNoUnwrappedItemOptionPairs(\n items: Array>,\n index: number,\n type: \"plugin\" | \"preset\",\n e: Error,\n): void {\n if (index === 0) return;\n\n const lastItem = items[index - 1];\n const thisItem = items[index];\n\n if (\n lastItem.file &&\n lastItem.options === undefined &&\n typeof thisItem.value === \"object\"\n ) {\n e.message +=\n `\\n- Maybe you meant to use\\n` +\n `\"${type}s\": [\\n [\"${lastItem.file.request}\", ${JSON.stringify(\n thisItem.value,\n undefined,\n 2,\n )}]\\n]\\n` +\n `To be a valid ${type}, its name and options should be wrapped in a pair of brackets`;\n }\n}\n"],"mappings":";;;;;;;;AAKA,IAAAA,QAAA,GAAAC,OAAA;AACA,IAAAC,iBAAA,GAAAD,OAAA;AA+BA,IAAAE,YAAA,GAAAF,OAAA;AAEA,MAAMG,eAA6B,GAAG;EACpCC,GAAG,EAAEC,8BAAkD;EACvDC,IAAI,EAAED,8BAAmD;EACzDE,QAAQ,EAAEC,gCAAyD;EACnEC,UAAU,EAAEC,wCAEX;EAEDC,MAAM,EAAEC,sCAA6D;EACrEC,QAAQ,EAAER,8BAAuD;EACjES,gBAAgB,EAAET,8BAEjB;EACDU,IAAI,EAAEC,+BAAoD;EAC1DC,GAAG,EAAED,+BAAmD;EAExDE,aAAa,EAAEF,+BAA6D;EAE5EG,OAAO,EAAEd;AACX,CAAC;AAED,MAAMe,kBAAgC,GAAG;EACvCC,OAAO,EAAEL,+BAAuD;EAChEM,YAAY,EAAEC;AAGhB,CAAC;AAED,MAAMC,oBAAkC,GAAG;EACzCC,OAAO,EAAEpB,8BAAsD;EAC/DqB,MAAM,EAAEC,kCAAyD;EACjEC,I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AG,CAAC,CAAC;EACjC,MAAMS,QAAQ,GAAGH,KAAK,CAACN,KAAK,CAAC;EAE7B,IACEQ,QAAQ,CAACE,IAAI,IACbF,QAAQ,CAACG,OAAO,KAAKC,SAAS,IAC9B,OAAOH,QAAQ,CAACf,KAAK,KAAK,QAAQ,EAClC;IACAa,CAAC,CAAC7B,OAAO,IACP,8BAA8B,GAC9B,IAAIT,IAAI,cAAcuC,QAAQ,CAACE,IAAI,CAACG,OAAO,MAAMC,IAAI,CAACC,SAAS,CAC7DN,QAAQ,CAACf,KAAK,EACdkB,SAAS,EACT,CACF,CAAC,QAAQ,GACT,iBAAiB3C,IAAI,gEAAgE;EACzF;AACF;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/validation/plugins.js b/node_modules/@babel/core/lib/config/validation/plugins.js new file mode 100644 index 0000000..d744ecc --- /dev/null +++ b/node_modules/@babel/core/lib/config/validation/plugins.js @@ -0,0 +1,67 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.validatePluginObject = validatePluginObject; +var _optionAssertions = require("./option-assertions.js"); +const VALIDATORS = { + name: _optionAssertions.assertString, + manipulateOptions: _optionAssertions.assertFunction, + pre: _optionAssertions.assertFunction, + post: _optionAssertions.assertFunction, + inherits: _optionAssertions.assertFunction, + visitor: assertVisitorMap, + parserOverride: _optionAssertions.assertFunction, + generatorOverride: _optionAssertions.assertFunction +}; +function assertVisitorMap(loc, value) { + const obj = (0, _optionAssertions.assertObject)(loc, value); + if (obj) { + Object.keys(obj).forEach(prop => { + if (prop !== "_exploded" && prop !== "_verified") { + assertVisitorHandler(prop, obj[prop]); + } + }); + if (obj.enter || obj.exit) { + throw new Error(`${(0, _optionAssertions.msg)(loc)} cannot contain catch-all "enter" or "exit" handlers. Please target individual nodes.`); + } + } + return obj; +} +function assertVisitorHandler(key, value) { + if (value && typeof value === "object") { + Object.keys(value).forEach(handler => { + if (handler !== "enter" && handler !== "exit") { + throw new Error(`.visitor["${key}"] may only have .enter and/or .exit handlers.`); + } + }); + } else if (typeof value !== "function") { + throw new Error(`.visitor["${key}"] must be a function`); + } +} +function validatePluginObject(obj) { + const rootPath = { + type: "root", + source: "plugin" + }; + Object.keys(obj).forEach(key => { + const validator = VALIDATORS[key]; + if (validator) { + const optLoc = { + type: "option", + name: key, + parent: rootPath + }; + validator(optLoc, obj[key]); + } else { + const invalidPluginPropertyError = new Error(`.${key} is not a valid Plugin property`); + invalidPluginPropertyError.code = "BABEL_UNKNOWN_PLUGIN_PROPERTY"; + throw invalidPluginPropertyError; + } + }); + return obj; +} +0 && 0; + +//# sourceMappingURL=plugins.js.map diff --git a/node_modules/@babel/core/lib/config/validation/plugins.js.map b/node_modules/@babel/core/lib/config/validation/plugins.js.map new file mode 100644 index 0000000..41a4ba9 --- /dev/null +++ b/node_modules/@babel/core/lib/config/validation/plugins.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_optionAssertions","require","VALIDATORS","name","assertString","manipulateOptions","assertFunction","pre","post","inherits","visitor","assertVisitorMap","parserOverride","generatorOverride","loc","value","obj","assertObject","Object","keys","forEach","prop","assertVisitorHandler","enter","exit","Error","msg","key","handler","validatePluginObject","rootPath","type","source","validator","optLoc","parent","invalidPluginPropertyError","code"],"sources":["../../../src/config/validation/plugins.ts"],"sourcesContent":["import {\n assertString,\n assertFunction,\n assertObject,\n msg,\n} from \"./option-assertions.ts\";\n\nimport type {\n ValidatorSet,\n Validator,\n OptionPath,\n RootPath,\n} from \"./option-assertions.ts\";\nimport type { ParserOptions } from \"@babel/parser\";\nimport type { Visitor } from \"@babel/traverse\";\nimport type { ValidatedOptions } from \"./options.ts\";\nimport type { File, PluginAPI, PluginPass } from \"../../index.ts\";\n\n// Note: The casts here are just meant to be static assertions to make sure\n// that the assertion functions actually assert that the value's type matches\n// the declared types.\nconst VALIDATORS: ValidatorSet = {\n name: assertString as Validator,\n manipulateOptions: assertFunction as Validator<\n PluginObject[\"manipulateOptions\"]\n >,\n pre: assertFunction as Validator,\n post: assertFunction as Validator,\n inherits: assertFunction as Validator,\n visitor: assertVisitorMap as Validator,\n\n parserOverride: assertFunction as Validator,\n generatorOverride: assertFunction as Validator<\n PluginObject[\"generatorOverride\"]\n >,\n};\n\nfunction assertVisitorMap(loc: OptionPath, value: unknown): Visitor {\n const obj = assertObject(loc, value);\n if (obj) {\n Object.keys(obj).forEach(prop => {\n if (prop !== \"_exploded\" && prop !== \"_verified\") {\n assertVisitorHandler(prop, obj[prop]);\n }\n });\n\n if (obj.enter || obj.exit) {\n throw new Error(\n `${msg(\n loc,\n )} cannot contain catch-all \"enter\" or \"exit\" handlers. Please target individual nodes.`,\n );\n }\n }\n return obj as Visitor;\n}\n\nfunction assertVisitorHandler(\n key: string,\n value: unknown,\n): asserts value is VisitorHandler {\n if (value && typeof value === \"object\") {\n Object.keys(value).forEach((handler: string) => {\n if (handler !== \"enter\" && handler !== \"exit\") {\n throw new Error(\n `.visitor[\"${key}\"] may only have .enter and/or .exit handlers.`,\n );\n }\n });\n } else if (typeof value !== \"function\") {\n throw new Error(`.visitor[\"${key}\"] must be a function`);\n }\n}\n\ntype VisitorHandler =\n | Function\n | {\n enter?: Function;\n exit?: Function;\n };\n\nexport type PluginObject = {\n name?: string;\n manipulateOptions?: (\n options: ValidatedOptions,\n parserOpts: ParserOptions,\n ) => void;\n pre?: (this: S, file: File) => void;\n post?: (this: S, file: File) => void;\n inherits?: (\n api: PluginAPI,\n options: unknown,\n dirname: string,\n ) => PluginObject;\n visitor?: Visitor;\n parserOverride?: Function;\n generatorOverride?: Function;\n};\n\nexport function validatePluginObject(obj: {\n [key: string]: unknown;\n}): PluginObject {\n const rootPath: RootPath = {\n type: \"root\",\n source: \"plugin\",\n };\n Object.keys(obj).forEach((key: string) => {\n const validator = VALIDATORS[key];\n\n if (validator) {\n const optLoc: OptionPath = {\n type: \"option\",\n name: key,\n parent: rootPath,\n };\n validator(optLoc, obj[key]);\n } else {\n const invalidPluginPropertyError = new Error(\n `.${key} is not a valid Plugin property`,\n );\n // @ts-expect-error todo(flow->ts) consider adding BabelConfigError with code field\n invalidPluginPropertyError.code = \"BABEL_UNKNOWN_PLUGIN_PROPERTY\";\n throw invalidPluginPropertyError;\n }\n });\n\n return obj as any;\n}\n"],"mappings":";;;;;;AAAA,IAAAA,iBAAA,GAAAC,OAAA;AAqBA,MAAMC,UAAwB,GAAG;EAC/BC,IAAI,EAAEC,8BAA+C;EACrDC,iBAAiB,EAAEC,gCAElB;EACDC,GAAG,EAAED,gCAAgD;EACrDE,IAAI,EAAEF,gCAAiD;EACvDG,QAAQ,EAAEH,gCAAqD;EAC/DI,OAAO,EAAEC,gBAAsD;EAE/DC,cAAc,EAAEN,gCAA2D;EAC3EO,iBAAiB,EAAEP;AAGrB,CAAC;AAED,SAASK,gBAAgBA,CAACG,GAAe,EAAEC,KAAc,EAAW;EAClE,MAAMC,GAAG,GAAG,IAAAC,8BAAY,EAACH,GAAG,EAAEC,KAAK,CAAC;EACpC,IAAIC,GAAG,EAAE;IACPE,MAAM,CAACC,IAAI,CAACH,GAAG,CAAC,CAACI,OAAO,CAACC,IAAI,IAAI;MAC/B,IAAIA,IAAI,KAAK,WAAW,IAAIA,IAAI,KAAK,WAAW,EAAE;QAChDC,oBAAoB,CAACD,IAAI,EAAEL,GAAG,CAACK,IAAI,CAAC,CAAC;MACvC;IACF,CAAC,CAAC;IAEF,IAAIL,GAAG,CAACO,KAAK,IAAIP,GAAG,CAACQ,IAAI,EAAE;MACzB,MAAM,IAAIC,KAAK,CACb,GAAG,IAAAC,qBAAG,EACJZ,GACF,CAAC,uFACH,CAAC;IACH;EACF;EACA,OAAOE,GAAG;AACZ;AAEA,SAASM,oBAAoBA,CAC3BK,GAAW,EACXZ,KAAc,EACmB;EACjC,IAAIA,KAAK,IAAI,OAAOA,KAAK,KAAK,QAAQ,EAAE;IACtCG,MAAM,CAACC,IAAI,CAACJ,KAAK,CAAC,CAACK,OAAO,CAAEQ,OAAe,IAAK;MAC9C,IAAIA,OAAO,KAAK,OAAO,IAAIA,OAAO,KAAK,MAAM,EAAE;QAC7C,MAAM,IAAIH,KAAK,CACb,aAAaE,GAAG,gDAClB,CAAC;MACH;IACF,CAAC,CAAC;EACJ,CAAC,MAAM,IAAI,OAAOZ,KAAK,KAAK,UAAU,EAAE;IACtC,MAAM,IAAIU,KAAK,CAAC,aAAaE,GAAG,uBAAuB,CAAC;EAC1D;AACF;AA2BO,SAASE,oBAAoBA,CAACb,GAEpC,EAAgB;EACf,MAAMc,QAAkB,GAAG;IACzBC,IAAI,EAAE,MAAM;IACZC,MAAM,EAAE;EACV,CAAC;EACDd,MAAM,CAACC,IAAI,CAACH,GAAG,CAAC,CAACI,OAAO,CAAEO,GAAW,IAAK;IACxC,MAAMM,SAAS,GAAG/B,UAAU,CAACyB,GAAG,CAAC;IAEjC,IAAIM,SAAS,EAAE;MACb,MAAMC,MAAkB,GAAG;QACzBH,IAAI,EAAE,QAAQ;QACd5B,IAAI,EAAEwB,GAAG;QACTQ,MAAM,EAAEL;MACV,CAAC;MACDG,SAAS,CAACC,MAAM,EAAElB,GAAG,CAACW,GAAG,CAAC,CAAC;IAC7B,CAAC,MAAM;MACL,MAAMS,0BAA0B,GAAG,IAAIX,KAAK,CAC1C,IAAIE,GAAG,iCACT,CAAC;MAEDS,0BAA0B,CAACC,IAAI,GAAG,+BAA+B;MACjE,MAAMD,0BAA0B;IAClC;EACF,CAAC,CAAC;EAEF,OAAOpB,GAAG;AACZ;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/validation/removed.js b/node_modules/@babel/core/lib/config/validation/removed.js new file mode 100644 index 0000000..9bd436e --- /dev/null +++ b/node_modules/@babel/core/lib/config/validation/removed.js @@ -0,0 +1,68 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = exports.default = { + auxiliaryComment: { + message: "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`" + }, + blacklist: { + message: "Put the specific transforms you want in the `plugins` option" + }, + breakConfig: { + message: "This is not a necessary option in Babel 6" + }, + experimental: { + message: "Put the specific transforms you want in the `plugins` option" + }, + externalHelpers: { + message: "Use the `external-helpers` plugin instead. " + "Check out http://babeljs.io/docs/plugins/external-helpers/" + }, + extra: { + message: "" + }, + jsxPragma: { + message: "use the `pragma` option in the `react-jsx` plugin. " + "Check out http://babeljs.io/docs/plugins/transform-react-jsx/" + }, + loose: { + message: "Specify the `loose` option for the relevant plugin you are using " + "or use a preset that sets the option." + }, + metadataUsedHelpers: { + message: "Not required anymore as this is enabled by default" + }, + modules: { + message: "Use the corresponding module transform plugin in the `plugins` option. " + "Check out http://babeljs.io/docs/plugins/#modules" + }, + nonStandard: { + message: "Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. " + "Also check out the react preset http://babeljs.io/docs/plugins/preset-react/" + }, + optional: { + message: "Put the specific transforms you want in the `plugins` option" + }, + sourceMapName: { + message: "The `sourceMapName` option has been removed because it makes more sense for the " + "tooling that calls Babel to assign `map.file` themselves." + }, + stage: { + message: "Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets" + }, + whitelist: { + message: "Put the specific transforms you want in the `plugins` option" + }, + resolveModuleSource: { + version: 6, + message: "Use `babel-plugin-module-resolver@3`'s 'resolvePath' options" + }, + metadata: { + version: 6, + message: "Generated plugin metadata is always included in the output result" + }, + sourceMapTarget: { + version: 6, + message: "The `sourceMapTarget` option has been removed because it makes more sense for the tooling " + "that calls Babel to assign `map.file` themselves." + } +}; +0 && 0; + +//# sourceMappingURL=removed.js.map diff --git a/node_modules/@babel/core/lib/config/validation/removed.js.map b/node_modules/@babel/core/lib/config/validation/removed.js.map new file mode 100644 index 0000000..fa56595 --- /dev/null +++ b/node_modules/@babel/core/lib/config/validation/removed.js.map @@ -0,0 +1 @@ +{"version":3,"names":["auxiliaryComment","message","blacklist","breakConfig","experimental","externalHelpers","extra","jsxPragma","loose","metadataUsedHelpers","modules","nonStandard","optional","sourceMapName","stage","whitelist","resolveModuleSource","version","metadata","sourceMapTarget"],"sources":["../../../src/config/validation/removed.ts"],"sourcesContent":["export default {\n auxiliaryComment: {\n message: \"Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`\",\n },\n blacklist: {\n message: \"Put the specific transforms you want in the `plugins` option\",\n },\n breakConfig: {\n message: \"This is not a necessary option in Babel 6\",\n },\n experimental: {\n message: \"Put the specific transforms you want in the `plugins` option\",\n },\n externalHelpers: {\n message:\n \"Use the `external-helpers` plugin instead. \" +\n \"Check out http://babeljs.io/docs/plugins/external-helpers/\",\n },\n extra: {\n message: \"\",\n },\n jsxPragma: {\n message:\n \"use the `pragma` option in the `react-jsx` plugin. \" +\n \"Check out http://babeljs.io/docs/plugins/transform-react-jsx/\",\n },\n loose: {\n message:\n \"Specify the `loose` option for the relevant plugin you are using \" +\n \"or use a preset that sets the option.\",\n },\n metadataUsedHelpers: {\n message: \"Not required anymore as this is enabled by default\",\n },\n modules: {\n message:\n \"Use the corresponding module transform plugin in the `plugins` option. \" +\n \"Check out http://babeljs.io/docs/plugins/#modules\",\n },\n nonStandard: {\n message:\n \"Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. \" +\n \"Also check out the react preset http://babeljs.io/docs/plugins/preset-react/\",\n },\n optional: {\n message: \"Put the specific transforms you want in the `plugins` option\",\n },\n sourceMapName: {\n message:\n \"The `sourceMapName` option has been removed because it makes more sense for the \" +\n \"tooling that calls Babel to assign `map.file` themselves.\",\n },\n stage: {\n message:\n \"Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets\",\n },\n whitelist: {\n message: \"Put the specific transforms you want in the `plugins` option\",\n },\n\n resolveModuleSource: {\n version: 6,\n message: \"Use `babel-plugin-module-resolver@3`'s 'resolvePath' options\",\n },\n metadata: {\n version: 6,\n message:\n \"Generated plugin metadata is always included in the output result\",\n },\n sourceMapTarget: {\n version: 6,\n message:\n \"The `sourceMapTarget` option has been removed because it makes more sense for the tooling \" +\n \"that calls Babel to assign `map.file` themselves.\",\n },\n} as { [name: string]: { version?: number; message: string } };\n"],"mappings":";;;;;;iCAAe;EACbA,gBAAgB,EAAE;IAChBC,OAAO,EAAE;EACX,CAAC;EACDC,SAAS,EAAE;IACTD,OAAO,EAAE;EACX,CAAC;EACDE,WAAW,EAAE;IACXF,OAAO,EAAE;EACX,CAAC;EACDG,YAAY,EAAE;IACZH,OAAO,EAAE;EACX,CAAC;EACDI,eAAe,EAAE;IACfJ,OAAO,EACL,6CAA6C,GAC7C;EACJ,CAAC;EACDK,KAAK,EAAE;IACLL,OAAO,EAAE;EACX,CAAC;EACDM,SAAS,EAAE;IACTN,OAAO,EACL,qDAAqD,GACrD;EACJ,CAAC;EACDO,KAAK,EAAE;IACLP,OAAO,EACL,mEAAmE,GACnE;EACJ,CAAC;EACDQ,mBAAmB,EAAE;IACnBR,OAAO,EAAE;EACX,CAAC;EACDS,OAAO,EAAE;IACPT,OAAO,EACL,yEAAyE,GACzE;EACJ,CAAC;EACDU,WAAW,EAAE;IACXV,OAAO,EACL,8EAA8E,GAC9E;EACJ,CAAC;EACDW,QAAQ,EAAE;IACRX,OAAO,EAAE;EACX,CAAC;EACDY,aAAa,EAAE;IACbZ,OAAO,EACL,kFAAkF,GAClF;EACJ,CAAC;EACDa,KAAK,EAAE;IACLb,OAAO,EACL;EACJ,CAAC;EACDc,SAAS,EAAE;IACTd,OAAO,EAAE;EACX,CAAC;EAEDe,mBAAmB,EAAE;IACnBC,OAAO,EAAE,CAAC;IACVhB,OAAO,EAAE;EACX,CAAC;EACDiB,QAAQ,EAAE;IACRD,OAAO,EAAE,CAAC;IACVhB,OAAO,EACL;EACJ,CAAC;EACDkB,eAAe,EAAE;IACfF,OAAO,EAAE,CAAC;IACVhB,OAAO,EACL,4FAA4F,GAC5F;EACJ;AACF,CAAC;AAAA","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/errors/config-error.js b/node_modules/@babel/core/lib/errors/config-error.js new file mode 100644 index 0000000..c290804 --- /dev/null +++ b/node_modules/@babel/core/lib/errors/config-error.js @@ -0,0 +1,18 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _rewriteStackTrace = require("./rewrite-stack-trace.js"); +class ConfigError extends Error { + constructor(message, filename) { + super(message); + (0, _rewriteStackTrace.expectedError)(this); + if (filename) (0, _rewriteStackTrace.injectVirtualStackFrame)(this, filename); + } +} +exports.default = ConfigError; +0 && 0; + +//# sourceMappingURL=config-error.js.map diff --git a/node_modules/@babel/core/lib/errors/config-error.js.map b/node_modules/@babel/core/lib/errors/config-error.js.map new file mode 100644 index 0000000..0045ded --- /dev/null +++ b/node_modules/@babel/core/lib/errors/config-error.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_rewriteStackTrace","require","ConfigError","Error","constructor","message","filename","expectedError","injectVirtualStackFrame","exports","default"],"sources":["../../src/errors/config-error.ts"],"sourcesContent":["import {\n injectVirtualStackFrame,\n expectedError,\n} from \"./rewrite-stack-trace.ts\";\n\nexport default class ConfigError extends Error {\n constructor(message: string, filename?: string) {\n super(message);\n expectedError(this);\n if (filename) injectVirtualStackFrame(this, filename);\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,kBAAA,GAAAC,OAAA;AAKe,MAAMC,WAAW,SAASC,KAAK,CAAC;EAC7CC,WAAWA,CAACC,OAAe,EAAEC,QAAiB,EAAE;IAC9C,KAAK,CAACD,OAAO,CAAC;IACd,IAAAE,gCAAa,EAAC,IAAI,CAAC;IACnB,IAAID,QAAQ,EAAE,IAAAE,0CAAuB,EAAC,IAAI,EAAEF,QAAQ,CAAC;EACvD;AACF;AAACG,OAAA,CAAAC,OAAA,GAAAR,WAAA;AAAA","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/errors/rewrite-stack-trace.js b/node_modules/@babel/core/lib/errors/rewrite-stack-trace.js new file mode 100644 index 0000000..68896d3 --- /dev/null +++ b/node_modules/@babel/core/lib/errors/rewrite-stack-trace.js @@ -0,0 +1,98 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.beginHiddenCallStack = beginHiddenCallStack; +exports.endHiddenCallStack = endHiddenCallStack; +exports.expectedError = expectedError; +exports.injectVirtualStackFrame = injectVirtualStackFrame; +var _Object$getOwnPropert; +const ErrorToString = Function.call.bind(Error.prototype.toString); +const SUPPORTED = !!Error.captureStackTrace && ((_Object$getOwnPropert = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit")) == null ? void 0 : _Object$getOwnPropert.writable) === true; +const START_HIDING = "startHiding - secret - don't use this - v1"; +const STOP_HIDING = "stopHiding - secret - don't use this - v1"; +const expectedErrors = new WeakSet(); +const virtualFrames = new WeakMap(); +function CallSite(filename) { + return Object.create({ + isNative: () => false, + isConstructor: () => false, + isToplevel: () => true, + getFileName: () => filename, + getLineNumber: () => undefined, + getColumnNumber: () => undefined, + getFunctionName: () => undefined, + getMethodName: () => undefined, + getTypeName: () => undefined, + toString: () => filename + }); +} +function injectVirtualStackFrame(error, filename) { + if (!SUPPORTED) return; + let frames = virtualFrames.get(error); + if (!frames) virtualFrames.set(error, frames = []); + frames.push(CallSite(filename)); + return error; +} +function expectedError(error) { + if (!SUPPORTED) return; + expectedErrors.add(error); + return error; +} +function beginHiddenCallStack(fn) { + if (!SUPPORTED) return fn; + return Object.defineProperty(function (...args) { + setupPrepareStackTrace(); + return fn(...args); + }, "name", { + value: STOP_HIDING + }); +} +function endHiddenCallStack(fn) { + if (!SUPPORTED) return fn; + return Object.defineProperty(function (...args) { + return fn(...args); + }, "name", { + value: START_HIDING + }); +} +function setupPrepareStackTrace() { + setupPrepareStackTrace = () => {}; + const { + prepareStackTrace = defaultPrepareStackTrace + } = Error; + const MIN_STACK_TRACE_LIMIT = 50; + Error.stackTraceLimit && (Error.stackTraceLimit = Math.max(Error.stackTraceLimit, MIN_STACK_TRACE_LIMIT)); + Error.prepareStackTrace = function stackTraceRewriter(err, trace) { + let newTrace = []; + const isExpected = expectedErrors.has(err); + let status = isExpected ? "hiding" : "unknown"; + for (let i = 0; i < trace.length; i++) { + const name = trace[i].getFunctionName(); + if (name === START_HIDING) { + status = "hiding"; + } else if (name === STOP_HIDING) { + if (status === "hiding") { + status = "showing"; + if (virtualFrames.has(err)) { + newTrace.unshift(...virtualFrames.get(err)); + } + } else if (status === "unknown") { + newTrace = trace; + break; + } + } else if (status !== "hiding") { + newTrace.push(trace[i]); + } + } + return prepareStackTrace(err, newTrace); + }; +} +function defaultPrepareStackTrace(err, trace) { + if (trace.length === 0) return ErrorToString(err); + return `${ErrorToString(err)}\n at ${trace.join("\n at ")}`; +} +0 && 0; + +//# sourceMappingURL=rewrite-stack-trace.js.map diff --git a/node_modules/@babel/core/lib/errors/rewrite-stack-trace.js.map b/node_modules/@babel/core/lib/errors/rewrite-stack-trace.js.map new file mode 100644 index 0000000..725bf91 --- /dev/null +++ b/node_modules/@babel/core/lib/errors/rewrite-stack-trace.js.map @@ -0,0 +1 @@ +{"version":3,"names":["ErrorToString","Function","call","bind","Error","prototype","toString","SUPPORTED","captureStackTrace","_Object$getOwnPropert","Object","getOwnPropertyDescriptor","writable","START_HIDING","STOP_HIDING","expectedErrors","WeakSet","virtualFrames","WeakMap","CallSite","filename","create","isNative","isConstructor","isToplevel","getFileName","getLineNumber","undefined","getColumnNumber","getFunctionName","getMethodName","getTypeName","injectVirtualStackFrame","error","frames","get","set","push","expectedError","add","beginHiddenCallStack","fn","defineProperty","args","setupPrepareStackTrace","value","endHiddenCallStack","prepareStackTrace","defaultPrepareStackTrace","MIN_STACK_TRACE_LIMIT","stackTraceLimit","Math","max","stackTraceRewriter","err","trace","newTrace","isExpected","has","status","i","length","name","unshift","join"],"sources":["../../src/errors/rewrite-stack-trace.ts"],"sourcesContent":["/**\n * This file uses the internal V8 Stack Trace API (https://v8.dev/docs/stack-trace-api)\n * to provide utilities to rewrite the stack trace.\n * When this API is not present, all the functions in this file become noops.\n *\n * beginHiddenCallStack(fn) and endHiddenCallStack(fn) wrap their parameter to\n * mark an hidden portion of the stack trace. The function passed to\n * beginHiddenCallStack is the first hidden function, while the function passed\n * to endHiddenCallStack is the first shown function.\n *\n * When an error is thrown _outside_ of the hidden zone, everything between\n * beginHiddenCallStack and endHiddenCallStack will not be shown.\n * If an error is thrown _inside_ the hidden zone, then the whole stack trace\n * will be visible: this is to avoid hiding real bugs.\n * However, if an error inside the hidden zone is expected, it can be marked\n * with the expectedError(error) function to keep the hidden frames hidden.\n *\n * Consider this call stack (the outer function is the bottom one):\n *\n * 1. a()\n * 2. endHiddenCallStack(b)()\n * 3. c()\n * 4. beginHiddenCallStack(d)()\n * 5. e()\n * 6. f()\n *\n * - If a() throws an error, then its shown call stack will be \"a, b, e, f\"\n * - If b() throws an error, then its shown call stack will be \"b, e, f\"\n * - If c() throws an expected error, then its shown call stack will be \"e, f\"\n * - If c() throws an unexpected error, then its shown call stack will be \"c, d, e, f\"\n * - If d() throws an expected error, then its shown call stack will be \"e, f\"\n * - If d() throws an unexpected error, then its shown call stack will be \"d, e, f\"\n * - If e() throws an error, then its shown call stack will be \"e, f\"\n *\n * Additionally, an error can inject additional \"virtual\" stack frames using the\n * injectVirtualStackFrame(error, filename) function: those are injected as a\n * replacement of the hidden frames.\n * In the example above, if we called injectVirtualStackFrame(err, \"h\") and\n * injectVirtualStackFrame(err, \"i\") on the expected error thrown by c(), its\n * shown call stack would have been \"h, i, e, f\".\n * This can be useful, for example, to report config validation errors as if they\n * were directly thrown in the config file.\n */\n\nconst ErrorToString = Function.call.bind(Error.prototype.toString);\n\nconst SUPPORTED =\n !!Error.captureStackTrace &&\n Object.getOwnPropertyDescriptor(Error, \"stackTraceLimit\")?.writable === true;\n\nconst START_HIDING = \"startHiding - secret - don't use this - v1\";\nconst STOP_HIDING = \"stopHiding - secret - don't use this - v1\";\n\ntype CallSite = NodeJS.CallSite;\n\nconst expectedErrors = new WeakSet();\nconst virtualFrames = new WeakMap();\n\nfunction CallSite(filename: string): CallSite {\n // We need to use a prototype otherwise it breaks source-map-support's internals\n return Object.create({\n isNative: () => false,\n isConstructor: () => false,\n isToplevel: () => true,\n getFileName: () => filename,\n getLineNumber: () => undefined,\n getColumnNumber: () => undefined,\n getFunctionName: () => undefined,\n getMethodName: () => undefined,\n getTypeName: () => undefined,\n toString: () => filename,\n } as CallSite);\n}\n\nexport function injectVirtualStackFrame(error: Error, filename: string) {\n if (!SUPPORTED) return;\n\n let frames = virtualFrames.get(error);\n if (!frames) virtualFrames.set(error, (frames = []));\n frames.push(CallSite(filename));\n\n return error;\n}\n\nexport function expectedError(error: Error) {\n if (!SUPPORTED) return;\n expectedErrors.add(error);\n return error;\n}\n\nexport function beginHiddenCallStack(\n fn: (...args: A) => R,\n) {\n if (!SUPPORTED) return fn;\n\n return Object.defineProperty(\n function (...args: A) {\n setupPrepareStackTrace();\n return fn(...args);\n },\n \"name\",\n { value: STOP_HIDING },\n );\n}\n\nexport function endHiddenCallStack(\n fn: (...args: A) => R,\n) {\n if (!SUPPORTED) return fn;\n\n return Object.defineProperty(\n function (...args: A) {\n return fn(...args);\n },\n \"name\",\n { value: START_HIDING },\n );\n}\n\nfunction setupPrepareStackTrace() {\n // @ts-expect-error This function is a singleton\n setupPrepareStackTrace = () => {};\n\n const { prepareStackTrace = defaultPrepareStackTrace } = Error;\n\n // We add some extra frames to Error.stackTraceLimit, so that we can\n // always show some useful frames even after deleting ours.\n // STACK_TRACE_LIMIT_DELTA should be around the maximum expected number\n // of internal frames, and not too big because capturing the stack trace\n // is slow (this is why Error.stackTraceLimit does not default to Infinity!).\n // Increase it if needed.\n // However, we only do it if the user did not explicitly set it to 0.\n const MIN_STACK_TRACE_LIMIT = 50;\n Error.stackTraceLimit &&= Math.max(\n Error.stackTraceLimit,\n MIN_STACK_TRACE_LIMIT,\n );\n\n Error.prepareStackTrace = function stackTraceRewriter(err, trace) {\n let newTrace = [];\n\n const isExpected = expectedErrors.has(err);\n let status: \"showing\" | \"hiding\" | \"unknown\" = isExpected\n ? \"hiding\"\n : \"unknown\";\n for (let i = 0; i < trace.length; i++) {\n const name = trace[i].getFunctionName();\n if (name === START_HIDING) {\n status = \"hiding\";\n } else if (name === STOP_HIDING) {\n if (status === \"hiding\") {\n status = \"showing\";\n if (virtualFrames.has(err)) {\n newTrace.unshift(...virtualFrames.get(err));\n }\n } else if (status === \"unknown\") {\n // Unexpected internal error, show the full stack trace\n newTrace = trace;\n break;\n }\n } else if (status !== \"hiding\") {\n newTrace.push(trace[i]);\n }\n }\n\n return prepareStackTrace(err, newTrace);\n };\n}\n\nfunction defaultPrepareStackTrace(err: Error, trace: CallSite[]) {\n if (trace.length === 0) return ErrorToString(err);\n return `${ErrorToString(err)}\\n at ${trace.join(\"\\n at \")}`;\n}\n"],"mappings":";;;;;;;;;;AA4CA,MAAMA,aAAa,GAAGC,QAAQ,CAACC,IAAI,CAACC,IAAI,CAACC,KAAK,CAACC,SAAS,CAACC,QAAQ,CAAC;AAElE,MAAMC,SAAS,GACb,CAAC,CAACH,KAAK,CAACI,iBAAiB,IACzB,EAAAC,qBAAA,GAAAC,MAAM,CAACC,wBAAwB,CAACP,KAAK,EAAE,iBAAiB,CAAC,qBAAzDK,qBAAA,CAA2DG,QAAQ,MAAK,IAAI;AAE9E,MAAMC,YAAY,GAAG,4CAA4C;AACjE,MAAMC,WAAW,GAAG,2CAA2C;AAI/D,MAAMC,cAAc,GAAG,IAAIC,OAAO,CAAQ,CAAC;AAC3C,MAAMC,aAAa,GAAG,IAAIC,OAAO,CAAoB,CAAC;AAEtD,SAASC,QAAQA,CAACC,QAAgB,EAAY;EAE5C,OAAOV,MAAM,CAACW,MAAM,CAAC;IACnBC,QAAQ,EAAEA,CAAA,KAAM,KAAK;IACrBC,aAAa,EAAEA,CAAA,KAAM,KAAK;IAC1BC,UAAU,EAAEA,CAAA,KAAM,IAAI;IACtBC,WAAW,EAAEA,CAAA,KAAML,QAAQ;IAC3BM,aAAa,EAAEA,CAAA,KAAMC,SAAS;IAC9BC,eAAe,EAAEA,CAAA,KAAMD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nB,IAAI,CAACkB,KAAK,CAACK,CAAC,CAAC,CAAC;MACzB;IACF;IAEA,OAAOb,iBAAiB,CAACO,GAAG,EAAEE,QAAQ,CAAC;EACzC,CAAC;AACH;AAEA,SAASR,wBAAwBA,CAACM,GAAU,EAAEC,KAAiB,EAAE;EAC/D,IAAIA,KAAK,CAACM,MAAM,KAAK,CAAC,EAAE,OAAO7D,aAAa,CAACsD,GAAG,CAAC;EACjD,OAAO,GAAGtD,aAAa,CAACsD,GAAG,CAAC,YAAYC,KAAK,CAACS,IAAI,CAAC,WAAW,CAAC,EAAE;AACnE;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/gensync-utils/async.js b/node_modules/@babel/core/lib/gensync-utils/async.js new file mode 100644 index 0000000..9e00fde --- /dev/null +++ b/node_modules/@babel/core/lib/gensync-utils/async.js @@ -0,0 +1,90 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.forwardAsync = forwardAsync; +exports.isAsync = void 0; +exports.isThenable = isThenable; +exports.maybeAsync = maybeAsync; +exports.waitFor = exports.onFirstPause = void 0; +function _gensync() { + const data = require("gensync"); + _gensync = function () { + return data; + }; + return data; +} +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +const runGenerator = _gensync()(function* (item) { + return yield* item; +}); +const isAsync = exports.isAsync = _gensync()({ + sync: () => false, + errback: cb => cb(null, true) +}); +function maybeAsync(fn, message) { + return _gensync()({ + sync(...args) { + const result = fn.apply(this, args); + if (isThenable(result)) throw new Error(message); + return result; + }, + async(...args) { + return Promise.resolve(fn.apply(this, args)); + } + }); +} +const withKind = _gensync()({ + sync: cb => cb("sync"), + async: function () { + var _ref = _asyncToGenerator(function* (cb) { + return cb("async"); + }); + return function async(_x) { + return _ref.apply(this, arguments); + }; + }() +}); +function forwardAsync(action, cb) { + const g = _gensync()(action); + return withKind(kind => { + const adapted = g[kind]; + return cb(adapted); + }); +} +const onFirstPause = exports.onFirstPause = _gensync()({ + name: "onFirstPause", + arity: 2, + sync: function (item) { + return runGenerator.sync(item); + }, + errback: function (item, firstPause, cb) { + let completed = false; + runGenerator.errback(item, (err, value) => { + completed = true; + cb(err, value); + }); + if (!completed) { + firstPause(); + } + } +}); +const waitFor = exports.waitFor = _gensync()({ + sync: x => x, + async: function () { + var _ref2 = _asyncToGenerator(function* (x) { + return x; + }); + return function async(_x2) { + return _ref2.apply(this, arguments); + }; + }() +}); +function isThenable(val) { + return !!val && (typeof val === "object" || typeof val === "function") && !!val.then && typeof val.then === "function"; +} +0 && 0; + +//# sourceMappingURL=async.js.map diff --git a/node_modules/@babel/core/lib/gensync-utils/async.js.map b/node_modules/@babel/core/lib/gensync-utils/async.js.map new file mode 100644 index 0000000..ac27b93 --- /dev/null +++ b/node_modules/@babel/core/lib/gensync-utils/async.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_gensync","data","require","asyncGeneratorStep","gen","resolve","reject","_next","_throw","key","arg","info","value","error","done","Promise","then","_asyncToGenerator","fn","self","args","arguments","apply","err","undefined","runGenerator","gensync","item","isAsync","exports","sync","errback","cb","maybeAsync","message","result","isThenable","Error","async","withKind","_ref","_x","forwardAsync","action","g","kind","adapted","onFirstPause","name","arity","firstPause","completed","waitFor","x","_ref2","_x2","val"],"sources":["../../src/gensync-utils/async.ts"],"sourcesContent":["import gensync, { type Gensync, type Handler, type Callback } from \"gensync\";\n\ntype MaybePromise = T | Promise;\n\nconst runGenerator: {\n sync(gen: Handler): Return;\n async(gen: Handler): Promise;\n errback(gen: Handler, cb: Callback): void;\n} = gensync(function* (item: Handler): Handler {\n return yield* item;\n});\n\n// This Gensync returns true if the current execution context is\n// asynchronous, otherwise it returns false.\nexport const isAsync = gensync({\n sync: () => false,\n errback: cb => cb(null, true),\n});\n\n// This function wraps any functions (which could be either synchronous or\n// asynchronous) with a Gensync. If the wrapped function returns a promise\n// but the current execution context is synchronous, it will throw the\n// provided error.\n// This is used to handle user-provided functions which could be asynchronous.\nexport function maybeAsync(\n fn: (...args: Args) => Return,\n message: string,\n): Gensync {\n return gensync({\n sync(...args) {\n const result = fn.apply(this, args);\n if (isThenable(result)) throw new Error(message);\n return result;\n },\n async(...args) {\n return Promise.resolve(fn.apply(this, args));\n },\n });\n}\n\nconst withKind = gensync({\n sync: cb => cb(\"sync\"),\n async: async cb => cb(\"async\"),\n}) as (cb: (kind: \"sync\" | \"async\") => MaybePromise) => Handler;\n\n// This function wraps a generator (or a Gensync) into another function which,\n// when called, will run the provided generator in a sync or async way, depending\n// on the execution context where this forwardAsync function is called.\n// This is useful, for example, when passing a callback to a function which isn't\n// aware of gensync, but it only knows about synchronous and asynchronous functions.\n// An example is cache.using, which being exposed to the user must be as simple as\n// possible:\n// yield* forwardAsync(gensyncFn, wrappedFn =>\n// cache.using(x => {\n// // Here we don't know about gensync. wrappedFn is a\n// // normal sync or async function\n// return wrappedFn(x);\n// })\n// )\nexport function forwardAsync(\n action: (...args: Args) => Handler,\n cb: (\n adapted: (...args: Args) => MaybePromise,\n ) => MaybePromise,\n): Handler {\n const g = gensync(action);\n return withKind(kind => {\n const adapted = g[kind];\n return cb(adapted);\n });\n}\n\n// If the given generator is executed asynchronously, the first time that it\n// is paused (i.e. When it yields a gensync generator which can't be run\n// synchronously), call the \"firstPause\" callback.\nexport const onFirstPause = gensync<\n [gen: Handler, firstPause: () => void],\n unknown\n>({\n name: \"onFirstPause\",\n arity: 2,\n sync: function (item) {\n return runGenerator.sync(item);\n },\n errback: function (item, firstPause, cb) {\n let completed = false;\n\n runGenerator.errback(item, (err, value) => {\n completed = true;\n cb(err, value);\n });\n\n if (!completed) {\n firstPause();\n }\n },\n}) as (gen: Handler, firstPause: () => void) => Handler;\n\n// Wait for the given promise to be resolved\nexport const waitFor = gensync({\n sync: x => x,\n async: async x => x,\n}) as (p: T | Promise) => Handler;\n\nexport function isThenable(val: any): val is PromiseLike {\n return (\n !!val &&\n (typeof val === \"object\" || typeof val === \"function\") &&\n !!val.then &&\n typeof val.then === \"function\"\n );\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAAA,SAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,QAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAA6E,SAAAE,mBAAAC,GAAA,EAAAC,OAAA,EAAAC,MAAA,EAAAC,KAAA,EAAAC,MAAA,EAAAC,GAAA,EAAAC,GAAA,cAAAC,IAAA,GAAAP,GAAA,CAAAK,GAAA,EAAAC,GAAA,OAAAE,KAAA,GAAAD,IAAA,CAAAC,KAAA,WAAAC,KAAA,IAAAP,MAAA,CAAAO,KAAA,iBAAAF,IAAA,CAAAG,IAAA,IAAAT,OAAA,CAAAO,KAAA,YAAAG,OAAA,CAAAV,OAAA,CAAAO,KAAA,EAAAI,IAAA,CAAAT,KAAA,EAAAC,MAAA;AAAA,SAAAS,kBAAAC,EAAA,6BAAAC,IAAA,SAAAC,IAAA,GAAAC,SAAA,aAAAN,OAAA,WAAAV,OAAA,EAAAC,MAAA,QAAAF,GAAA,GAAAc,EAAA,CAAAI,KAAA,CAAAH,IAAA,EAAAC,IAAA,YAAAb,MAAAK,KAAA,IAAAT,kBAAA,CAAAC,GAAA,EAAAC,OAAA,EAAAC,MAAA,EAAAC,KAAA,EAAAC,MAAA,UAAAI,KAAA,cAAAJ,OAAAe,GAAA,IAAApB,kBAAA,CAAAC,GAAA,EAAAC,OAAA,EAAAC,MAAA,EAAAC,KAAA,EAAAC,MAAA,WAAAe,GAAA,KAAAhB,KAAA,CAAAiB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,IAAI,IACV,OAAOwC,GAAG,CAACxC,IAAI,KAAK,UAAU;AAElC;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/gensync-utils/fs.js b/node_modules/@babel/core/lib/gensync-utils/fs.js new file mode 100644 index 0000000..b842df8 --- /dev/null +++ b/node_modules/@babel/core/lib/gensync-utils/fs.js @@ -0,0 +1,31 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.stat = exports.readFile = void 0; +function _fs() { + const data = require("fs"); + _fs = function () { + return data; + }; + return data; +} +function _gensync() { + const data = require("gensync"); + _gensync = function () { + return data; + }; + return data; +} +const readFile = exports.readFile = _gensync()({ + sync: _fs().readFileSync, + errback: _fs().readFile +}); +const stat = exports.stat = _gensync()({ + sync: _fs().statSync, + errback: _fs().stat +}); +0 && 0; + +//# sourceMappingURL=fs.js.map diff --git a/node_modules/@babel/core/lib/gensync-utils/fs.js.map b/node_modules/@babel/core/lib/gensync-utils/fs.js.map new file mode 100644 index 0000000..a1fd53a --- /dev/null +++ b/node_modules/@babel/core/lib/gensync-utils/fs.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_fs","data","require","_gensync","readFile","exports","gensync","sync","fs","readFileSync","errback","stat","statSync"],"sources":["../../src/gensync-utils/fs.ts"],"sourcesContent":["import fs from \"fs\";\nimport gensync from \"gensync\";\n\nexport const readFile = gensync<[filepath: string, encoding: \"utf8\"], string>({\n sync: fs.readFileSync,\n errback: fs.readFile,\n});\n\nexport const stat = gensync({\n sync: fs.statSync,\n errback: fs.stat,\n});\n"],"mappings":";;;;;;AAAA,SAAAA,IAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,GAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,SAAA;EAAA,MAAAF,IAAA,GAAAC,OAAA;EAAAC,QAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEO,MAAMG,QAAQ,GAAAC,OAAA,CAAAD,QAAA,GAAGE,SAAMA,CAAC,CAA+C;EAC5EC,IAAI,EAAEC,IAACA,CAAC,CAACC,YAAY;EACrBC,OAAO,EAAEF,IAACA,CAAC,CAACJ;AACd,CAAC,CAAC;AAEK,MAAMO,IAAI,GAAAN,OAAA,CAAAM,IAAA,GAAGL,SAAMA,CAAC,CAAC;EAC1BC,IAAI,EAAEC,IAACA,CAAC,CAACI,QAAQ;EACjBF,OAAO,EAAEF,IAACA,CAAC,CAACG;AACd,CAAC,CAAC;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/gensync-utils/functional.js b/node_modules/@babel/core/lib/gensync-utils/functional.js new file mode 100644 index 0000000..d7f7755 --- /dev/null +++ b/node_modules/@babel/core/lib/gensync-utils/functional.js @@ -0,0 +1,58 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.once = once; +var _async = require("./async.js"); +function once(fn) { + let result; + let resultP; + let promiseReferenced = false; + return function* () { + if (!result) { + if (resultP) { + promiseReferenced = true; + return yield* (0, _async.waitFor)(resultP); + } + if (!(yield* (0, _async.isAsync)())) { + try { + result = { + ok: true, + value: yield* fn() + }; + } catch (error) { + result = { + ok: false, + value: error + }; + } + } else { + let resolve, reject; + resultP = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + try { + result = { + ok: true, + value: yield* fn() + }; + resultP = null; + if (promiseReferenced) resolve(result.value); + } catch (error) { + result = { + ok: false, + value: error + }; + resultP = null; + if (promiseReferenced) reject(error); + } + } + } + if (result.ok) return result.value;else throw result.value; + }; +} +0 && 0; + +//# sourceMappingURL=functional.js.map diff --git a/node_modules/@babel/core/lib/gensync-utils/functional.js.map b/node_modules/@babel/core/lib/gensync-utils/functional.js.map new file mode 100644 index 0000000..e8c5ed0 --- /dev/null +++ b/node_modules/@babel/core/lib/gensync-utils/functional.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_async","require","once","fn","result","resultP","promiseReferenced","waitFor","isAsync","ok","value","error","resolve","reject","Promise","res","rej"],"sources":["../../src/gensync-utils/functional.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\n\nimport { isAsync, waitFor } from \"./async.ts\";\n\nexport function once(fn: () => Handler): () => Handler {\n let result: { ok: true; value: R } | { ok: false; value: unknown };\n let resultP: Promise;\n let promiseReferenced = false;\n return function* () {\n if (!result) {\n if (resultP) {\n promiseReferenced = true;\n return yield* waitFor(resultP);\n }\n\n if (!(yield* isAsync())) {\n try {\n result = { ok: true, value: yield* fn() };\n } catch (error) {\n result = { ok: false, value: error };\n }\n } else {\n let resolve: (result: R) => void, reject: (error: unknown) => void;\n resultP = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n try {\n result = { ok: true, value: yield* fn() };\n // Avoid keeping the promise around\n // now that we have the result.\n resultP = null;\n // We only resolve/reject the promise if it has been actually\n // referenced. If there are no listeners we can forget about it.\n // In the reject case, this avoid uncatchable unhandledRejection\n // events.\n if (promiseReferenced) resolve(result.value);\n } catch (error) {\n result = { ok: false, value: error };\n resultP = null;\n if (promiseReferenced) reject(error);\n }\n }\n }\n\n if (result.ok) return result.value;\n else throw result.value;\n };\n}\n"],"mappings":";;;;;;AAEA,IAAAA,MAAA,GAAAC,OAAA;AAEO,SAASC,IAAIA,CAAIC,EAAoB,EAAoB;EAC9D,IAAIC,MAA8D;EAClE,IAAIC,OAAmB;EACvB,IAAIC,iBAAiB,GAAG,KAAK;EAC7B,OAAO,aAAa;IAClB,IAAI,CAACF,MAAM,EAAE;MACX,IAAIC,OAAO,EAAE;QACXC,iBAAiB,GAAG,IAAI;QACxB,OAAO,OAAO,IAAAC,cAAO,EAACF,OAAO,CAAC;MAChC;MAEA,IAAI,EAAE,OAAO,IAAAG,cAAO,EAAC,CAAC,CAAC,EAAE;QACvB,IAAI;UACFJ,MAAM,GAAG;YAAEK,EAAE,EAAE,IAAI;YAAEC,KAAK,EAAE,OAAOP,EAAE,CAAC;UAAE,CAAC;QAC3C,CAAC,CAAC,OAAOQ,KAAK,EAAE;UACdP,MAAM,GAAG;YAAEK,EAAE,EAAE,KAAK;YAAEC,KAAK,EAAEC;UAAM,CAAC;QACtC;MACF,CAAC,MAAM;QACL,IAAIC,OAA4B,EAAEC,MAAgC;QAClER,OAAO,GAAG,IAAIS,OAAO,CAAC,CAACC,GAAG,EAAEC,GAAG,KAAK;UAClCJ,OAAO,GAAGG,GAAG;UACbF,MAAM,GAAGG,GAAG;QACd,CAAC,CAAC;QAEF,IAAI;UACFZ,MAAM,GAAG;YAAEK,EAAE,EAAE,IAAI;YAAEC,KAAK,EAAE,OAAOP,EAAE,CAAC;UAAE,CAAC;UAGzCE,OAAO,GAAG,IAAI;UAKd,IAAIC,iBAAiB,EAAEM,OAAO,CAACR,MAAM,CAACM,KAAK,CAAC;QAC9C,CAAC,CAAC,OAAOC,KAAK,EAAE;UACdP,MAAM,GAAG;YAAEK,EAAE,EAAE,KAAK;YAAEC,KAAK,EAAEC;UAAM,CAAC;UACpCN,OAAO,GAAG,IAAI;UACd,IAAIC,iBAAiB,EAAEO,MAAM,CAACF,KAAK,CAAC;QACtC;MACF;IACF;IAEA,IAAIP,MAAM,CAACK,EAAE,EAAE,OAAOL,MAAM,CAACM,KAAK,CAAC,KAC9B,MAAMN,MAAM,CAACM,KAAK;EACzB,CAAC;AACH;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/index.js b/node_modules/@babel/core/lib/index.js new file mode 100644 index 0000000..26f24c6 --- /dev/null +++ b/node_modules/@babel/core/lib/index.js @@ -0,0 +1,242 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.DEFAULT_EXTENSIONS = void 0; +Object.defineProperty(exports, "File", { + enumerable: true, + get: function () { + return _file.default; + } +}); +Object.defineProperty(exports, "buildExternalHelpers", { + enumerable: true, + get: function () { + return _buildExternalHelpers.default; + } +}); +Object.defineProperty(exports, "createConfigItem", { + enumerable: true, + get: function () { + return _index2.createConfigItem; + } +}); +Object.defineProperty(exports, "createConfigItemAsync", { + enumerable: true, + get: function () { + return _index2.createConfigItemAsync; + } +}); +Object.defineProperty(exports, "createConfigItemSync", { + enumerable: true, + get: function () { + return _index2.createConfigItemSync; + } +}); +Object.defineProperty(exports, "getEnv", { + enumerable: true, + get: function () { + return _environment.getEnv; + } +}); +Object.defineProperty(exports, "loadOptions", { + enumerable: true, + get: function () { + return _index2.loadOptions; + } +}); +Object.defineProperty(exports, "loadOptionsAsync", { + enumerable: true, + get: function () { + return _index2.loadOptionsAsync; + } +}); +Object.defineProperty(exports, "loadOptionsSync", { + enumerable: true, + get: function () { + return _index2.loadOptionsSync; + } +}); +Object.defineProperty(exports, "loadPartialConfig", { + enumerable: true, + get: function () { + return _index2.loadPartialConfig; + } +}); +Object.defineProperty(exports, "loadPartialConfigAsync", { + enumerable: true, + get: function () { + return _index2.loadPartialConfigAsync; + } +}); +Object.defineProperty(exports, "loadPartialConfigSync", { + enumerable: true, + get: function () { + return _index2.loadPartialConfigSync; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function () { + return _parse.parse; + } +}); +Object.defineProperty(exports, "parseAsync", { + enumerable: true, + get: function () { + return _parse.parseAsync; + } +}); +Object.defineProperty(exports, "parseSync", { + enumerable: true, + get: function () { + return _parse.parseSync; + } +}); +Object.defineProperty(exports, "resolvePlugin", { + enumerable: true, + get: function () { + return _index.resolvePlugin; + } +}); +Object.defineProperty(exports, "resolvePreset", { + enumerable: true, + get: function () { + return _index.resolvePreset; + } +}); +Object.defineProperty((0, exports), "template", { + enumerable: true, + get: function () { + return _template().default; + } +}); +Object.defineProperty((0, exports), "tokTypes", { + enumerable: true, + get: function () { + return _parser().tokTypes; + } +}); +Object.defineProperty(exports, "transform", { + enumerable: true, + get: function () { + return _transform.transform; + } +}); +Object.defineProperty(exports, "transformAsync", { + enumerable: true, + get: function () { + return _transform.transformAsync; + } +}); +Object.defineProperty(exports, "transformFile", { + enumerable: true, + get: function () { + return _transformFile.transformFile; + } +}); +Object.defineProperty(exports, "transformFileAsync", { + enumerable: true, + get: function () { + return _transformFile.transformFileAsync; + } +}); +Object.defineProperty(exports, "transformFileSync", { + enumerable: true, + get: function () { + return _transformFile.transformFileSync; + } +}); +Object.defineProperty(exports, "transformFromAst", { + enumerable: true, + get: function () { + return _transformAst.transformFromAst; + } +}); +Object.defineProperty(exports, "transformFromAstAsync", { + enumerable: true, + get: function () { + return _transformAst.transformFromAstAsync; + } +}); +Object.defineProperty(exports, "transformFromAstSync", { + enumerable: true, + get: function () { + return _transformAst.transformFromAstSync; + } +}); +Object.defineProperty(exports, "transformSync", { + enumerable: true, + get: function () { + return _transform.transformSync; + } +}); +Object.defineProperty((0, exports), "traverse", { + enumerable: true, + get: function () { + return _traverse().default; + } +}); +exports.version = exports.types = void 0; +var _file = require("./transformation/file/file.js"); +var _buildExternalHelpers = require("./tools/build-external-helpers.js"); +var _index = require("./config/files/index.js"); +var _environment = require("./config/helpers/environment.js"); +function _types() { + const data = require("@babel/types"); + _types = function () { + return data; + }; + return data; +} +Object.defineProperty((0, exports), "types", { + enumerable: true, + get: function () { + return _types(); + } +}); +function _parser() { + const data = require("@babel/parser"); + _parser = function () { + return data; + }; + return data; +} +function _traverse() { + const data = require("@babel/traverse"); + _traverse = function () { + return data; + }; + return data; +} +function _template() { + const data = require("@babel/template"); + _template = function () { + return data; + }; + return data; +} +var _index2 = require("./config/index.js"); +var _transform = require("./transform.js"); +var _transformFile = require("./transform-file.js"); +var _transformAst = require("./transform-ast.js"); +var _parse = require("./parse.js"); +var thisFile = require("./index.js"); +; +const version = exports.version = "7.25.2"; +const DEFAULT_EXTENSIONS = exports.DEFAULT_EXTENSIONS = Object.freeze([".js", ".jsx", ".es6", ".es", ".mjs", ".cjs"]); +; +{ + exports.OptionManager = class OptionManager { + init(opts) { + return (0, _index2.loadOptionsSync)(opts); + } + }; + exports.Plugin = function Plugin(alias) { + throw new Error(`The (${alias}) Babel 5 plugin is being run with an unsupported Babel version.`); + }; +} +0 && (exports.types = exports.traverse = exports.tokTypes = exports.template = 0); + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/core/lib/index.js.map b/node_modules/@babel/core/lib/index.js.map new file mode 100644 index 0000000..6108b82 --- /dev/null +++ b/node_modules/@babel/core/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_file","require","_buildExternalHelpers","_index","_environment","_types","data","Object","defineProperty","exports","enumerable","get","_parser","_traverse","_template","_index2","_transform","_transformFile","_transformAst","_parse","thisFile","version","DEFAULT_EXTENSIONS","freeze","OptionManager","init","opts","loadOptionsSync","Plugin","alias","Error","types","traverse","tokTypes","template"],"sources":["../src/index.ts"],"sourcesContent":["if (!process.env.IS_PUBLISH && !USE_ESM && process.env.BABEL_8_BREAKING) {\n throw new Error(\n \"BABEL_8_BREAKING is only supported in ESM. Please run `make use-esm`.\",\n );\n}\n\nexport const version = PACKAGE_JSON.version;\n\nexport { default as File } from \"./transformation/file/file.ts\";\nexport type { default as PluginPass } from \"./transformation/plugin-pass.ts\";\nexport { default as buildExternalHelpers } from \"./tools/build-external-helpers.ts\";\nexport { resolvePlugin, resolvePreset } from \"./config/files/index.ts\";\n\nexport { getEnv } from \"./config/helpers/environment.ts\";\n\n// NOTE: Lazy re-exports aren't detected by the Node.js CJS-ESM interop.\n// These are handled by pluginInjectNodeReexportsHints in our babel.config.js\n// so that they can work well.\nexport * as types from \"@babel/types\";\nexport { tokTypes } from \"@babel/parser\";\nexport { default as traverse } from \"@babel/traverse\";\nexport { default as template } from \"@babel/template\";\n\n// rollup-plugin-dts assumes that all re-exported types are also valid values\n// Visitor is only a type, so we need to use this workaround to prevent\n// rollup-plugin-dts from breaking it.\n// TODO: Figure out how to fix this upstream.\nexport type { NodePath, Scope } from \"@babel/traverse\";\nexport type Visitor = import(\"@babel/traverse\").Visitor;\n\nexport {\n createConfigItem,\n createConfigItemSync,\n createConfigItemAsync,\n} from \"./config/index.ts\";\n\nexport {\n loadPartialConfig,\n loadPartialConfigSync,\n loadPartialConfigAsync,\n loadOptions,\n loadOptionsAsync,\n} from \"./config/index.ts\";\nimport { loadOptionsSync } from \"./config/index.ts\";\nexport { loadOptionsSync };\n\nexport type {\n CallerMetadata,\n InputOptions,\n PluginAPI,\n PluginObject,\n PresetAPI,\n PresetObject,\n ConfigItem,\n} from \"./config/index.ts\";\n\nexport {\n transform,\n transformSync,\n transformAsync,\n type FileResult,\n} from \"./transform.ts\";\nexport {\n transformFile,\n transformFileSync,\n transformFileAsync,\n} from \"./transform-file.ts\";\nexport {\n transformFromAst,\n transformFromAstSync,\n transformFromAstAsync,\n} from \"./transform-ast.ts\";\nexport { parse, parseSync, parseAsync } from \"./parse.ts\";\n\n/**\n * Recommended set of compilable extensions. Not used in @babel/core directly, but meant as\n * as an easy source for tooling making use of @babel/core.\n */\nexport const DEFAULT_EXTENSIONS = Object.freeze([\n \".js\",\n \".jsx\",\n \".es6\",\n \".es\",\n \".mjs\",\n \".cjs\",\n] as const);\n\nimport Module from \"module\";\nimport * as thisFile from \"./index.ts\";\nif (USE_ESM && !IS_STANDALONE) {\n // Pass this module to the CJS proxy, so that it can be synchronously accessed.\n const cjsProxy = Module.createRequire(import.meta.url)(\"../cjs-proxy.cjs\");\n cjsProxy[\"__ initialize @babel/core cjs proxy __\"] = thisFile;\n}\n\nif (!process.env.BABEL_8_BREAKING && !USE_ESM) {\n // For easier backward-compatibility, provide an API like the one we exposed in Babel 6.\n // eslint-disable-next-line no-restricted-globals\n exports.OptionManager = class OptionManager {\n init(opts: unknown) {\n return loadOptionsSync(opts);\n }\n };\n\n // eslint-disable-next-line no-restricted-globals\n exports.Plugin = function Plugin(alias: string) {\n throw new Error(\n `The (${alias}) Babel 5 plugin is being run with an unsupported Babel version.`,\n );\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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KAAK,EACL,MAAM,EACN,MAAM,EACN,KAAK,EACL,MAAM,EACN,MAAM,CACE,CAAC;AAAC;AAUmC;EAG7Cd,OAAO,CAACe,aAAa,GAAG,MAAMA,aAAa,CAAC;IAC1CC,IAAIA,CAACC,IAAa,EAAE;MAClB,OAAO,IAAAC,uBAAe,EAACD,IAAI,CAAC;IAC9B;EACF,CAAC;EAGDjB,OAAO,CAACmB,MAAM,GAAG,SAASA,MAAMA,CAACC,KAAa,EAAE;IAC9C,MAAM,IAAIC,KAAK,CACb,QAAQD,KAAK,kEACf,CAAC;EACH,CAAC;AACH;AAAC,MAAApB,OAAA,CAAAsB,KAAA,GAAAtB,OAAA,CAAAuB,QAAA,GAAAvB,OAAA,CAAAwB,QAAA,GAAAxB,OAAA,CAAAyB,QAAA","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/parse.js b/node_modules/@babel/core/lib/parse.js new file mode 100644 index 0000000..7e41142 --- /dev/null +++ b/node_modules/@babel/core/lib/parse.js @@ -0,0 +1,47 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.parse = void 0; +exports.parseAsync = parseAsync; +exports.parseSync = parseSync; +function _gensync() { + const data = require("gensync"); + _gensync = function () { + return data; + }; + return data; +} +var _index = require("./config/index.js"); +var _index2 = require("./parser/index.js"); +var _normalizeOpts = require("./transformation/normalize-opts.js"); +var _rewriteStackTrace = require("./errors/rewrite-stack-trace.js"); +const parseRunner = _gensync()(function* parse(code, opts) { + const config = yield* (0, _index.default)(opts); + if (config === null) { + return null; + } + return yield* (0, _index2.default)(config.passes, (0, _normalizeOpts.default)(config), code); +}); +const parse = exports.parse = function parse(code, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = undefined; + } + if (callback === undefined) { + { + return (0, _rewriteStackTrace.beginHiddenCallStack)(parseRunner.sync)(code, opts); + } + } + (0, _rewriteStackTrace.beginHiddenCallStack)(parseRunner.errback)(code, opts, callback); +}; +function parseSync(...args) { + return (0, _rewriteStackTrace.beginHiddenCallStack)(parseRunner.sync)(...args); +} +function parseAsync(...args) { + return (0, _rewriteStackTrace.beginHiddenCallStack)(parseRunner.async)(...args); +} +0 && 0; + +//# sourceMappingURL=parse.js.map diff --git a/node_modules/@babel/core/lib/parse.js.map b/node_modules/@babel/core/lib/parse.js.map new file mode 100644 index 0000000..676788c --- /dev/null +++ b/node_modules/@babel/core/lib/parse.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_gensync","data","require","_index","_index2","_normalizeOpts","_rewriteStackTrace","parseRunner","gensync","parse","code","opts","config","loadConfig","parser","passes","normalizeOptions","exports","callback","undefined","beginHiddenCallStack","sync","errback","parseSync","args","parseAsync","async"],"sources":["../src/parse.ts"],"sourcesContent":["import gensync, { type Handler } from \"gensync\";\n\nimport loadConfig, { type InputOptions } from \"./config/index.ts\";\nimport parser, { type ParseResult } from \"./parser/index.ts\";\nimport normalizeOptions from \"./transformation/normalize-opts.ts\";\nimport type { ValidatedOptions } from \"./config/validation/options.ts\";\n\nimport { beginHiddenCallStack } from \"./errors/rewrite-stack-trace.ts\";\n\ntype FileParseCallback = {\n (err: Error, ast: null): void;\n (err: null, ast: ParseResult | null): void;\n};\n\ntype Parse = {\n (code: string, callback: FileParseCallback): void;\n (\n code: string,\n opts: InputOptions | undefined | null,\n callback: FileParseCallback,\n ): void;\n (code: string, opts?: InputOptions | null): ParseResult | null;\n};\n\nconst parseRunner = gensync(function* parse(\n code: string,\n opts: InputOptions | undefined | null,\n): Handler {\n const config = yield* loadConfig(opts);\n\n if (config === null) {\n return null;\n }\n\n return yield* parser(config.passes, normalizeOptions(config), code);\n});\n\nexport const parse: Parse = function parse(\n code,\n opts?,\n callback?: FileParseCallback,\n) {\n if (typeof opts === \"function\") {\n callback = opts;\n opts = undefined as ValidatedOptions;\n }\n\n if (callback === undefined) {\n if (process.env.BABEL_8_BREAKING) {\n throw new Error(\n \"Starting from Babel 8.0.0, the 'parse' function expects a callback. If you need to call it synchronously, please use 'parseSync'.\",\n );\n } else {\n // console.warn(\n // \"Starting from Babel 8.0.0, the 'parse' function will expect a callback. If you need to call it synchronously, please use 'parseSync'.\",\n // );\n return beginHiddenCallStack(parseRunner.sync)(code, opts);\n }\n }\n\n beginHiddenCallStack(parseRunner.errback)(code, opts, callback);\n};\n\nexport function parseSync(...args: Parameters) {\n return beginHiddenCallStack(parseRunner.sync)(...args);\n}\nexport function parseAsync(...args: Parameters) {\n return beginHiddenCallStack(parseRunner.async)(...args);\n}\n"],"mappings":";;;;;;;;AAAA,SAAAA,SAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,QAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,IAAAE,MAAA,GAAAD,OAAA;AACA,IAAAE,OAAA,GAAAF,OAAA;AACA,IAAAG,cAAA,GAAAH,OAAA;AAGA,IAAAI,kBAAA,GAAAJ,OAAA;AAiBA,MAAMK,WAAW,GAAGC,SAAMA,CAAC,CAAC,UAAUC,KAAKA,CACzCC,IAAY,EACZC,IAAqC,EACR;EAC7B,MAAMC,MAAM,GAAG,OAAO,IAAAC,cAAU,EAACF,IAAI,CAAC;EAEtC,IAAIC,MAAM,KAAK,IAAI,EAAE;IACnB,OAAO,IAAI;EACb;EAEA,OAAO,OAAO,IAAAE,eAAM,EAACF,MAAM,CAACG,MAAM,EAAE,IAAAC,sBAAgB,EAACJ,MAAM,CAAC,EAAEF,IAAI,CAAC;AACrE,CAAC,CAAC;AAEK,MAAMD,KAAY,GAAAQ,OAAA,CAAAR,KAAA,GAAG,SAASA,KAAKA,CACxCC,IAAI,EACJC,IAAK,EACLO,QAA4B,EAC5B;EACA,IAAI,OAAOP,IAAI,KAAK,UAAU,EAAE;IAC9BO,QAAQ,GAAGP,IAAI;IACfA,IAAI,GAAGQ,SAA6B;EACtC;EAEA,IAAID,QAAQ,KAAKC,SAAS,EAAE;IAKnB;MAIL,OAAO,IAAAC,uCAAoB,EAACb,WAAW,CAACc,IAAI,CAAC,CAACX,IAAI,EAAEC,IAAI,CAAC;IAC3D;EACF;EAEA,IAAAS,uCAAoB,EAACb,WAAW,CAACe,OAAO,CAAC,CAACZ,IAAI,EAAEC,IAAI,EAAEO,QAAQ,CAAC;AACjE,CAAC;AAEM,SAASK,SAASA,CAAC,GAAGC,IAAyC,EAAE;EACtE,OAAO,IAAAJ,uCAAoB,EAACb,WAAW,CAACc,IAAI,CAAC,CAAC,GAAGG,IAAI,CAAC;AACxD;AACO,SAASC,UAAUA,CAAC,GAAGD,IAA0C,EAAE;EACxE,OAAO,IAAAJ,uCAAoB,EAACb,WAAW,CAACmB,KAAK,CAAC,CAAC,GAAGF,IAAI,CAAC;AACzD;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/parser/index.js b/node_modules/@babel/core/lib/parser/index.js new file mode 100644 index 0000000..d198bb2 --- /dev/null +++ b/node_modules/@babel/core/lib/parser/index.js @@ -0,0 +1,79 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = parser; +function _parser() { + const data = require("@babel/parser"); + _parser = function () { + return data; + }; + return data; +} +function _codeFrame() { + const data = require("@babel/code-frame"); + _codeFrame = function () { + return data; + }; + return data; +} +var _missingPluginHelper = require("./util/missing-plugin-helper.js"); +function* parser(pluginPasses, { + parserOpts, + highlightCode = true, + filename = "unknown" +}, code) { + try { + const results = []; + for (const plugins of pluginPasses) { + for (const plugin of plugins) { + const { + parserOverride + } = plugin; + if (parserOverride) { + const ast = parserOverride(code, parserOpts, _parser().parse); + if (ast !== undefined) results.push(ast); + } + } + } + if (results.length === 0) { + return (0, _parser().parse)(code, parserOpts); + } else if (results.length === 1) { + yield* []; + if (typeof results[0].then === "function") { + throw new Error(`You appear to be using an async parser plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`); + } + return results[0]; + } + throw new Error("More than one plugin attempted to override parsing."); + } catch (err) { + if (err.code === "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED") { + err.message += "\nConsider renaming the file to '.mjs', or setting sourceType:module " + "or sourceType:unambiguous in your Babel config for this file."; + } + const { + loc, + missingPlugin + } = err; + if (loc) { + const codeFrame = (0, _codeFrame().codeFrameColumns)(code, { + start: { + line: loc.line, + column: loc.column + 1 + } + }, { + highlightCode + }); + if (missingPlugin) { + err.message = `${filename}: ` + (0, _missingPluginHelper.default)(missingPlugin[0], loc, codeFrame, filename); + } else { + err.message = `${filename}: ${err.message}\n\n` + codeFrame; + } + err.code = "BABEL_PARSE_ERROR"; + } + throw err; + } +} +0 && 0; + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/core/lib/parser/index.js.map b/node_modules/@babel/core/lib/parser/index.js.map new file mode 100644 index 0000000..1ac2c97 --- /dev/null +++ b/node_modules/@babel/core/lib/parser/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_parser","data","require","_codeFrame","_missingPluginHelper","parser","pluginPasses","parserOpts","highlightCode","filename","code","results","plugins","plugin","parserOverride","ast","parse","undefined","push","length","then","Error","err","message","loc","missingPlugin","codeFrame","codeFrameColumns","start","line","column","generateMissingPluginMessage"],"sources":["../../src/parser/index.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\nimport { parse, type File as ParseResult } from \"@babel/parser\";\nimport { codeFrameColumns } from \"@babel/code-frame\";\nimport generateMissingPluginMessage from \"./util/missing-plugin-helper.ts\";\nimport type { PluginPasses } from \"../config/index.ts\";\n\nexport type { ParseResult };\n\nexport default function* parser(\n pluginPasses: PluginPasses,\n { parserOpts, highlightCode = true, filename = \"unknown\" }: any,\n code: string,\n): Handler {\n try {\n const results = [];\n for (const plugins of pluginPasses) {\n for (const plugin of plugins) {\n const { parserOverride } = plugin;\n if (parserOverride) {\n const ast = parserOverride(code, parserOpts, parse);\n\n if (ast !== undefined) results.push(ast);\n }\n }\n }\n\n if (results.length === 0) {\n return parse(code, parserOpts);\n } else if (results.length === 1) {\n // @ts-expect-error - If we want to allow async parsers\n yield* [];\n if (typeof results[0].then === \"function\") {\n throw new Error(\n `You appear to be using an async parser plugin, ` +\n `which your current version of Babel does not support. ` +\n `If you're using a published plugin, you may need to upgrade ` +\n `your @babel/core version.`,\n );\n }\n return results[0];\n }\n // TODO: Add an error code\n throw new Error(\"More than one plugin attempted to override parsing.\");\n } catch (err) {\n if (err.code === \"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED\") {\n err.message +=\n \"\\nConsider renaming the file to '.mjs', or setting sourceType:module \" +\n \"or sourceType:unambiguous in your Babel config for this file.\";\n // err.code will be changed to BABEL_PARSE_ERROR later.\n }\n\n const { loc, missingPlugin } = err;\n if (loc) {\n const codeFrame = codeFrameColumns(\n code,\n {\n start: {\n line: loc.line,\n column: loc.column + 1,\n },\n },\n {\n highlightCode,\n },\n );\n if (missingPlugin) {\n err.message =\n `${filename}: ` +\n generateMissingPluginMessage(\n missingPlugin[0],\n loc,\n codeFrame,\n filename,\n );\n } else {\n err.message = `${filename}: ${err.message}\\n\\n` + codeFrame;\n }\n err.code = \"BABEL_PARSE_ERROR\";\n }\n throw err;\n }\n}\n"],"mappings":";;;;;;AACA,SAAAA,QAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,OAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,WAAA;EAAA,MAAAF,IAAA,GAAAC,OAAA;EAAAC,UAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,IAAAG,oBAAA,GAAAF,OAAA;AAKe,UAAUG,MAAMA,CAC7BC,YAA0B,EAC1B;EAAEC,UAAU;EAAEC,aAAa,GAAG,IAAI;EAAEC,QAAQ,GAAG;AAAe,CAAC,EAC/DC,IAAY,EACU;EACtB,IAAI;IACF,MAAMC,OAAO,GAAG,EAAE;IAClB,KAAK,MAAMC,OAAO,IAAIN,YAAY,EAAE;MAClC,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I,GACf,IAAAsB,4BAA4B,EAC1BN,aAAa,CAAC,CAAC,CAAC,EAChBD,GAAG,EACHE,SAAS,EACTjB,QACF,CAAC;MACL,CAAC,MAAM;QACLa,GAAG,CAACC,OAAO,GAAG,GAAGd,QAAQ,KAAKa,GAAG,CAACC,OAAO,MAAM,GAAGG,SAAS;MAC7D;MACAJ,GAAG,CAACZ,IAAI,GAAG,mBAAmB;IAChC;IACA,MAAMY,GAAG;EACX;AACF;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/parser/util/missing-plugin-helper.js b/node_modules/@babel/core/lib/parser/util/missing-plugin-helper.js new file mode 100644 index 0000000..166e973 --- /dev/null +++ b/node_modules/@babel/core/lib/parser/util/missing-plugin-helper.js @@ -0,0 +1,339 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = generateMissingPluginMessage; +const pluginNameMap = { + asyncDoExpressions: { + syntax: { + name: "@babel/plugin-syntax-async-do-expressions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-async-do-expressions" + } + }, + decimal: { + syntax: { + name: "@babel/plugin-syntax-decimal", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-decimal" + } + }, + decorators: { + syntax: { + name: "@babel/plugin-syntax-decorators", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-decorators" + }, + transform: { + name: "@babel/plugin-proposal-decorators", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-decorators" + } + }, + doExpressions: { + syntax: { + name: "@babel/plugin-syntax-do-expressions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-do-expressions" + }, + transform: { + name: "@babel/plugin-proposal-do-expressions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-do-expressions" + } + }, + exportDefaultFrom: { + syntax: { + name: "@babel/plugin-syntax-export-default-from", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-export-default-from" + }, + transform: { + name: "@babel/plugin-proposal-export-default-from", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-export-default-from" + } + }, + flow: { + syntax: { + name: "@babel/plugin-syntax-flow", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-flow" + }, + transform: { + name: "@babel/preset-flow", + url: "https://github.com/babel/babel/tree/main/packages/babel-preset-flow" + } + }, + functionBind: { + syntax: { + name: "@babel/plugin-syntax-function-bind", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-function-bind" + }, + transform: { + name: "@babel/plugin-proposal-function-bind", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-function-bind" + } + }, + functionSent: { + syntax: { + name: "@babel/plugin-syntax-function-sent", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-function-sent" + }, + transform: { + name: "@babel/plugin-proposal-function-sent", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-function-sent" + } + }, + jsx: { + syntax: { + name: "@babel/plugin-syntax-jsx", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-jsx" + }, + transform: { + name: "@babel/preset-react", + url: "https://github.com/babel/babel/tree/main/packages/babel-preset-react" + } + }, + importAttributes: { + syntax: { + name: "@babel/plugin-syntax-import-attributes", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-attributes" + } + }, + pipelineOperator: { + syntax: { + name: "@babel/plugin-syntax-pipeline-operator", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-pipeline-operator" + }, + transform: { + name: "@babel/plugin-proposal-pipeline-operator", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-pipeline-operator" + } + }, + recordAndTuple: { + syntax: { + name: "@babel/plugin-syntax-record-and-tuple", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-record-and-tuple" + } + }, + throwExpressions: { + syntax: { + name: "@babel/plugin-syntax-throw-expressions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-throw-expressions" + }, + transform: { + name: "@babel/plugin-proposal-throw-expressions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-throw-expressions" + } + }, + typescript: { + syntax: { + name: "@babel/plugin-syntax-typescript", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-typescript" + }, + transform: { + name: "@babel/preset-typescript", + url: "https://github.com/babel/babel/tree/main/packages/babel-preset-typescript" + } + } +}; +{ + Object.assign(pluginNameMap, { + asyncGenerators: { + syntax: { + name: "@babel/plugin-syntax-async-generators", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-async-generators" + }, + transform: { + name: "@babel/plugin-transform-async-generator-functions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-async-generator-functions" + } + }, + classProperties: { + syntax: { + name: "@babel/plugin-syntax-class-properties", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-class-properties" + }, + transform: { + name: "@babel/plugin-transform-class-properties", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-class-properties" + } + }, + classPrivateProperties: { + syntax: { + name: "@babel/plugin-syntax-class-properties", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-class-properties" + }, + transform: { + name: "@babel/plugin-transform-class-properties", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-class-properties" + } + }, + classPrivateMethods: { + syntax: { + name: "@babel/plugin-syntax-class-properties", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-class-properties" + }, + transform: { + name: "@babel/plugin-transform-private-methods", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-private-methods" + } + }, + classStaticBlock: { + syntax: { + name: "@babel/plugin-syntax-class-static-block", + url: "https://github.com/babel/babel/tree/HEAD/packages/babel-plugin-syntax-class-static-block" + }, + transform: { + name: "@babel/plugin-transform-class-static-block", + url: "https://github.com/babel/babel/tree/HEAD/packages/babel-plugin-transform-class-static-block" + } + }, + dynamicImport: { + syntax: { + name: "@babel/plugin-syntax-dynamic-import", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-dynamic-import" + } + }, + exportNamespaceFrom: { + syntax: { + name: "@babel/plugin-syntax-export-namespace-from", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-export-namespace-from" + }, + transform: { + name: "@babel/plugin-transform-export-namespace-from", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-export-namespace-from" + } + }, + importAssertions: { + syntax: { + name: "@babel/plugin-syntax-import-assertions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-assertions" + } + }, + importMeta: { + syntax: { + name: "@babel/plugin-syntax-import-meta", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-meta" + } + }, + logicalAssignment: { + syntax: { + name: "@babel/plugin-syntax-logical-assignment-operators", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-logical-assignment-operators" + }, + transform: { + name: "@babel/plugin-transform-logical-assignment-operators", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-logical-assignment-operators" + } + }, + moduleStringNames: { + syntax: { + name: "@babel/plugin-syntax-module-string-names", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-module-string-names" + } + }, + numericSeparator: { + syntax: { + name: "@babel/plugin-syntax-numeric-separator", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-numeric-separator" + }, + transform: { + name: "@babel/plugin-transform-numeric-separator", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-numeric-separator" + } + }, + nullishCoalescingOperator: { + syntax: { + name: "@babel/plugin-syntax-nullish-coalescing-operator", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-nullish-coalescing-operator" + }, + transform: { + name: "@babel/plugin-transform-nullish-coalescing-operator", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-nullish-coalescing-opearator" + } + }, + objectRestSpread: { + syntax: { + name: "@babel/plugin-syntax-object-rest-spread", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-object-rest-spread" + }, + transform: { + name: "@babel/plugin-transform-object-rest-spread", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-object-rest-spread" + } + }, + optionalCatchBinding: { + syntax: { + name: "@babel/plugin-syntax-optional-catch-binding", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-optional-catch-binding" + }, + transform: { + name: "@babel/plugin-transform-optional-catch-binding", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-optional-catch-binding" + } + }, + optionalChaining: { + syntax: { + name: "@babel/plugin-syntax-optional-chaining", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-optional-chaining" + }, + transform: { + name: "@babel/plugin-transform-optional-chaining", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-optional-chaining" + } + }, + privateIn: { + syntax: { + name: "@babel/plugin-syntax-private-property-in-object", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-private-property-in-object" + }, + transform: { + name: "@babel/plugin-transform-private-property-in-object", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-private-property-in-object" + } + }, + regexpUnicodeSets: { + syntax: { + name: "@babel/plugin-syntax-unicode-sets-regex", + url: "https://github.com/babel/babel/blob/main/packages/babel-plugin-syntax-unicode-sets-regex/README.md" + }, + transform: { + name: "@babel/plugin-transform-unicode-sets-regex", + url: "https://github.com/babel/babel/blob/main/packages/babel-plugin-proposalunicode-sets-regex/README.md" + } + } + }); +} +const getNameURLCombination = ({ + name, + url +}) => `${name} (${url})`; +function generateMissingPluginMessage(missingPluginName, loc, codeFrame, filename) { + let helpMessage = `Support for the experimental syntax '${missingPluginName}' isn't currently enabled ` + `(${loc.line}:${loc.column + 1}):\n\n` + codeFrame; + const pluginInfo = pluginNameMap[missingPluginName]; + if (pluginInfo) { + const { + syntax: syntaxPlugin, + transform: transformPlugin + } = pluginInfo; + if (syntaxPlugin) { + const syntaxPluginInfo = getNameURLCombination(syntaxPlugin); + if (transformPlugin) { + const transformPluginInfo = getNameURLCombination(transformPlugin); + const sectionType = transformPlugin.name.startsWith("@babel/plugin") ? "plugins" : "presets"; + helpMessage += `\n\nAdd ${transformPluginInfo} to the '${sectionType}' section of your Babel config to enable transformation. +If you want to leave it as-is, add ${syntaxPluginInfo} to the 'plugins' section to enable parsing.`; + } else { + helpMessage += `\n\nAdd ${syntaxPluginInfo} to the 'plugins' section of your Babel config ` + `to enable parsing.`; + } + } + } + const msgFilename = filename === "unknown" ? "" : filename; + helpMessage += ` + +If you already added the plugin for this syntax to your config, it's possible that your config \ +isn't being loaded. +You can re-run Babel with the BABEL_SHOW_CONFIG_FOR environment variable to show the loaded \ +configuration: +\tnpx cross-env BABEL_SHOW_CONFIG_FOR=${msgFilename} +See https://babeljs.io/docs/configuration#print-effective-configs for more info. +`; + return helpMessage; +} +0 && 0; + +//# sourceMappingURL=missing-plugin-helper.js.map diff --git a/node_modules/@babel/core/lib/parser/util/missing-plugin-helper.js.map b/node_modules/@babel/core/lib/parser/util/missing-plugin-helper.js.map new file mode 100644 index 0000000..6aebfa7 --- /dev/null +++ b/node_modules/@babel/core/lib/parser/util/missing-plugin-helper.js.map @@ -0,0 +1 @@ +{"version":3,"names":["pluginNameMap","asyncDoExpressions","syntax","name","url","decimal","decorators","transform","doExpressions","exportDefaultFrom","flow","functionBind","functionSent","jsx","importAttributes","pipelineOperator","recordAndTuple","throwExpressions","typescript","Object","assign","asyncGenerators","classProperties","classPrivateProperties","classPrivateMethods","classStaticBlock","dynamicImport","exportNamespaceFrom","importAssertions","importMeta","logicalAssignment","moduleStringNames","numericSeparator","nullishCoalescingOperator","objectRestSpread","optionalCatchBinding","optionalChaining","privateIn","regexpUnicodeSets","getNameURLCombination","generateMissingPluginMessage","missingPluginName","loc","codeFrame","filename","helpMessage","line","column","pluginInfo","syntaxPlugin","transformPlugin","syntaxPluginInfo","transformPluginInfo","sectionType","startsWith","msgFilename"],"sources":["../../../src/parser/util/missing-plugin-helper.ts"],"sourcesContent":["const pluginNameMap: Record<\n string,\n Partial>>\n> = {\n asyncDoExpressions: {\n syntax: {\n name: \"@babel/plugin-syntax-async-do-expressions\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-async-do-expressions\",\n },\n },\n decimal: {\n syntax: {\n name: \"@babel/plugin-syntax-decimal\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-decimal\",\n },\n },\n decorators: {\n syntax: {\n name: \"@babel/plugin-syntax-decorators\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-decorators\",\n },\n transform: {\n name: \"@babel/plugin-proposal-decorators\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-decorators\",\n },\n },\n doExpressions: {\n syntax: {\n name: \"@babel/plugin-syntax-do-expressions\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-do-expressions\",\n },\n transform: {\n name: \"@babel/plugin-proposal-do-expressions\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-do-expressions\",\n },\n },\n exportDefaultFrom: {\n syntax: {\n name: \"@babel/plugin-syntax-export-default-from\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-export-default-from\",\n },\n transform: {\n name: \"@babel/plugin-proposal-export-default-from\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-export-default-from\",\n },\n },\n flow: {\n syntax: {\n name: \"@babel/plugin-syntax-flow\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-flow\",\n },\n transform: {\n name: \"@babel/preset-flow\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-preset-flow\",\n },\n },\n functionBind: {\n syntax: {\n name: \"@babel/plugin-syntax-function-bind\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-function-bind\",\n },\n transform: {\n name: \"@babel/plugin-proposal-function-bind\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-function-bind\",\n },\n },\n functionSent: {\n syntax: {\n name: \"@babel/plugin-syntax-function-sent\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-function-sent\",\n },\n transform: {\n name: \"@babel/plugin-proposal-function-sent\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-function-sent\",\n },\n },\n jsx: {\n syntax: {\n name: \"@babel/plugin-syntax-jsx\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-jsx\",\n },\n transform: {\n name: \"@babel/preset-react\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-preset-react\",\n },\n },\n importAttributes: {\n syntax: {\n name: \"@babel/plugin-syntax-import-attributes\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-attributes\",\n },\n },\n pipelineOperator: {\n syntax: {\n name: \"@babel/plugin-syntax-pipeline-operator\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-pipeline-operator\",\n },\n transform: {\n name: \"@babel/plugin-proposal-pipeline-operator\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-pipeline-operator\",\n },\n },\n recordAndTuple: {\n syntax: {\n name: \"@babel/plugin-syntax-record-and-tuple\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-record-and-tuple\",\n },\n },\n throwExpressions: {\n syntax: {\n name: \"@babel/plugin-syntax-throw-expressions\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-throw-expressions\",\n },\n transform: {\n name: \"@babel/plugin-proposal-throw-expressions\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-throw-expressions\",\n },\n },\n typescript: {\n syntax: {\n name: \"@babel/plugin-syntax-typescript\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-typescript\",\n },\n transform: {\n name: \"@babel/preset-typescript\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-preset-typescript\",\n },\n },\n};\n\nif (!process.env.BABEL_8_BREAKING) {\n // TODO: This plugins are now supported by default by @babel/parser.\n Object.assign(pluginNameMap, {\n asyncGenerators: {\n syntax: {\n name: \"@babel/plugin-syntax-async-generators\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-async-generators\",\n },\n transform: {\n name: \"@babel/plugin-transform-async-generator-functions\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-async-generator-functions\",\n },\n },\n classProperties: {\n syntax: {\n name: \"@babel/plugin-syntax-class-properties\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-class-properties\",\n },\n transform: {\n name: \"@babel/plugin-transform-class-properties\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-class-properties\",\n },\n },\n classPrivateProperties: {\n syntax: {\n name: \"@babel/plugin-syntax-class-properties\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-class-properties\",\n },\n transform: {\n name: \"@babel/plugin-transform-class-properties\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-class-properties\",\n },\n },\n classPrivateMethods: {\n syntax: {\n name: \"@babel/plugin-syntax-class-properties\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-class-properties\",\n },\n transform: {\n name: \"@babel/plugin-transform-private-methods\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-private-methods\",\n },\n },\n classStaticBlock: {\n syntax: {\n name: \"@babel/plugin-syntax-class-static-block\",\n url: \"https://github.com/babel/babel/tree/HEAD/packages/babel-plugin-syntax-class-static-block\",\n },\n transform: {\n name: \"@babel/plugin-transform-class-static-block\",\n url: \"https://github.com/babel/babel/tree/HEAD/packages/babel-plugin-transform-class-static-block\",\n },\n },\n dynamicImport: {\n syntax: {\n name: \"@babel/plugin-syntax-dynamic-import\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-dynamic-import\",\n },\n },\n exportNamespaceFrom: {\n syntax: {\n name: \"@babel/plugin-syntax-export-namespace-from\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-export-namespace-from\",\n },\n transform: {\n name: \"@babel/plugin-transform-export-namespace-from\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-export-namespace-from\",\n },\n },\n // Will be removed\n importAssertions: {\n syntax: {\n name: \"@babel/plugin-syntax-import-assertions\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-assertions\",\n },\n },\n importMeta: {\n syntax: {\n name: \"@babel/plugin-syntax-import-meta\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-meta\",\n },\n },\n logicalAssignment: {\n syntax: {\n name: \"@babel/plugin-syntax-logical-assignment-operators\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-logical-assignment-operators\",\n },\n transform: {\n name: \"@babel/plugin-transform-logical-assignment-operators\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-logical-assignment-operators\",\n },\n },\n moduleStringNames: {\n syntax: {\n name: \"@babel/plugin-syntax-module-string-names\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-module-string-names\",\n },\n },\n numericSeparator: {\n syntax: {\n name: \"@babel/plugin-syntax-numeric-separator\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-numeric-separator\",\n },\n transform: {\n name: \"@babel/plugin-transform-numeric-separator\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-numeric-separator\",\n },\n },\n nullishCoalescingOperator: {\n syntax: {\n name: \"@babel/plugin-syntax-nullish-coalescing-operator\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-nullish-coalescing-operator\",\n },\n transform: {\n name: \"@babel/plugin-transform-nullish-coalescing-operator\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-nullish-coalescing-opearator\",\n },\n },\n objectRestSpread: {\n syntax: {\n name: \"@babel/plugin-syntax-object-rest-spread\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-object-rest-spread\",\n },\n transform: {\n name: \"@babel/plugin-transform-object-rest-spread\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-object-rest-spread\",\n },\n },\n optionalCatchBinding: {\n syntax: {\n name: \"@babel/plugin-syntax-optional-catch-binding\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-optional-catch-binding\",\n },\n transform: {\n name: \"@babel/plugin-transform-optional-catch-binding\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-optional-catch-binding\",\n },\n },\n optionalChaining: {\n syntax: {\n name: \"@babel/plugin-syntax-optional-chaining\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-optional-chaining\",\n },\n transform: {\n name: \"@babel/plugin-transform-optional-chaining\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-optional-chaining\",\n },\n },\n privateIn: {\n syntax: {\n name: \"@babel/plugin-syntax-private-property-in-object\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-private-property-in-object\",\n },\n transform: {\n name: \"@babel/plugin-transform-private-property-in-object\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-private-property-in-object\",\n },\n },\n regexpUnicodeSets: {\n syntax: {\n name: \"@babel/plugin-syntax-unicode-sets-regex\",\n url: \"https://github.com/babel/babel/blob/main/packages/babel-plugin-syntax-unicode-sets-regex/README.md\",\n },\n transform: {\n name: \"@babel/plugin-transform-unicode-sets-regex\",\n url: \"https://github.com/babel/babel/blob/main/packages/babel-plugin-proposalunicode-sets-regex/README.md\",\n },\n },\n });\n}\n\nconst getNameURLCombination = ({ name, url }: { name: string; url: string }) =>\n `${name} (${url})`;\n\n/*\nReturns a string of the format:\nSupport for the experimental syntax [@babel/parser plugin name] isn't currently enabled ([loc]):\n\n[code frame]\n\nAdd [npm package name] ([url]) to the 'plugins' section of your Babel config\nto enable [parsing|transformation].\n*/\nexport default function generateMissingPluginMessage(\n missingPluginName: string,\n loc: {\n line: number;\n column: number;\n },\n codeFrame: string,\n filename: string,\n): string {\n let helpMessage =\n `Support for the experimental syntax '${missingPluginName}' isn't currently enabled ` +\n `(${loc.line}:${loc.column + 1}):\\n\\n` +\n codeFrame;\n const pluginInfo = pluginNameMap[missingPluginName];\n if (pluginInfo) {\n const { syntax: syntaxPlugin, transform: transformPlugin } = pluginInfo;\n if (syntaxPlugin) {\n const syntaxPluginInfo = getNameURLCombination(syntaxPlugin);\n if (transformPlugin) {\n const transformPluginInfo = getNameURLCombination(transformPlugin);\n const sectionType = transformPlugin.name.startsWith(\"@babel/plugin\")\n ? \"plugins\"\n : \"presets\";\n helpMessage += `\\n\\nAdd ${transformPluginInfo} to the '${sectionType}' section of your Babel config to enable transformation.\nIf you want to leave it as-is, add ${syntaxPluginInfo} to the 'plugins' section to enable parsing.`;\n } else {\n helpMessage +=\n `\\n\\nAdd ${syntaxPluginInfo} to the 'plugins' section of your Babel config ` +\n `to enable parsing.`;\n }\n }\n }\n\n const msgFilename =\n filename === \"unknown\" ? \"\" : filename;\n helpMessage += `\n\nIf you already added the plugin for this syntax to your config, it's possible that your config \\\nisn't being loaded.\nYou can re-run Babel with the BABEL_SHOW_CONFIG_FOR environment variable to show the loaded \\\nconfiguration:\n\\tnpx cross-env BABEL_SHOW_CONFIG_FOR=${msgFilename} \nSee https://babeljs.io/docs/configuration#print-effective-configs for more info.\n`;\n return helpMessage;\n}\n"],"mappings":";;;;;;AAAA,MAAMA,aAGL,GAAG;EACFC,kBAAkB,EAAE;IAClBC,MAAM,EAAE;MACNC,IAAI,EAAE,2CAA2C;MACjDC,GAAG,EAAE;IACP;EACF,CAAC;EACDC,OAAO,EAAE;IACPH,MAAM,EAAE;MACNC,IAAI,EAAE,8BAA8B;MACpCC,GAAG,EAAE;IACP;EACF,CAAC;EACDE,UAAU,EAAE;IACVJ,MAAM,EAAE;MACNC,IAAI,EAAE,iCAAiC;MAC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AAC;EAAEpC,IAAI;EAAEC;AAAmC,CAAC,KACzE,GAAGD,IAAI,KAAKC,GAAG,GAAG;AAWL,SAASoC,4BAA4BA,CAClDC,iBAAyB,EACzBC,GAGC,EACDC,SAAiB,EACjBC,QAAgB,EACR;EACR,IAAIC,WAAW,GACb,wCAAwCJ,iBAAiB,4BAA4B,GACrF,IAAIC,GAAG,CAACI,IAAI,IAAIJ,GAAG,CAACK,MAAM,GAAG,CAAC,QAAQ,GACtCJ,SAAS;EACX,MAAMK,UAAU,GAAGhD,aAAa,CAACyC,iBAAiB,CAAC;EACnD,IAAIO,UAAU,EAAE;IACd,MAAM;MAAE9C,MAAM,EAAE+C,YAAY;MAAE1C,SAAS,EAAE2C;IAAgB,CAAC,GAAGF,UAAU;IACvE,IAAIC,YAAY,EAAE;MAChB,MAAME,gBAAgB,GAAGZ,qBAAqB,CAACU,YAAY,CAAC;MAC5D,IAAIC,eAAe,EAAE;QACnB,MAAME,mBAAmB,GAAGb,qBAAqB,CAACW,eAAe,CAAC;QAClE,MAAMG,WAAW,GAAGH,eAAe,CAAC/C,IAAI,CAACmD,UAAU,CAAC,eAAe,CAAC,GAChE,SAAS,GACT,SAAS;QACbT,WAAW,IAAI,WAAWO,mBAAmB,YAAYC,WAAW;AAC5E,qCAAqCF,gBAAgB,8CAA8C;MAC7F,CAAC,MAAM;QACLN,WAAW,IACT,WAAWM,gBAAgB,iDAAiD,GAC5E,oBAAoB;MACxB;IACF;EACF;EAEA,MAAMI,WAAW,GACfX,QAAQ,KAAK,SAAS,GAAG,0BAA0B,GAAGA,QAAQ;EAChEC,WAAW,IAAI;AACjB;AACA;AACA;AACA;AACA;AACA,wCAAwCU,WAAW;AACnD;AACA,CAAC;EACC,OAAOV,WAAW;AACpB;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/tools/build-external-helpers.js b/node_modules/@babel/core/lib/tools/build-external-helpers.js new file mode 100644 index 0000000..88c90dc --- /dev/null +++ b/node_modules/@babel/core/lib/tools/build-external-helpers.js @@ -0,0 +1,144 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; +function helpers() { + const data = require("@babel/helpers"); + helpers = function () { + return data; + }; + return data; +} +function _generator() { + const data = require("@babel/generator"); + _generator = function () { + return data; + }; + return data; +} +function _template() { + const data = require("@babel/template"); + _template = function () { + return data; + }; + return data; +} +function _t() { + const data = require("@babel/types"); + _t = function () { + return data; + }; + return data; +} +const { + arrayExpression, + assignmentExpression, + binaryExpression, + blockStatement, + callExpression, + cloneNode, + conditionalExpression, + exportNamedDeclaration, + exportSpecifier, + expressionStatement, + functionExpression, + identifier, + memberExpression, + objectExpression, + program, + stringLiteral, + unaryExpression, + variableDeclaration, + variableDeclarator +} = _t(); +const buildUmdWrapper = replacements => _template().default.statement` + (function (root, factory) { + if (typeof define === "function" && define.amd) { + define(AMD_ARGUMENTS, factory); + } else if (typeof exports === "object") { + factory(COMMON_ARGUMENTS); + } else { + factory(BROWSER_ARGUMENTS); + } + })(UMD_ROOT, function (FACTORY_PARAMETERS) { + FACTORY_BODY + }); + `(replacements); +function buildGlobal(allowlist) { + const namespace = identifier("babelHelpers"); + const body = []; + const container = functionExpression(null, [identifier("global")], blockStatement(body)); + const tree = program([expressionStatement(callExpression(container, [conditionalExpression(binaryExpression("===", unaryExpression("typeof", identifier("global")), stringLiteral("undefined")), identifier("self"), identifier("global"))]))]); + body.push(variableDeclaration("var", [variableDeclarator(namespace, assignmentExpression("=", memberExpression(identifier("global"), namespace), objectExpression([])))])); + buildHelpers(body, namespace, allowlist); + return tree; +} +function buildModule(allowlist) { + const body = []; + const refs = buildHelpers(body, null, allowlist); + body.unshift(exportNamedDeclaration(null, Object.keys(refs).map(name => { + return exportSpecifier(cloneNode(refs[name]), identifier(name)); + }))); + return program(body, [], "module"); +} +function buildUmd(allowlist) { + const namespace = identifier("babelHelpers"); + const body = []; + body.push(variableDeclaration("var", [variableDeclarator(namespace, identifier("global"))])); + buildHelpers(body, namespace, allowlist); + return program([buildUmdWrapper({ + FACTORY_PARAMETERS: identifier("global"), + BROWSER_ARGUMENTS: assignmentExpression("=", memberExpression(identifier("root"), namespace), objectExpression([])), + COMMON_ARGUMENTS: identifier("exports"), + AMD_ARGUMENTS: arrayExpression([stringLiteral("exports")]), + FACTORY_BODY: body, + UMD_ROOT: identifier("this") + })]); +} +function buildVar(allowlist) { + const namespace = identifier("babelHelpers"); + const body = []; + body.push(variableDeclaration("var", [variableDeclarator(namespace, objectExpression([]))])); + const tree = program(body); + buildHelpers(body, namespace, allowlist); + body.push(expressionStatement(namespace)); + return tree; +} +function buildHelpers(body, namespace, allowlist) { + const getHelperReference = name => { + return namespace ? memberExpression(namespace, identifier(name)) : identifier(`_${name}`); + }; + const refs = {}; + helpers().list.forEach(function (name) { + if (allowlist && !allowlist.includes(name)) return; + const ref = refs[name] = getHelperReference(name); + const { + nodes + } = helpers().get(name, getHelperReference, namespace ? null : `_${name}`, [], namespace ? (ast, exportName, mapExportBindingAssignments) => { + mapExportBindingAssignments(node => assignmentExpression("=", ref, node)); + ast.body.push(expressionStatement(assignmentExpression("=", ref, identifier(exportName)))); + } : null); + body.push(...nodes); + }); + return refs; +} +function _default(allowlist, outputType = "global") { + let tree; + const build = { + global: buildGlobal, + module: buildModule, + umd: buildUmd, + var: buildVar + }[outputType]; + if (build) { + tree = build(allowlist); + } else { + throw new Error(`Unsupported output type ${outputType}`); + } + return (0, _generator().default)(tree).code; +} +0 && 0; + +//# sourceMappingURL=build-external-helpers.js.map diff --git a/node_modules/@babel/core/lib/tools/build-external-helpers.js.map b/node_modules/@babel/core/lib/tools/build-external-helpers.js.map new file mode 100644 index 0000000..56020e4 --- /dev/null +++ b/node_modules/@babel/core/lib/tools/build-external-helpers.js.map @@ -0,0 +1 @@ +{"version":3,"names":["helpers","data","require","_generator","_template","_t","arrayExpression","assignmentExpression","binaryExpression","blockStatement","callExpression","cloneNode","conditionalExpression","exportNamedDeclaration","exportSpecifier","expressionStatement","functionExpression","identifier","memberExpression","objectExpression","program","stringLiteral","unaryExpression","variableDeclaration","variableDeclarator","buildUmdWrapper","replacements","template","statement","buildGlobal","allowlist","namespace","body","container","tree","push","buildHelpers","buildModule","refs","unshift","Object","keys","map","name","buildUmd","FACTORY_PARAMETERS","BROWSER_ARGUMENTS","COMMON_ARGUMENTS","AMD_ARGUMENTS","FACTORY_BODY","UMD_ROOT","buildVar","getHelperReference","list","forEach","includes","ref","nodes","get","ast","exportName","mapExportBindingAssignments","node","_default","outputType","build","global","module","umd","var","Error","generator","code"],"sources":["../../src/tools/build-external-helpers.ts"],"sourcesContent":["import * as helpers from \"@babel/helpers\";\nimport generator from \"@babel/generator\";\nimport template from \"@babel/template\";\nimport {\n arrayExpression,\n assignmentExpression,\n binaryExpression,\n blockStatement,\n callExpression,\n cloneNode,\n conditionalExpression,\n exportNamedDeclaration,\n exportSpecifier,\n expressionStatement,\n functionExpression,\n identifier,\n memberExpression,\n objectExpression,\n program,\n stringLiteral,\n unaryExpression,\n variableDeclaration,\n variableDeclarator,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport type { Replacements } from \"@babel/template\";\n\n// Wrapped to avoid wasting time parsing this when almost no-one uses\n// build-external-helpers.\nconst buildUmdWrapper = (replacements: Replacements) =>\n template.statement`\n (function (root, factory) {\n if (typeof define === \"function\" && define.amd) {\n define(AMD_ARGUMENTS, factory);\n } else if (typeof exports === \"object\") {\n factory(COMMON_ARGUMENTS);\n } else {\n factory(BROWSER_ARGUMENTS);\n }\n })(UMD_ROOT, function (FACTORY_PARAMETERS) {\n FACTORY_BODY\n });\n `(replacements);\n\nfunction buildGlobal(allowlist?: Array) {\n const namespace = identifier(\"babelHelpers\");\n\n const body: t.Statement[] = [];\n const container = functionExpression(\n null,\n [identifier(\"global\")],\n blockStatement(body),\n );\n const tree = program([\n expressionStatement(\n callExpression(container, [\n // typeof global === \"undefined\" ? self : global\n conditionalExpression(\n binaryExpression(\n \"===\",\n unaryExpression(\"typeof\", identifier(\"global\")),\n stringLiteral(\"undefined\"),\n ),\n identifier(\"self\"),\n identifier(\"global\"),\n ),\n ]),\n ),\n ]);\n\n body.push(\n variableDeclaration(\"var\", [\n variableDeclarator(\n namespace,\n assignmentExpression(\n \"=\",\n memberExpression(identifier(\"global\"), namespace),\n objectExpression([]),\n ),\n ),\n ]),\n );\n\n buildHelpers(body, namespace, allowlist);\n\n return tree;\n}\n\nfunction buildModule(allowlist?: Array) {\n const body: t.Statement[] = [];\n const refs = buildHelpers(body, null, allowlist);\n\n body.unshift(\n exportNamedDeclaration(\n null,\n Object.keys(refs).map(name => {\n return exportSpecifier(cloneNode(refs[name]), identifier(name));\n }),\n ),\n );\n\n return program(body, [], \"module\");\n}\n\nfunction buildUmd(allowlist?: Array) {\n const namespace = identifier(\"babelHelpers\");\n\n const body: t.Statement[] = [];\n body.push(\n variableDeclaration(\"var\", [\n variableDeclarator(namespace, identifier(\"global\")),\n ]),\n );\n\n buildHelpers(body, namespace, allowlist);\n\n return program([\n buildUmdWrapper({\n FACTORY_PARAMETERS: identifier(\"global\"),\n BROWSER_ARGUMENTS: assignmentExpression(\n \"=\",\n memberExpression(identifier(\"root\"), namespace),\n objectExpression([]),\n ),\n COMMON_ARGUMENTS: identifier(\"exports\"),\n AMD_ARGUMENTS: arrayExpression([stringLiteral(\"exports\")]),\n FACTORY_BODY: body,\n UMD_ROOT: identifier(\"this\"),\n }),\n ]);\n}\n\nfunction buildVar(allowlist?: Array) {\n const namespace = identifier(\"babelHelpers\");\n\n const body: t.Statement[] = [];\n body.push(\n variableDeclaration(\"var\", [\n variableDeclarator(namespace, objectExpression([])),\n ]),\n );\n const tree = program(body);\n buildHelpers(body, namespace, allowlist);\n body.push(expressionStatement(namespace));\n return tree;\n}\n\nfunction buildHelpers(\n body: t.Statement[],\n namespace: t.Expression,\n allowlist?: Array,\n): Record;\nfunction buildHelpers(\n body: t.Statement[],\n namespace: null,\n allowlist?: Array,\n): Record;\n\nfunction buildHelpers(\n body: t.Statement[],\n namespace: t.Expression | null,\n allowlist?: Array,\n) {\n const getHelperReference = (name: string) => {\n return namespace\n ? memberExpression(namespace, identifier(name))\n : identifier(`_${name}`);\n };\n\n const refs: { [key: string]: t.Identifier | t.MemberExpression } = {};\n helpers.list.forEach(function (name) {\n if (allowlist && !allowlist.includes(name)) return;\n\n const ref = (refs[name] = getHelperReference(name));\n\n const { nodes } = helpers.get(\n name,\n getHelperReference,\n namespace ? null : `_${name}`,\n [],\n namespace\n ? (ast, exportName, mapExportBindingAssignments) => {\n mapExportBindingAssignments(node =>\n assignmentExpression(\"=\", ref, node),\n );\n ast.body.push(\n expressionStatement(\n assignmentExpression(\"=\", ref, identifier(exportName)),\n ),\n );\n }\n : null,\n );\n\n body.push(...nodes);\n });\n return refs;\n}\nexport default function (\n allowlist?: Array,\n outputType: \"global\" | \"module\" | \"umd\" | \"var\" = \"global\",\n) {\n let tree: t.Program;\n\n const build = {\n global: buildGlobal,\n module: buildModule,\n umd: buildUmd,\n var: buildVar,\n }[outputType];\n\n if (build) {\n tree = build(allowlist);\n } else {\n throw new Error(`Unsupported output type ${outputType}`);\n }\n\n return generator(tree).code;\n}\n"],"mappings":";;;;;;AAAA,SAAAA,QAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,OAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,WAAA;EAAA,MAAAF,IAAA,GAAAC,OAAA;EAAAC,UAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAG,UAAA;EAAA,MAAAH,IAAA,GAAAC,OAAA;EAAAE,SAAA,YAAAA,CAAA;IAAA,OAAAH,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAI,GAAA;EAAA,MAAAJ,IAAA,GAAAC,OAAA;EAAAG,EAAA,YAAAA,CAAA;IAAA,OAAAJ,IAAA;EAAA;EAAA,OA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D,OAAO,CAAD,CAAC,CAAC0D,GAAG,CAC3Bf,IAAI,EACJS,kBAAkB,EAClBrB,SAAS,GAAG,IAAI,GAAG,IAAIY,IAAI,EAAE,EAC7B,EAAE,EACFZ,SAAS,GACL,CAAC4B,GAAG,EAAEC,UAAU,EAAEC,2BAA2B,KAAK;MAChDA,2BAA2B,CAACC,IAAI,IAC9BvD,oBAAoB,CAAC,GAAG,EAAEiD,GAAG,EAAEM,IAAI,CACrC,CAAC;MACDH,GAAG,CAAC3B,IAAI,CAACG,IAAI,CACXpB,mBAAmB,CACjBR,oBAAoB,CAAC,GAAG,EAAEiD,GAAG,EAAEvC,UAAU,CAAC2C,UAAU,CAAC,CACvD,CACF,CAAC;IACH,CAAC,GACD,IACN,CAAC;IAED5B,IAAI,CAACG,IAAI,CAAC,GAAGsB,KAAK,CAAC;EACrB,CAAC,CAAC;EACF,OAAOnB,IAAI;AACb;AACe,SAAAyB,SACbjC,SAAyB,EACzBkC,UAA+C,GAAG,QAAQ,EAC1D;EACA,IAAI9B,IAAe;EAEnB,MAAM+B,KAAK,GAAG;IACZC,MAAM,EAAErC,WAAW;IACnBsC,MAAM,EAAE9B,WAAW;IACnB+B,GAAG,EAAExB,QAAQ;IACbyB,GAAG,EAAElB;EACP,CAAC,CAACa,UAAU,CAAC;EAEb,IAAIC,KAAK,EAAE;IACT/B,IAAI,GAAG+B,KAAK,CAACnC,SAAS,CAAC;EACzB,CAAC,MAAM;IACL,MAAM,IAAIwC,KAAK,CAAC,2BAA2BN,UAAU,EAAE,CAAC;EAC1D;EAEA,OAAO,IAAAO,oBAAS,EAACrC,IAAI,CAAC,CAACsC,IAAI;AAC7B;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transform-ast.js b/node_modules/@babel/core/lib/transform-ast.js new file mode 100644 index 0000000..0a86cd1 --- /dev/null +++ b/node_modules/@babel/core/lib/transform-ast.js @@ -0,0 +1,50 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.transformFromAst = void 0; +exports.transformFromAstAsync = transformFromAstAsync; +exports.transformFromAstSync = transformFromAstSync; +function _gensync() { + const data = require("gensync"); + _gensync = function () { + return data; + }; + return data; +} +var _index = require("./config/index.js"); +var _index2 = require("./transformation/index.js"); +var _rewriteStackTrace = require("./errors/rewrite-stack-trace.js"); +const transformFromAstRunner = _gensync()(function* (ast, code, opts) { + const config = yield* (0, _index.default)(opts); + if (config === null) return null; + if (!ast) throw new Error("No AST given"); + return yield* (0, _index2.run)(config, code, ast); +}); +const transformFromAst = exports.transformFromAst = function transformFromAst(ast, code, optsOrCallback, maybeCallback) { + let opts; + let callback; + if (typeof optsOrCallback === "function") { + callback = optsOrCallback; + opts = undefined; + } else { + opts = optsOrCallback; + callback = maybeCallback; + } + if (callback === undefined) { + { + return (0, _rewriteStackTrace.beginHiddenCallStack)(transformFromAstRunner.sync)(ast, code, opts); + } + } + (0, _rewriteStackTrace.beginHiddenCallStack)(transformFromAstRunner.errback)(ast, code, opts, callback); +}; +function transformFromAstSync(...args) { + return (0, _rewriteStackTrace.beginHiddenCallStack)(transformFromAstRunner.sync)(...args); +} +function transformFromAstAsync(...args) { + return (0, _rewriteStackTrace.beginHiddenCallStack)(transformFromAstRunner.async)(...args); +} +0 && 0; + +//# sourceMappingURL=transform-ast.js.map diff --git a/node_modules/@babel/core/lib/transform-ast.js.map b/node_modules/@babel/core/lib/transform-ast.js.map new file mode 100644 index 0000000..ff14834 --- /dev/null +++ b/node_modules/@babel/core/lib/transform-ast.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_gensync","data","require","_index","_index2","_rewriteStackTrace","transformFromAstRunner","gensync","ast","code","opts","config","loadConfig","Error","run","transformFromAst","exports","optsOrCallback","maybeCallback","callback","undefined","beginHiddenCallStack","sync","errback","transformFromAstSync","args","transformFromAstAsync","async"],"sources":["../src/transform-ast.ts"],"sourcesContent":["import gensync, { type Handler } from \"gensync\";\n\nimport loadConfig from \"./config/index.ts\";\nimport type { InputOptions, ResolvedConfig } from \"./config/index.ts\";\nimport { run } from \"./transformation/index.ts\";\nimport type * as t from \"@babel/types\";\n\nimport { beginHiddenCallStack } from \"./errors/rewrite-stack-trace.ts\";\n\nimport type { FileResult, FileResultCallback } from \"./transformation/index.ts\";\ntype AstRoot = t.File | t.Program;\n\ntype TransformFromAst = {\n (ast: AstRoot, code: string, callback: FileResultCallback): void;\n (\n ast: AstRoot,\n code: string,\n opts: InputOptions | undefined | null,\n callback: FileResultCallback,\n ): void;\n (ast: AstRoot, code: string, opts?: InputOptions | null): FileResult | null;\n};\n\nconst transformFromAstRunner = gensync(function* (\n ast: AstRoot,\n code: string,\n opts: InputOptions | undefined | null,\n): Handler {\n const config: ResolvedConfig | null = yield* loadConfig(opts);\n if (config === null) return null;\n\n if (!ast) throw new Error(\"No AST given\");\n\n return yield* run(config, code, ast);\n});\n\nexport const transformFromAst: TransformFromAst = function transformFromAst(\n ast,\n code,\n optsOrCallback?: InputOptions | null | undefined | FileResultCallback,\n maybeCallback?: FileResultCallback,\n) {\n let opts: InputOptions | undefined | null;\n let callback: FileResultCallback | undefined;\n if (typeof optsOrCallback === \"function\") {\n callback = optsOrCallback;\n opts = undefined;\n } else {\n opts = optsOrCallback;\n callback = maybeCallback;\n }\n\n if (callback === undefined) {\n if (process.env.BABEL_8_BREAKING) {\n throw new Error(\n \"Starting from Babel 8.0.0, the 'transformFromAst' function expects a callback. If you need to call it synchronously, please use 'transformFromAstSync'.\",\n );\n } else {\n // console.warn(\n // \"Starting from Babel 8.0.0, the 'transformFromAst' function will expect a callback. If you need to call it synchronously, please use 'transformFromAstSync'.\",\n // );\n return beginHiddenCallStack(transformFromAstRunner.sync)(ast, code, opts);\n }\n }\n\n beginHiddenCallStack(transformFromAstRunner.errback)(\n ast,\n code,\n opts,\n callback,\n );\n};\n\nexport function transformFromAstSync(\n ...args: Parameters\n) {\n return beginHiddenCallStack(transformFromAstRunner.sync)(...args);\n}\n\nexport function transformFromAstAsync(\n ...args: Par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,CAClDf,GAAG,EACHC,IAAI,EACJC,IAAI,EACJS,QACF,CAAC;AACH,CAAC;AAEM,SAASK,oBAAoBA,CAClC,GAAGC,IAAoD,EACvD;EACA,OAAO,IAAAJ,uCAAoB,EAACf,sBAAsB,CAACgB,IAAI,CAAC,CAAC,GAAGG,IAAI,CAAC;AACnE;AAEO,SAASC,qBAAqBA,CACnC,GAAGD,IAAqD,EACxD;EACA,OAAO,IAAAJ,uCAAoB,EAACf,sBAAsB,CAACqB,KAAK,CAAC,CAAC,GAAGF,IAAI,CAAC;AACpE;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transform-file-browser.js b/node_modules/@babel/core/lib/transform-file-browser.js new file mode 100644 index 0000000..8576809 --- /dev/null +++ b/node_modules/@babel/core/lib/transform-file-browser.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.transformFile = void 0; +exports.transformFileAsync = transformFileAsync; +exports.transformFileSync = transformFileSync; +const transformFile = exports.transformFile = function transformFile(filename, opts, callback) { + if (typeof opts === "function") { + callback = opts; + } + callback(new Error("Transforming files is not supported in browsers"), null); +}; +function transformFileSync() { + throw new Error("Transforming files is not supported in browsers"); +} +function transformFileAsync() { + return Promise.reject(new Error("Transforming files is not supported in browsers")); +} +0 && 0; + +//# sourceMappingURL=transform-file-browser.js.map diff --git a/node_modules/@babel/core/lib/transform-file-browser.js.map b/node_modules/@babel/core/lib/transform-file-browser.js.map new file mode 100644 index 0000000..f0c0614 --- /dev/null +++ b/node_modules/@babel/core/lib/transform-file-browser.js.map @@ -0,0 +1 @@ +{"version":3,"names":["transformFile","exports","filename","opts","callback","Error","transformFileSync","transformFileAsync","Promise","reject"],"sources":["../src/transform-file-browser.ts"],"sourcesContent":["// duplicated from transform-file so we do not have to import anything here\ntype TransformFile = {\n (filename: string, callback: (error: Error, file: null) => void): void;\n (\n filename: string,\n opts: any,\n callback: (error: Error, file: null) => void,\n ): void;\n};\n\nexport const transformFile: TransformFile = function transformFile(\n filename,\n opts,\n callback?: (error: Error, file: null) => void,\n) {\n if (typeof opts === \"function\") {\n callback = opts;\n }\n\n callback(new Error(\"Transforming files is not supported in browsers\"), null);\n};\n\nexport function transformFileSync(): never {\n throw new Error(\"Transforming files is not supported in browsers\");\n}\n\nexport function transformFileAsync() {\n return Promise.reject(\n new Error(\"Transforming files is not supported in browsers\"),\n );\n}\n"],"mappings":";;;;;;;;AAUO,MAAMA,aAA4B,GAAAC,OAAA,CAAAD,aAAA,GAAG,SAASA,aAAaA,CAChEE,QAAQ,EACRC,IAAI,EACJC,QAA6C,EAC7C;EACA,IAAI,OAAOD,IAAI,KAAK,UAAU,EAAE;IAC9BC,QAAQ,GAAGD,IAAI;EACjB;EAEAC,QAAQ,CAAC,IAAIC,KAAK,CAAC,iDAAiD,CAAC,EAAE,IAAI,CAAC;AAC9E,CAAC;AAEM,SAASC,iBAAiBA,CAAA,EAAU;EACzC,MAAM,IAAID,KAAK,CAAC,iDAAiD,CAAC;AACpE;AAEO,SAASE,kBAAkBA,CAAA,EAAG;EACnC,OAAOC,OAAO,CAACC,MAAM,CACnB,IAAIJ,KAAK,CAAC,iDAAiD,CAC7D,CAAC;AACH;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transform-file.js b/node_modules/@babel/core/lib/transform-file.js new file mode 100644 index 0000000..ce7f9f9 --- /dev/null +++ b/node_modules/@babel/core/lib/transform-file.js @@ -0,0 +1,40 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.transformFile = transformFile; +exports.transformFileAsync = transformFileAsync; +exports.transformFileSync = transformFileSync; +function _gensync() { + const data = require("gensync"); + _gensync = function () { + return data; + }; + return data; +} +var _index = require("./config/index.js"); +var _index2 = require("./transformation/index.js"); +var fs = require("./gensync-utils/fs.js"); +({}); +const transformFileRunner = _gensync()(function* (filename, opts) { + const options = Object.assign({}, opts, { + filename + }); + const config = yield* (0, _index.default)(options); + if (config === null) return null; + const code = yield* fs.readFile(filename, "utf8"); + return yield* (0, _index2.run)(config, code); +}); +function transformFile(...args) { + transformFileRunner.errback(...args); +} +function transformFileSync(...args) { + return transformFileRunner.sync(...args); +} +function transformFileAsync(...args) { + return transformFileRunner.async(...args); +} +0 && 0; + +//# sourceMappingURL=transform-file.js.map diff --git a/node_modules/@babel/core/lib/transform-file.js.map b/node_modules/@babel/core/lib/transform-file.js.map new file mode 100644 index 0000000..aab7ce6 --- /dev/null +++ b/node_modules/@babel/core/lib/transform-file.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_gensync","data","require","_index","_index2","fs","transformFileRunner","gensync","filename","opts","options","Object","assign","config","loadConfig","code","readFile","run","transformFile","args","errback","transformFileSync","sync","transformFileAsync","async"],"sources":["../src/transform-file.ts"],"sourcesContent":["import gensync, { type Handler } from \"gensync\";\n\nimport loadConfig from \"./config/index.ts\";\nimport type { InputOptions, ResolvedConfig } from \"./config/index.ts\";\nimport { run } from \"./transformation/index.ts\";\nimport type { FileResult, FileResultCallback } from \"./transformation/index.ts\";\nimport * as fs from \"./gensync-utils/fs.ts\";\n\ntype transformFileBrowserType = typeof import(\"./transform-file-browser\");\ntype transformFileType = typeof import(\"./transform-file\");\n\n// Kind of gross, but essentially asserting that the exports of this module are the same as the\n// exports of transform-file-browser, since this file may be replaced at bundle time with\n// transform-file-browser.\n({}) as any as transformFileBrowserType as transformFileType;\n\nconst transformFileRunner = gensync(function* (\n filename: string,\n opts?: InputOptions,\n): Handler {\n const options = { ...opts, filename };\n\n const config: ResolvedConfig | null = yield* loadConfig(options);\n if (config === null) return null;\n\n const code = yield* fs.readFile(filename, \"utf8\");\n return yield* run(config, code);\n});\n\n// @ts-expect-error TS doesn't detect that this signature is compatible\nexport function transformFile(\n filename: string,\n callback: FileResultCallback,\n): void;\nexport function transformFile(\n filename: string,\n opts: InputOptions | undefined | null,\n callback: FileResultCallback,\n): void;\nexport function transformFile(\n ...args: Parameters\n) {\n transformFileRunner.errback(...args);\n}\n\nexport function transformFileSync(\n ...args: Parameters\n) {\n return transformFileRunner.sync(...args);\n}\nexport function transformFileAsync(\n ...args: Parameters\n) {\n return transformFileRunner.async(...args);\n}\n"],"mappings":";;;;;;;;AAAA,SAAAA,SAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,QAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,IAAAE,MAAA,GAAAD,OAAA;AAEA,IAAAE,OAAA,GAAAF,OAAA;AAEA,IAAAG,EAAA,GAAAH,OAAA;AAQA,CAAC,CAAC,CAAC;AAEH,MAAMI,mBAAmB,GAAGC,SAAMA,CAAC,CAAC,WAClCC,QAAgB,EAChBC,IAAmB,EACS;EAC5B,MAAMC,OAAO,GAAAC,MAAA,CAAAC,MAAA,KAAQH,IAAI;IAAED;EAAQ,EAAE;EAErC,MAAMK,MAA6B,GAAG,OAAO,IAAAC,cAAU,EAACJ,OAAO,CAAC;EAChE,IAAIG,MAAM,KAAK,IAAI,EAAE,OAAO,IAAI;EAEhC,MAAME,IAAI,GAAG,OAAOV,EAAE,CAACW,QAAQ,CAACR,QAAQ,EAAE,MAAM,CAAC;EACjD,OAAO,OAAO,IAAAS,WAAG,EAACJ,MAAM,EAAEE,IAAI,CAAC;AACjC,CAAC,CAAC;AAYK,SAASG,aAAaA,CAC3B,GAAGC,IAAoD,EACvD;EACAb,mBAAmB,CAACc,OAAO,CAAC,GAAGD,IAAI,CAAC;AACtC;AAEO,SAASE,iBAAiBA,CAC/B,GAAGF,IAAiD,EACpD;EACA,OAAOb,mBAAmB,CAACgB,IAAI,CAAC,GAAGH,IAAI,CAAC;AAC1C;AACO,SAASI,kBAAkBA,CAChC,GAAGJ,IAAkD,EACrD;EACA,OAAOb,mBAAmB,CAACkB,KAAK,CAAC,GAAGL,IAAI,CAAC;AAC3C;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transform.js b/node_modules/@babel/core/lib/transform.js new file mode 100644 index 0000000..be55705 --- /dev/null +++ b/node_modules/@babel/core/lib/transform.js @@ -0,0 +1,49 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.transform = void 0; +exports.transformAsync = transformAsync; +exports.transformSync = transformSync; +function _gensync() { + const data = require("gensync"); + _gensync = function () { + return data; + }; + return data; +} +var _index = require("./config/index.js"); +var _index2 = require("./transformation/index.js"); +var _rewriteStackTrace = require("./errors/rewrite-stack-trace.js"); +const transformRunner = _gensync()(function* transform(code, opts) { + const config = yield* (0, _index.default)(opts); + if (config === null) return null; + return yield* (0, _index2.run)(config, code); +}); +const transform = exports.transform = function transform(code, optsOrCallback, maybeCallback) { + let opts; + let callback; + if (typeof optsOrCallback === "function") { + callback = optsOrCallback; + opts = undefined; + } else { + opts = optsOrCallback; + callback = maybeCallback; + } + if (callback === undefined) { + { + return (0, _rewriteStackTrace.beginHiddenCallStack)(transformRunner.sync)(code, opts); + } + } + (0, _rewriteStackTrace.beginHiddenCallStack)(transformRunner.errback)(code, opts, callback); +}; +function transformSync(...args) { + return (0, _rewriteStackTrace.beginHiddenCallStack)(transformRunner.sync)(...args); +} +function transformAsync(...args) { + return (0, _rewriteStackTrace.beginHiddenCallStack)(transformRunner.async)(...args); +} +0 && 0; + +//# sourceMappingURL=transform.js.map diff --git a/node_modules/@babel/core/lib/transform.js.map b/node_modules/@babel/core/lib/transform.js.map new file mode 100644 index 0000000..3a7832a --- /dev/null +++ b/node_modules/@babel/core/lib/transform.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_gensync","data","require","_index","_index2","_rewriteStackTrace","transformRunner","gensync","transform","code","opts","config","loadConfig","run","exports","optsOrCallback","maybeCallback","callback","undefined","beginHiddenCallStack","sync","errback","transformSync","args","transformAsync","async"],"sources":["../src/transform.ts"],"sourcesContent":["import gensync, { type Handler } from \"gensync\";\n\nimport loadConfig from \"./config/index.ts\";\nimport type { InputOptions, ResolvedConfig } from \"./config/index.ts\";\nimport { run } from \"./transformation/index.ts\";\n\nimport type { FileResult, FileResultCallback } from \"./transformation/index.ts\";\nimport { beginHiddenCallStack } from \"./errors/rewrite-stack-trace.ts\";\n\nexport type { FileResult } from \"./transformation/index.ts\";\n\ntype Transform = {\n (code: string, callback: FileResultCallback): void;\n (\n code: string,\n opts: InputOptions | undefined | null,\n callback: FileResultCallback,\n ): void;\n (code: string, opts?: InputOptions | null): FileResult | null;\n};\n\nconst transformRunner = gensync(function* transform(\n code: string,\n opts?: InputOptions,\n): Handler {\n const config: ResolvedConfig | null = yield* loadConfig(opts);\n if (config === null) return null;\n\n return yield* run(config, code);\n});\n\nexport const transform: Transform = function transform(\n code,\n optsOrCallback?: InputOptions | null | undefined | FileResultCallback,\n maybeCallback?: FileResultCallback,\n) {\n let opts: InputOptions | undefined | null;\n let callback: FileResultCallback | undefined;\n if (typeof optsOrCallback === \"function\") {\n callback = optsOrCallback;\n opts = undefined;\n } else {\n opts = optsOrCallback;\n callback = maybeCallback;\n }\n\n if (callback === undefined) {\n if (process.env.BABEL_8_BREAKING) {\n throw new Error(\n \"Starting from Babel 8.0.0, the 'transform' function expects a callback. If you need to call it synchronously, please use 'transformSync'.\",\n );\n } else {\n // console.warn(\n // \"Starting from Babel 8.0.0, the 'transform' function will expect a callback. If you need to call it synchronously, please use 'transformSync'.\",\n // );\n return beginHiddenCallStack(transformRunner.sync)(code, opts);\n }\n }\n\n beginHiddenCallStack(transformRunner.errback)(code, opts, callback);\n};\n\nexport function transformSync(\n ...args: Parameters\n) {\n return beginHiddenCallStack(transformRunner.sync)(...args);\n}\nexport function transformAsync(\n ...args: Parameters\n) {\n return beginHiddenCallStack(transformRunner.async)(...args);\n}\n"],"mappings":";;;;;;;;AAAA,SAAAA,SAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,QAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,IAAAE,MAAA,GAAAD,OAAA;AA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 No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/block-hoist-plugin.js b/node_modules/@babel/core/lib/transformation/block-hoist-plugin.js new file mode 100644 index 0000000..ec22ee3 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/block-hoist-plugin.js @@ -0,0 +1,84 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = loadBlockHoistPlugin; +function _traverse() { + const data = require("@babel/traverse"); + _traverse = function () { + return data; + }; + return data; +} +var _plugin = require("../config/plugin.js"); +let LOADED_PLUGIN; +const blockHoistPlugin = { + name: "internal.blockHoist", + visitor: { + Block: { + exit({ + node + }) { + node.body = performHoisting(node.body); + } + }, + SwitchCase: { + exit({ + node + }) { + node.consequent = performHoisting(node.consequent); + } + } + } +}; +function performHoisting(body) { + let max = Math.pow(2, 30) - 1; + let hasChange = false; + for (let i = 0; i < body.length; i++) { + const n = body[i]; + const p = priority(n); + if (p > max) { + hasChange = true; + break; + } + max = p; + } + if (!hasChange) return body; + return stableSort(body.slice()); +} +function loadBlockHoistPlugin() { + if (!LOADED_PLUGIN) { + LOADED_PLUGIN = new _plugin.default(Object.assign({}, blockHoistPlugin, { + visitor: _traverse().default.explode(blockHoistPlugin.visitor) + }), {}); + } + return LOADED_PLUGIN; +} +function priority(bodyNode) { + const priority = bodyNode == null ? void 0 : bodyNode._blockHoist; + if (priority == null) return 1; + if (priority === true) return 2; + return priority; +} +function stableSort(body) { + const buckets = Object.create(null); + for (let i = 0; i < body.length; i++) { + const n = body[i]; + const p = priority(n); + const bucket = buckets[p] || (buckets[p] = []); + bucket.push(n); + } + const keys = Object.keys(buckets).map(k => +k).sort((a, b) => b - a); + let index = 0; + for (const key of keys) { + const bucket = buckets[key]; + for (const n of bucket) { + body[index++] = n; + } + } + return body; +} +0 && 0; + +//# sourceMappingURL=block-hoist-plugin.js.map diff --git a/node_modules/@babel/core/lib/transformation/block-hoist-plugin.js.map b/node_modules/@babel/core/lib/transformation/block-hoist-plugin.js.map new file mode 100644 index 0000000..028e36a --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/block-hoist-plugin.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_traverse","data","require","_plugin","LOADED_PLUGIN","blockHoistPlugin","name","visitor","Block","exit","node","body","performHoisting","SwitchCase","consequent","max","Math","pow","hasChange","i","length","n","p","priority","stableSort","slice","loadBlockHoistPlugin","Plugin","Object","assign","traverse","explode","bodyNode","_blockHoist","buckets","create","bucket","push","keys","map","k","sort","a","b","index","key"],"sources":["../../src/transformation/block-hoist-plugin.ts"],"sourcesContent":["import traverse from \"@babel/traverse\";\nimport type { Statement } from \"@babel/types\";\nimport type { PluginObject } from \"../config/index.ts\";\nimport Plugin from \"../config/plugin.ts\";\n\nlet LOADED_PLUGIN: Plugin | void;\n\nconst blockHoistPlugin: PluginObject = {\n /**\n * [Please add a description.]\n *\n * Priority:\n *\n * - 0 We want this to be at the **very** bottom\n * - 1 Default node position\n * - 2 Priority over normal nodes\n * - 3 We want this to be at the **very** top\n * - 4 Reserved for the helpers used to implement module imports.\n */\n\n name: \"internal.blockHoist\",\n\n visitor: {\n Block: {\n exit({ node }) {\n node.body = performHoisting(node.body);\n },\n },\n SwitchCase: {\n exit({ node }) {\n // In case statements, hoisting is difficult to perform correctly due to\n // functions that are declared and referenced in different blocks.\n // Nevertheless, hoisting the statements *inside* of each case should at\n // least mitigate the failure cases.\n node.consequent = performHoisting(node.consequent);\n },\n },\n },\n};\n\nfunction performHoisting(body: Statement[]): Statement[] {\n // Largest SMI\n let max = 2 ** 30 - 1;\n let hasChange = false;\n for (let i = 0; i < body.length; i++) {\n const n = body[i];\n const p = priority(n);\n if (p > max) {\n hasChange = true;\n break;\n }\n max = p;\n }\n if (!hasChange) return body;\n\n // My kingdom for a stable sort!\n return stableSort(body.slice());\n}\n\nexport default function loadBlockHoistPlugin(): Plugin {\n if (!LOADED_PLUGIN) {\n // cache the loaded blockHoist plugin plugin\n LOADED_PLUGIN = new Plugin(\n {\n ...blockHoistPlugin,\n visitor: traverse.explode(blockHoistPlugin.visitor),\n },\n {},\n );\n }\n\n return LOADED_PLUGIN;\n}\n\nfunction priority(bodyNode: Statement & { _blockHoist?: number | true }) {\n const priority = bodyNode?._blockHoist;\n if (priority == null) return 1;\n if (priority === true) return 2;\n return priority;\n}\n\nfunction stableSort(body: Statement[]) {\n // By default, we use priorities of 0-4.\n const buckets = Object.create(null);\n\n // By collecting into buckets, we can guarantee a stable sort.\n for (let i = 0; i < body.length; i++) {\n const n = body[i];\n const p = priority(n);\n\n // In case some plugin is setting an unexpected priority.\n const bucket = buckets[p] || (buckets[p] = []);\n bucket.push(n);\n }\n\n // Sort our keys in descending order. Keys are unique, so we don't have to\n // worry about stability.\n const keys = Object.keys(buckets)\n .map(k => +k)\n .sort((a, b) => b - a);\n\n let index = 0;\n for (const key of keys) {\n const bucket = buckets[key];\n for (const n of bucket) {\n body[index++] = n;\n }\n }\n return body;\n}\n"],"mappings":";;;;;;AAAA,SAAAA,UAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,SAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAGA,IAAAE,OAAA,GAAAD,OAAA;AAEA,IAAIE,aAA4B;AAEhC,MAAMC,gBAA8B,GAAG;EAarCC,IAAI,EAAE,qBAAqB;EAE3BC,OAAO,EAAE;IACPC,KAAK,EAAE;MACLC,IAAIA,CAAC;QAAEC;MAAK,CAAC,EAAE;QACbA,IAAI,CAACC,IAAI,GAAGC,eAAe,CAACF,IAAI,CAACC,IAAI,CAAC;MACxC;IACF,CAAC;IACDE,UAAU,EAAE;MACVJ,IAAIA,CAAC;QAAEC;MAAK,CAAC,EAAE;QAKbA,IAAI,CAACI,UAAU,GAAGF,eAAe,CAACF,IAAI,CAACI,UAAU,CAAC;MACpD;IACF;EACF;AACF,CAAC;AAED,SAASF,eAAeA,CAACD,IAAiB,EAAe;EAEvD,IAAII,GAAG,GAAGC,IAAA,CA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AACQ,CAAC,CAAC;IACjB,MAAMG,CAAC,GAAGC,QAAQ,CAACF,CAAC,CAAC;IAGrB,MAAMe,MAAM,GAAGF,OAAO,CAACZ,CAAC,CAAC,KAAKY,OAAO,CAACZ,CAAC,CAAC,GAAG,EAAE,CAAC;IAC9Cc,MAAM,CAACC,IAAI,CAAChB,CAAC,CAAC;EAChB;EAIA,MAAMiB,IAAI,GAAGV,MAAM,CAACU,IAAI,CAACJ,OAAO,CAAC,CAC9BK,GAAG,CAACC,CAAC,IAAI,CAACA,CAAC,CAAC,CACZC,IAAI,CAAC,CAACC,CAAC,EAAEC,CAAC,KAAKA,CAAC,GAAGD,CAAC,CAAC;EAExB,IAAIE,KAAK,GAAG,CAAC;EACb,KAAK,MAAMC,GAAG,IAAIP,IAAI,EAAE;IACtB,MAAMF,MAAM,GAAGF,OAAO,CAACW,GAAG,CAAC;IAC3B,KAAK,MAAMxB,CAAC,IAAIe,MAAM,EAAE;MACtBzB,IAAI,CAACiC,KAAK,EAAE,CAAC,GAAGvB,CAAC;IACnB;EACF;EACA,OAAOV,IAAI;AACb;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/file/babel-7-helpers.cjs b/node_modules/@babel/core/lib/transformation/file/babel-7-helpers.cjs new file mode 100644 index 0000000..a532ff1 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/file/babel-7-helpers.cjs @@ -0,0 +1,4 @@ +exports.getModuleName = () => require("@babel/helper-module-transforms").getModuleName; +0 && 0; + +//# sourceMappingURL=babel-7-helpers.cjs.map diff --git a/node_modules/@babel/core/lib/transformation/file/babel-7-helpers.cjs.map b/node_modules/@babel/core/lib/transformation/file/babel-7-helpers.cjs.map new file mode 100644 index 0000000..bfc0d1b --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/file/babel-7-helpers.cjs.map @@ -0,0 +1 @@ +{"version":3,"names":["exports","getModuleName","require"],"sources":["../../../src/transformation/file/babel-7-helpers.cjs"],"sourcesContent":["// TODO(Babel 8): Remove this file\n\nexports.getModuleName = () =>\n require(\"@babel/helper-module-transforms\").getModuleName;\n"],"mappings":"AAEAA,OAAO,CAACC,aAAa,GAAG,MACtBC,OAAO,CAAC,iCAAiC,CAAC,CAACD,aAAa;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/file/file.js b/node_modules/@babel/core/lib/transformation/file/file.js new file mode 100644 index 0000000..61caa17 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/file/file.js @@ -0,0 +1,214 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +function helpers() { + const data = require("@babel/helpers"); + helpers = function () { + return data; + }; + return data; +} +function _traverse() { + const data = require("@babel/traverse"); + _traverse = function () { + return data; + }; + return data; +} +function _codeFrame() { + const data = require("@babel/code-frame"); + _codeFrame = function () { + return data; + }; + return data; +} +function _t() { + const data = require("@babel/types"); + _t = function () { + return data; + }; + return data; +} +function _semver() { + const data = require("semver"); + _semver = function () { + return data; + }; + return data; +} +var babel7 = _interopRequireWildcard(require("./babel-7-helpers.cjs"), true); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +const { + cloneNode, + interpreterDirective +} = _t(); +const errorVisitor = { + enter(path, state) { + const loc = path.node.loc; + if (loc) { + state.loc = loc; + path.stop(); + } + } +}; +class File { + constructor(options, { + code, + ast, + inputMap + }) { + this._map = new Map(); + this.opts = void 0; + this.declarations = {}; + this.path = void 0; + this.ast = void 0; + this.scope = void 0; + this.metadata = {}; + this.code = ""; + this.inputMap = void 0; + this.hub = { + file: this, + getCode: () => this.code, + getScope: () => this.scope, + addHelper: this.addHelper.bind(this), + buildError: this.buildCodeFrameError.bind(this) + }; + this.opts = options; + this.code = code; + this.ast = ast; + this.inputMap = inputMap; + this.path = _traverse().NodePath.get({ + hub: this.hub, + parentPath: null, + parent: this.ast, + container: this.ast, + key: "program" + }).setContext(); + this.scope = this.path.scope; + } + get shebang() { + const { + interpreter + } = this.path.node; + return interpreter ? interpreter.value : ""; + } + set shebang(value) { + if (value) { + this.path.get("interpreter").replaceWith(interpreterDirective(value)); + } else { + this.path.get("interpreter").remove(); + } + } + set(key, val) { + { + if (key === "helpersNamespace") { + throw new Error("Babel 7.0.0-beta.56 has dropped support for the 'helpersNamespace' utility." + "If you are using @babel/plugin-external-helpers you will need to use a newer " + "version than the one you currently have installed. " + "If you have your own implementation, you'll want to explore using 'helperGenerator' " + "alongside 'file.availableHelper()'."); + } + } + this._map.set(key, val); + } + get(key) { + return this._map.get(key); + } + has(key) { + return this._map.has(key); + } + availableHelper(name, versionRange) { + let minVersion; + try { + minVersion = helpers().minVersion(name); + } catch (err) { + if (err.code !== "BABEL_HELPER_UNKNOWN") throw err; + return false; + } + if (typeof versionRange !== "string") return true; + if (_semver().valid(versionRange)) versionRange = `^${versionRange}`; + { + return !_semver().intersects(`<${minVersion}`, versionRange) && !_semver().intersects(`>=8.0.0`, versionRange); + } + } + addHelper(name) { + const declar = this.declarations[name]; + if (declar) return cloneNode(declar); + const generator = this.get("helperGenerator"); + if (generator) { + const res = generator(name); + if (res) return res; + } + helpers().minVersion(name); + const uid = this.declarations[name] = this.scope.generateUidIdentifier(name); + const dependencies = {}; + for (const dep of helpers().getDependencies(name)) { + dependencies[dep] = this.addHelper(dep); + } + const { + nodes, + globals + } = helpers().get(name, dep => dependencies[dep], uid.name, Object.keys(this.scope.getAllBindings())); + globals.forEach(name => { + if (this.path.scope.hasBinding(name, true)) { + this.path.scope.rename(name); + } + }); + nodes.forEach(node => { + node._compact = true; + }); + const added = this.path.unshiftContainer("body", nodes); + for (const path of added) { + if (path.isVariableDeclaration()) this.scope.registerDeclaration(path); + } + return uid; + } + buildCodeFrameError(node, msg, _Error = SyntaxError) { + let loc = node == null ? void 0 : node.loc; + if (!loc && node) { + const state = { + loc: null + }; + (0, _traverse().default)(node, errorVisitor, this.scope, state); + loc = state.loc; + let txt = "This is an error on an internal node. Probably an internal error."; + if (loc) txt += " Location has been estimated."; + msg += ` (${txt})`; + } + if (loc) { + const { + highlightCode = true + } = this.opts; + msg += "\n" + (0, _codeFrame().codeFrameColumns)(this.code, { + start: { + line: loc.start.line, + column: loc.start.column + 1 + }, + end: loc.end && loc.start.line === loc.end.line ? { + line: loc.end.line, + column: loc.end.column + 1 + } : undefined + }, { + highlightCode + }); + } + return new _Error(msg); + } +} +exports.default = File; +{ + File.prototype.addImport = function addImport() { + throw new Error("This API has been removed. If you're looking for this " + "functionality in Babel 7, you should import the " + "'@babel/helper-module-imports' module and use the functions exposed " + " from that module, such as 'addNamed' or 'addDefault'."); + }; + File.prototype.addTemplateObject = function addTemplateObject() { + throw new Error("This function has been moved into the template literal transform itself."); + }; + { + File.prototype.getModuleName = function getModuleName() { + return babel7.getModuleName()(this.opts, this.opts); + }; + } +} +0 && 0; + +//# sourceMappingURL=file.js.map diff --git a/node_modules/@babel/core/lib/transformation/file/file.js.map b/node_modules/@babel/core/lib/transformation/file/file.js.map new file mode 100644 index 0000000..41012b4 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/file/file.js.map @@ -0,0 +1 @@ +{"version":3,"names":["helpers","data","require","_traverse","_codeFrame","_t","_semver","babel7","_interopRequireWildcard","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","hasOwnProperty","call","i","set","cloneNode","interpreterDirective","errorVisitor","enter","path","state","loc","node","stop","File","constructor","options","code","ast","inputMap","_map","Map","opts","declarations","scope","metadata","hub","file","getCode","getScope","addHelper","bind","buildError","buildCodeFrameError","NodePath","parentPath","parent","container","key","setContext","shebang","interpreter","value","replaceWith","remove","val","Error","availableHelper","name","versionRange","minVersion","err","semver","valid","intersects","declar","generator","res","uid","generateUidIdentifier","dependencies","dep","getDependencies","nodes","globals","keys","getAllBindings","forEach","hasBinding","rename","_compact","added","unshiftContainer","isVariableDeclaration","registerDeclaration","msg","_Error","SyntaxError","traverse","txt","highlightCode","codeFrameColumns","start","line","column","end","undefined","exports","prototype","addImport","addTemplateObject","getModuleName"],"sources":["../../../src/transformation/file/file.ts"],"sourcesContent":["import * as helpers from \"@babel/helpers\";\nimport { NodePath } from \"@babel/traverse\";\nimport type { HubInterface, Visitor, Scope } from \"@babel/traverse\";\nimport { codeFrameColumns } from \"@babel/code-frame\";\nimport traverse from \"@babel/traverse\";\nimport { cloneNode, interpreterDirective } from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport semver from \"semver\";\n\nimport type { NormalizedFile } from \"../normalize-file.ts\";\n\n// @ts-expect-error This file is `any`\nimport * as babel7 from \"./babel-7-helpers.cjs\";\n\nconst errorVisitor: Visitor<{ loc: t.SourceLocation | null }> = {\n enter(path, state) {\n const loc = path.node.loc;\n if (loc) {\n state.loc = loc;\n path.stop();\n }\n },\n};\n\nexport default class File {\n _map: Map = new Map();\n opts: { [key: string]: any };\n declarations: { [key: string]: t.Identifier } = {};\n path: NodePath;\n ast: t.File;\n scope: Scope;\n metadata: { [key: string]: any } = {};\n code: string = \"\";\n inputMap: any;\n\n hub: HubInterface & { file: File } = {\n // keep it for the usage in babel-core, ex: path.hub.file.opts.filename\n file: this,\n getCode: () => this.code,\n getScope: () => this.scope,\n addHelper: this.addHelper.bind(this),\n buildError: this.buildCodeFrameError.bind(this),\n };\n\n constructor(options: any, { code, ast, inputMap }: NormalizedFile) {\n this.opts = options;\n this.code = code;\n this.ast = ast;\n this.inputMap = inputMap;\n\n this.path = NodePath.get({\n hub: this.hub,\n parentPath: null,\n parent: this.ast,\n container: this.ast,\n key: \"program\",\n }).setContext() as NodePath;\n this.scope = this.path.scope;\n }\n\n /**\n * Provide backward-compatible access to the interpreter directive handling\n * in Babel 6.x. If you are writing a plugin for Babel 7.x, it would be\n * best to use 'program.interpreter' directly.\n */\n get shebang(): string {\n const { interpreter } = this.path.node;\n return interpreter ? interpreter.value : \"\";\n }\n set shebang(value: string) {\n if (value) {\n this.path.get(\"interpreter\").replaceWith(interpreterDirective(value));\n } else {\n this.path.get(\"interpreter\").remove();\n }\n }\n\n set(key: unknown, val: unknown) {\n if (!process.env.BABEL_8_BREAKING) {\n if (key === \"helpersNamespace\") {\n throw new Error(\n \"Babel 7.0.0-beta.56 has dropped support for the 'helpersNamespace' utility.\" +\n \"If you are using @babel/plugin-external-helpers you will need to use a newer \" +\n \"version than the one you currently have installed. \" +\n \"If you have your own implementation, you'll want to explore using 'helperGenerator' \" +\n \"alongside 'file.availableHelper()'.\",\n );\n }\n }\n\n this._map.set(key, val);\n }\n\n get(key: unknown): any {\n return this._map.get(key);\n }\n\n has(key: unknown): boolean {\n return this._map.has(key);\n }\n\n /**\n * Check if a given helper is available in @babel/core's helper list.\n *\n * This _also_ allows you to pass a Babel version specifically. If the\n * helper exists, but was not available for the full given range, it will be\n * considered unavailable.\n */\n availableHelper(name: string, versionRange?: string | null): boolean {\n let minVersion;\n try {\n minVersion = helpers.minVersion(name);\n } catch (err) {\n if (err.code !== \"BABEL_HELPER_UNKNOWN\") throw err;\n\n return false;\n }\n\n if (typeof versionRange !== \"string\") return true;\n\n // semver.intersects() has some surprising behavior with comparing ranges\n // with pre-release versions. We add '^' to ensure that we are always\n // comparing ranges with ranges, which sidesteps this logic.\n // For example:\n //\n // semver.intersects(`<7.0.1`, \"7.0.0-beta.0\") // false - surprising\n // semver.intersects(`<7.0.1`, \"^7.0.0-beta.0\") // true - expected\n //\n // This is because the first falls back to\n //\n // semver.satisfies(\"7.0.0-beta.0\", `<7.0.1`) // false - surprising\n //\n // and this fails because a prerelease version can only satisfy a range\n // if it is a prerelease within the same major/minor/patch range.\n //\n // Note: If this is found to have issues, please also revisit the logic in\n // transform-runtime's definitions.js file.\n if (semver.valid(versionRange)) versionRange = `^${versionRange}`;\n\n if (process.env.BABEL_8_BREAKING) {\n return (\n !semver.intersects(`<${minVersion}`, versionRange) &&\n !semver.intersects(`>=9.0.0`, versionRange)\n );\n } else {\n return (\n !semver.intersects(`<${minVersion}`, versionRange) &&\n !semver.intersects(`>=8.0.0`, versionRange)\n );\n }\n }\n\n addHelper(name: string): t.Identifier {\n const declar = this.declarations[name];\n if (declar) return cloneNode(declar);\n\n const generator = this.get(\"helperGenerator\");\n if (generator) {\n const res = generator(name);\n if (res) return res;\n }\n\n // make sure that the helper exists\n helpers.minVersion(name);\n\n const uid = (this.declarations[name] =\n this.scope.generateUidIdentifier(name));\n\n const dependencies: { [key: string]: t.Identifier } = {};\n for (const dep of helpers.getDependencies(name)) {\n dependencies[dep] = this.addHelper(dep);\n }\n\n const { nodes, globals } = helpers.get(\n name,\n dep => dependencies[dep],\n uid.name,\n Object.keys(this.scope.getAllBindings()),\n );\n\n globals.forEach(name => {\n if (this.path.scope.hasBinding(name, true /* noGlobals */)) {\n this.path.scope.rename(name);\n }\n });\n\n nodes.forEach(node => {\n // @ts-expect-error Fixme: document _compact node property\n node._compact = true;\n });\n\n const added = this.path.unshiftContainer(\"body\", nodes);\n // TODO: NodePath#unshiftContainer should automatically register new\n // bindings.\n for (const path of added) {\n if (path.isVariableDeclaration()) this.scope.registerDeclaration(path);\n }\n\n return uid;\n }\n\n buildCodeFrameError(\n node: t.Node | undefined | null,\n msg: string,\n _Error: typeof Error = SyntaxError,\n ): Error {\n let loc = node?.loc;\n\n if (!loc && node) {\n const state: { loc?: t.SourceLocation | null } = {\n loc: null,\n };\n traverse(node, errorVisitor, this.scope, state);\n loc = state.loc;\n\n let txt =\n \"This is an error on an internal node. Probably an internal error.\";\n if (loc) txt += \" Location has been estimated.\";\n\n msg += ` (${txt})`;\n }\n\n if (loc) {\n const { highlightCode = true } = this.opts;\n\n msg +=\n \"\\n\" +\n codeFrameColumns(\n this.code,\n {\n start: {\n line: loc.start.line,\n column: loc.start.column + 1,\n },\n end:\n loc.end && loc.start.line === loc.end.line\n ? {\n line: loc.end.line,\n column: loc.end.column + 1,\n }\n : undefined,\n },\n { highlightCode },\n );\n }\n\n return new _Error(msg);\n }\n}\n\nif (!process.env.BABEL_8_BREAKING) {\n // @ts-expect-error Babel 7\n File.prototype.addImport = function addImport() {\n throw new Error(\n \"This API has been removed. If you're looking for this \" +\n \"functionality in Babel 7, you should import the \" +\n \"'@babel/helper-module-imports' module and use the functions exposed \" +\n \" from that module, such as 'addNamed' or 'addDefault'.\",\n );\n };\n // @ts-expect-error Babel 7\n File.prototype.addTemplateObject = function addTemplateObject() {\n throw new Error(\n \"This function has been moved into the template literal transform itself.\",\n );\n };\n\n if (!USE_ESM || IS_STANDALONE) {\n // @ts-expect-error Babel 7\n File.prototype.getModuleName = function getModuleName() {\n return babel7.getModuleName()(this.opts, this.opts);\n };\n }\n}\n"],"mappings":";;;;;;AAAA,SAAAA,QAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,OAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,UAAA;EAAA,MAAAF,IAAA,GAAAC,OAAA;EAAAC,SAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,SAAAG,WAAA;EAAA,MAAAH,IAAA,GAAAC,OAAA;EAAAE,UAAA,YAAAA,CAAA;IAAA,OAAAH,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,SAAAI,GAAA;EAAA,MAAAJ,IAAA,GAAAC,OAAA;EAAAG,EAAA,YAAAA,C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AAiBA,CAAA,EAAG;IAC9D,MAAM,IAAI5C,KAAK,CACb,0EACF,CAAC;EACH,CAAC;EAE8B;IAE7BhC,IAAI,CAAC0E,SAAS,CAACG,aAAa,GAAG,SAASA,aAAaA,CAAA,EAAG;MACtD,OAAO5G,MAAM,CAAC4G,aAAa,CAAC,CAAC,CAAC,IAAI,CAACrE,IAAI,EAAE,IAAI,CAACA,IAAI,CAAC;IACrD,CAAC;EACH;AACF;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/file/generate.js b/node_modules/@babel/core/lib/transformation/file/generate.js new file mode 100644 index 0000000..10b5b29 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/file/generate.js @@ -0,0 +1,84 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = generateCode; +function _convertSourceMap() { + const data = require("convert-source-map"); + _convertSourceMap = function () { + return data; + }; + return data; +} +function _generator() { + const data = require("@babel/generator"); + _generator = function () { + return data; + }; + return data; +} +var _mergeMap = require("./merge-map.js"); +function generateCode(pluginPasses, file) { + const { + opts, + ast, + code, + inputMap + } = file; + const { + generatorOpts + } = opts; + generatorOpts.inputSourceMap = inputMap == null ? void 0 : inputMap.toObject(); + const results = []; + for (const plugins of pluginPasses) { + for (const plugin of plugins) { + const { + generatorOverride + } = plugin; + if (generatorOverride) { + const result = generatorOverride(ast, generatorOpts, code, _generator().default); + if (result !== undefined) results.push(result); + } + } + } + let result; + if (results.length === 0) { + result = (0, _generator().default)(ast, generatorOpts, code); + } else if (results.length === 1) { + result = results[0]; + if (typeof result.then === "function") { + throw new Error(`You appear to be using an async codegen plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version.`); + } + } else { + throw new Error("More than one plugin attempted to override codegen."); + } + let { + code: outputCode, + decodedMap: outputMap = result.map + } = result; + if (result.__mergedMap) { + outputMap = Object.assign({}, result.map); + } else { + if (outputMap) { + if (inputMap) { + outputMap = (0, _mergeMap.default)(inputMap.toObject(), outputMap, generatorOpts.sourceFileName); + } else { + outputMap = result.map; + } + } + } + if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") { + outputCode += "\n" + _convertSourceMap().fromObject(outputMap).toComment(); + } + if (opts.sourceMaps === "inline") { + outputMap = null; + } + return { + outputCode, + outputMap + }; +} +0 && 0; + +//# sourceMappingURL=generate.js.map diff --git a/node_modules/@babel/core/lib/transformation/file/generate.js.map b/node_modules/@babel/core/lib/transformation/file/generate.js.map new file mode 100644 index 0000000..36401b4 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/file/generate.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_convertSourceMap","data","require","_generator","_mergeMap","generateCode","pluginPasses","file","opts","ast","code","inputMap","generatorOpts","inputSourceMap","toObject","results","plugins","plugin","generatorOverride","result","generate","undefined","push","length","then","Error","outputCode","decodedMap","outputMap","map","__mergedMap","Object","assign","mergeSourceMap","sourceFileName","sourceMaps","convertSourceMap","fromObject","toComment"],"sources":["../../../src/transformation/file/generate.ts"],"sourcesContent":["import type { PluginPasses } from \"../../config/index.ts\";\nimport convertSourceMap from \"convert-source-map\";\nimport type { GeneratorResult } from \"@babel/generator\";\nimport generate from \"@babel/generator\";\n\nimport type File from \"./file.ts\";\nimport mergeSourceMap from \"./merge-map.ts\";\n\nexport default function generateCode(\n pluginPasses: PluginPasses,\n file: File,\n): {\n outputCode: string;\n outputMap: GeneratorResult[\"map\"] | null;\n} {\n const { opts, ast, code, inputMap } = file;\n const { generatorOpts } = opts;\n\n generatorOpts.inputSourceMap = inputMap?.toObject();\n\n const results = [];\n for (const plugins of pluginPasses) {\n for (const plugin of plugins) {\n const { generatorOverride } = plugin;\n if (generatorOverride) {\n const result = generatorOverride(ast, generatorOpts, code, generate);\n\n if (result !== undefined) results.push(result);\n }\n }\n }\n\n let result;\n if (results.length === 0) {\n result = generate(ast, generatorOpts, code);\n } else if (results.length === 1) {\n result = results[0];\n\n if (typeof result.then === \"function\") {\n throw new Error(\n `You appear to be using an async codegen plugin, ` +\n `which your current version of Babel does not support. ` +\n `If you're using a published plugin, ` +\n `you may need to upgrade your @babel/core version.`,\n );\n }\n } else {\n throw new Error(\"More than one plugin attempted to override codegen.\");\n }\n\n // Decoded maps are faster to merge, so we attempt to get use the decodedMap\n // first. But to preserve backwards compat with older Generator, we'll fall\n // back to the encoded map.\n let { code: outputCode, decodedMap: outputMap = result.map } = result;\n\n // For backwards compat.\n if (result.__mergedMap) {\n /**\n * @see mergeSourceMap\n */\n outputMap = { ...result.map };\n } else {\n if (outputMap) {\n if (inputMap) {\n // mergeSourceMap returns an encoded map\n outputMap = mergeSourceMap(\n inputMap.toObject(),\n outputMap,\n generatorOpts.sourceFileName,\n );\n } else {\n // We cannot output a decoded map, so retrieve the encoded form. Because\n // the decoded form is free, it's fine to prioritize decoded first.\n outputMap = result.map;\n }\n }\n }\n\n if (opts.sourceMaps === \"inline\" || opts.sourceMaps === \"both\") {\n outputCode += \"\\n\" + convertSourceMap.fromObject(outputMap).toComment();\n }\n\n if (opts.sourceMaps === \"inline\") {\n outputMap = null;\n }\n\n return { outputCode, outputMap };\n}\n"],"mappings":";;;;;;AACA,SAAAA,kBAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,iBAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,SAAAE,WAAA;EAAA,MAAAF,IAAA,GAAAC,OAAA;EAAAC,UAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAGA,IAAAG,SAAA,GAAAF,OAAA;AAEe,SAASG,YAAYA,CAClCC,YAA0B,EAC1BC,IAAU,EAIV;EACA,MAAM;IAAEC,IAAI;IAAEC,GAAG;IAAEC,IAAI;IAAEC;EAAS,CAAC,GAAGJ,IAAI;EAC1C,MAAM;IAAEK;EAAc,CAAC,GAAGJ,IAAI;EAE9BI,aAAa,CAACC,cAA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,iBAAc,EACxBtB,QAAQ,CAACG,QAAQ,CAAC,CAAC,EACnBc,SAAS,EACThB,aAAa,CAACsB,cAChB,CAAC;MACH,CAAC,MAAM;QAGLN,SAAS,GAAGT,MAAM,CAACU,GAAG;MACxB;IACF;EACF;EAEA,IAAIrB,IAAI,CAAC2B,UAAU,KAAK,QAAQ,IAAI3B,IAAI,CAAC2B,UAAU,KAAK,MAAM,EAAE;IAC9DT,UAAU,IAAI,IAAI,GAAGU,kBAAeA,CAAC,CAACC,UAAU,CAACT,SAAS,CAAC,CAACU,SAAS,CAAC,CAAC;EACzE;EAEA,IAAI9B,IAAI,CAAC2B,UAAU,KAAK,QAAQ,EAAE;IAChCP,SAAS,GAAG,IAAI;EAClB;EAEA,OAAO;IAAEF,UAAU;IAAEE;EAAU,CAAC;AAClC;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/file/merge-map.js b/node_modules/@babel/core/lib/transformation/file/merge-map.js new file mode 100644 index 0000000..cf3971b --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/file/merge-map.js @@ -0,0 +1,37 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = mergeSourceMap; +function _remapping() { + const data = require("@ampproject/remapping"); + _remapping = function () { + return data; + }; + return data; +} +function mergeSourceMap(inputMap, map, sourceFileName) { + const source = sourceFileName.replace(/\\/g, "/"); + let found = false; + const result = _remapping()(rootless(map), (s, ctx) => { + if (s === source && !found) { + found = true; + ctx.source = ""; + return rootless(inputMap); + } + return null; + }); + if (typeof inputMap.sourceRoot === "string") { + result.sourceRoot = inputMap.sourceRoot; + } + return Object.assign({}, result); +} +function rootless(map) { + return Object.assign({}, map, { + sourceRoot: null + }); +} +0 && 0; + +//# sourceMappingURL=merge-map.js.map diff --git a/node_modules/@babel/core/lib/transformation/file/merge-map.js.map b/node_modules/@babel/core/lib/transformation/file/merge-map.js.map new file mode 100644 index 0000000..786f56d --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/file/merge-map.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_remapping","data","require","mergeSourceMap","inputMap","map","sourceFileName","source","replace","found","result","remapping","rootless","s","ctx","sourceRoot","Object","assign"],"sources":["../../../src/transformation/file/merge-map.ts"],"sourcesContent":["type SourceMap = any;\nimport remapping from \"@ampproject/remapping\";\n\nexport default function mergeSourceMap(\n inputMap: SourceMap,\n map: SourceMap,\n sourceFileName: string,\n): SourceMap {\n // On win32 machines, the sourceFileName uses backslash paths like\n // `C:\\foo\\bar.js`. But sourcemaps are always posix paths, so we need to\n // normalize to regular slashes before we can merge (else we won't find the\n // source associated with our input map).\n // This mirrors code done while generating the output map at\n // https://github.com/babel/babel/blob/5c2fcadc9ae34fd20dd72b1111d5cf50476d700d/packages/babel-generator/src/source-map.ts#L102\n const source = sourceFileName.replace(/\\\\/g, \"/\");\n\n // Prevent an infinite recursion if one of the input map's sources has the\n // same resolved path as the input map. In the case, it would keep find the\n // input map, then get it's sources which will include a path like the input\n // map, on and on.\n let found = false;\n const result = remapping(rootless(map), (s, ctx) => {\n if (s === source && !found) {\n found = true;\n // We empty the source location, which will prevent the sourcemap from\n // becoming relative to the input's location. Eg, if we're transforming a\n // file 'foo/bar.js', and it is a transformation of a `baz.js` file in the\n // same directory, the expected output is just `baz.js`. Without this step,\n // it would become `foo/baz.js`.\n ctx.source = \"\";\n\n return rootless(inputMap);\n }\n\n return null;\n });\n\n if (typeof inputMap.sourceRoot === \"string\") {\n result.sourceRoot = inputMap.sourceRoot;\n }\n\n // remapping returns a SourceMap class type, but this breaks code downstream in\n // @babel/traverse and @babel/types that relies on data being plain objects.\n // When it encounters the sourcemap type it outputs a \"don't know how to turn\n // this value into a node\" error. As a result, we are converting the merged\n // sourcemap to a plain js object.\n return { ...result };\n}\n\nfunction rootless(map: SourceMap): SourceMap {\n return {\n ...map,\n\n // This is a bit hack. Remapping will create absolute sources in our\n // sourcemap, but we want to maintain sources relative to the sourceRoot.\n // We'll re-add the sourceRoot after remapping.\n sourceRoot: null,\n };\n}\n"],"mappings":";;;;;;AACA,SAAAA,WAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,UAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEe,SAASE,cAAcA,CACpCC,QAAmB,EACnBC,GAAc,EACdC,cAAsB,EACX;EAOX,MAAMC,MAAM,GAAGD,cAAc,CAACE,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;EAMjD,IAAIC,KAAK,GAAG,KAAK;EACjB,MAAMC,MAAM,GAAGC,WAAQA,CAAC,CAACC,QAAQ,CAACP,GAAG,CAAC,EAAE,CAACQ,CAAC,EAAEC,GAAG,KAAK;IAClD,IAAID,CAAC,KAAKN,MAAM,IAAI,CAACE,KAAK,EAAE;MAC1BA,KAAK,GAAG,IAAI;MAMZK,GAAG,CAACP,MAAM,GAAG,EAAE;MAEf,OAAOK,QAAQ,CAACR,QAAQ,CAAC;IAC3B;IAEA,OAAO,IAAI;EACb,CAAC,CAAC;EAEF,IAAI,OAAOA,QAAQ,CAACW,UAAU,KAAK,QAAQ,EAAE;IAC3CL,MAAM,CAACK,UAAU,GAAGX,QAAQ,CAACW,UAAU;EACzC;EAOA,OAAAC,MAAA,CAAAC,MAAA,KAAYP,MAAM;AACpB;AAEA,SAASE,QAAQA,CAACP,GAAc,EAAa;EAC3C,OAAAW,MAAA,CAAAC,MAAA,KACKZ,GAAG;IAKNU,UAAU,EAAE;EAAI;AAEpB;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/index.js b/node_modules/@babel/core/lib/transformation/index.js new file mode 100644 index 0000000..7d3247f --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/index.js @@ -0,0 +1,101 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.run = run; +function _traverse() { + const data = require("@babel/traverse"); + _traverse = function () { + return data; + }; + return data; +} +var _pluginPass = require("./plugin-pass.js"); +var _blockHoistPlugin = require("./block-hoist-plugin.js"); +var _normalizeOpts = require("./normalize-opts.js"); +var _normalizeFile = require("./normalize-file.js"); +var _generate = require("./file/generate.js"); +var _deepArray = require("../config/helpers/deep-array.js"); +function* run(config, code, ast) { + const file = yield* (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code, ast); + const opts = file.opts; + try { + yield* transformFile(file, config.passes); + } catch (e) { + var _opts$filename; + e.message = `${(_opts$filename = opts.filename) != null ? _opts$filename : "unknown file"}: ${e.message}`; + if (!e.code) { + e.code = "BABEL_TRANSFORM_ERROR"; + } + throw e; + } + let outputCode, outputMap; + try { + if (opts.code !== false) { + ({ + outputCode, + outputMap + } = (0, _generate.default)(config.passes, file)); + } + } catch (e) { + var _opts$filename2; + e.message = `${(_opts$filename2 = opts.filename) != null ? _opts$filename2 : "unknown file"}: ${e.message}`; + if (!e.code) { + e.code = "BABEL_GENERATE_ERROR"; + } + throw e; + } + return { + metadata: file.metadata, + options: opts, + ast: opts.ast === true ? file.ast : null, + code: outputCode === undefined ? null : outputCode, + map: outputMap === undefined ? null : outputMap, + sourceType: file.ast.program.sourceType, + externalDependencies: (0, _deepArray.flattenToSet)(config.externalDependencies) + }; +} +function* transformFile(file, pluginPasses) { + for (const pluginPairs of pluginPasses) { + const passPairs = []; + const passes = []; + const visitors = []; + for (const plugin of pluginPairs.concat([(0, _blockHoistPlugin.default)()])) { + const pass = new _pluginPass.default(file, plugin.key, plugin.options); + passPairs.push([plugin, pass]); + passes.push(pass); + visitors.push(plugin.visitor); + } + for (const [plugin, pass] of passPairs) { + const fn = plugin.pre; + if (fn) { + const result = fn.call(pass, file); + yield* []; + if (isThenable(result)) { + throw new Error(`You appear to be using an plugin with an async .pre, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`); + } + } + } + const visitor = _traverse().default.visitors.merge(visitors, passes, file.opts.wrapPluginVisitorMethod); + { + (0, _traverse().default)(file.ast, visitor, file.scope); + } + for (const [plugin, pass] of passPairs) { + const fn = plugin.post; + if (fn) { + const result = fn.call(pass, file); + yield* []; + if (isThenable(result)) { + throw new Error(`You appear to be using an plugin with an async .post, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`); + } + } + } + } +} +function isThenable(val) { + return !!val && (typeof val === "object" || typeof val === "function") && !!val.then && typeof val.then === "function"; +} +0 && 0; + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/core/lib/transformation/index.js.map b/node_modules/@babel/core/lib/transformation/index.js.map new file mode 100644 index 0000000..a1364e6 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_traverse","data","require","_pluginPass","_blockHoistPlugin","_normalizeOpts","_normalizeFile","_generate","_deepArray","run","config","code","ast","file","normalizeFile","passes","normalizeOptions","opts","transformFile","e","_opts$filename","message","filename","outputCode","outputMap","generateCode","_opts$filename2","metadata","options","undefined","map","sourceType","program","externalDependencies","flattenToSet","pluginPasses","pluginPairs","passPairs","visitors","plugin","concat","loadBlockHoistPlugin","pass","PluginPass","key","push","visitor","fn","pre","result","call","isThenable","Error","traverse","merge","wrapPluginVisitorMethod","scope","post","val","then"],"sources":["../../src/transformation/index.ts"],"sourcesContent":["import traverse from \"@babel/traverse\";\nimport type * as t from \"@babel/types\";\nimport type { GeneratorResult } from \"@babel/generator\";\n\nimport type { Handler } from \"gensync\";\n\nimport type { ResolvedConfig, Plugin, PluginPasses } from \"../config/index.ts\";\n\nimport PluginPass from \"./plugin-pass.ts\";\nimport loadBlockHoistPlugin from \"./block-hoist-plugin.ts\";\nimport normalizeOptions from \"./normalize-opts.ts\";\nimport normalizeFile from \"./normalize-file.ts\";\n\nimport generateCode from \"./file/generate.ts\";\nimport type File from \"./file/file.ts\";\n\nimport { flattenToSet } from \"../config/helpers/deep-array.ts\";\n\nexport type FileResultCallback = {\n (err: Error, file: null): void;\n (err: null, file: FileResult | null): void;\n};\n\nexport type FileResult = {\n metadata: { [key: string]: any };\n options: { [key: string]: any };\n ast: t.File | null;\n code: string | null;\n map: GeneratorResult[\"map\"] | null;\n sourceType: \"script\" | \"module\";\n externalDependencies: Set;\n};\n\nexport function* run(\n config: ResolvedConfig,\n code: string,\n ast?: t.File | t.Program | null,\n): Handler {\n const file = yield* normalizeFile(\n config.passes,\n normalizeOptions(config),\n code,\n ast,\n );\n\n const opts = file.opts;\n try {\n yield* transformFile(file, config.passes);\n } catch (e) {\n e.message = `${opts.filename ?? \"unknown file\"}: ${e.message}`;\n if (!e.code) {\n e.code = \"BABEL_TRANSFORM_ERROR\";\n }\n throw e;\n }\n\n let outputCode, outputMap;\n try {\n if (opts.code !== false) {\n ({ outputCode, outputMap } = generateCode(config.passes, file));\n }\n } catch (e) {\n e.message = `${opts.filename ?? \"unknown file\"}: ${e.message}`;\n if (!e.code) {\n e.code = \"BABEL_GENERATE_ERROR\";\n }\n throw e;\n }\n\n return {\n metadata: file.metadata,\n options: opts,\n ast: opts.ast === true ? file.ast : null,\n code: outputCode === undefined ? null : outputCode,\n map: outputMap === undefined ? null : outputMap,\n sourceType: file.ast.program.sourceType,\n externalDependencies: flattenToSet(config.externalDependencies),\n };\n}\n\nfunction* transformFile(file: File, pluginPasses: PluginPasses): Handler {\n for (const pluginPairs of pluginPasses) {\n const passPairs: [Plugin, PluginPass][] = [];\n const passes = [];\n const visitors = [];\n\n for (const plugin of pluginPairs.concat([loadBlockHoistPlugin()])) {\n const pass = new PluginPass(file, plugin.key, plugin.options);\n\n passPairs.push([plugin, pass]);\n passes.push(pass);\n visitors.push(plugin.visitor);\n }\n\n for (const [plugin, pass] of passPairs) {\n const fn = plugin.pre;\n if (fn) {\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n const result = fn.call(pass, file);\n\n // @ts-expect-error - If we want to support async .pre\n yield* [];\n\n if (isThenable(result)) {\n throw new Error(\n `You appear to be using an plugin with an async .pre, ` +\n `which your current version of Babel does not support. ` +\n `If you're using a published plugin, you may need to upgrade ` +\n `your @babel/core version.`,\n );\n }\n }\n }\n\n // merge all plugin visitors into a single visitor\n const visitor = traverse.visitors.merge(\n visitors,\n passes,\n file.opts.wrapPluginVisitorMethod,\n );\n if (process.env.BABEL_8_BREAKING) {\n traverse(file.ast.program, visitor, file.scope, null, file.path, true);\n } else {\n traverse(file.ast, visitor, file.scope);\n }\n\n for (const [plugin, pass] of passPairs) {\n const fn = plugin.post;\n if (fn) {\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n const result = fn.call(pass, file);\n\n // @ts-expect-error - If we want to support async .post\n yield* [];\n\n if (isThenable(result)) {\n throw new Error(\n `You appear to be using an plugin with an async .post, ` +\n `which your current version of Babel does not support. ` +\n `If you're using a published plugin, you may need to upgrade ` +\n `your @babel/core version.`,\n );\n }\n }\n }\n }\n}\n\nfunction isThenable>(val: any): val is T {\n return (\n !!val &&\n (typeof val === \"object\" || typeof val === \"function\") &&\n !!val.then &&\n typeof val.then === \"function\"\n );\n}\n"],"mappings":";;;;;;AAAA,SAAAA,UAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,SAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAQA,IAAAE,WAAA,GAAAD,OAAA;AACA,IAAAE,iBAAA,GAAAF,OAAA;AACA,IAAAG,cAAA,GAAAH,OAAA;AACA,IAAAI,cAAA,GAAAJ,OAAA;AAEA,IAAAK,SAAA,GAAAL,OAAA;AAGA,IAAAM,UAAA,GAAAN,OAAA;AAiBO,UAAUO,GAAGA,CAClBC,MAAsB,EACtBC,IAAY,EACZC,GAA+B,EACV;EACrB,MAAMC,IAAI,GAAG,OAAO,IAAAC,sBAAa,EAC/BJ,MAAM,CAACK,MAAM,EACb,IAAAC,sBAAgB,EAACN,MAAM,CAAC,EACxBC,IAAI,EACJC,GACF,CAAC;EAED,MAAMK,IAAI,GAAGJ,IAAI,CAACI,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ACxC,IAAI,CAACD,GAAG,EAAEkC,OAAO,EAAEjC,IAAI,CAAC2C,KAAK,CAAC;IACzC;IAEA,KAAK,MAAM,CAACjB,MAAM,EAAEG,IAAI,CAAC,IAAIL,SAAS,EAAE;MACtC,MAAMU,EAAE,GAAGR,MAAM,CAACkB,IAAI;MACtB,IAAIV,EAAE,EAAE;QAEN,MAAME,MAAM,GAAGF,EAAE,CAACG,IAAI,CAACR,IAAI,EAAE7B,IAAI,CAAC;QAGlC,OAAO,EAAE;QAET,IAAIsC,UAAU,CAACF,MAAM,CAAC,EAAE;UACtB,MAAM,IAAIG,KAAK,CACb,wDAAwD,GACtD,wDAAwD,GACxD,8DAA8D,GAC9D,2BACJ,CAAC;QACH;MACF;IACF;EACF;AACF;AAEA,SAASD,UAAUA,CAA6BO,GAAQ,EAAY;EAClE,OACE,CAAC,CAACA,GAAG,KACJ,OAAOA,GAAG,KAAK,QAAQ,IAAI,OAAOA,GAAG,KAAK,UAAU,CAAC,IACtD,CAAC,CAACA,GAAG,CAACC,IAAI,IACV,OAAOD,GAAG,CAACC,IAAI,KAAK,UAAU;AAElC;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/normalize-file.js b/node_modules/@babel/core/lib/transformation/normalize-file.js new file mode 100644 index 0000000..20c5dc0 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/normalize-file.js @@ -0,0 +1,129 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = normalizeFile; +function _fs() { + const data = require("fs"); + _fs = function () { + return data; + }; + return data; +} +function _path() { + const data = require("path"); + _path = function () { + return data; + }; + return data; +} +function _debug() { + const data = require("debug"); + _debug = function () { + return data; + }; + return data; +} +function _t() { + const data = require("@babel/types"); + _t = function () { + return data; + }; + return data; +} +function _convertSourceMap() { + const data = require("convert-source-map"); + _convertSourceMap = function () { + return data; + }; + return data; +} +var _file = require("./file/file.js"); +var _index = require("../parser/index.js"); +var _cloneDeep = require("./util/clone-deep.js"); +const { + file, + traverseFast +} = _t(); +const debug = _debug()("babel:transform:file"); +const INLINE_SOURCEMAP_REGEX = /^[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,.*$/; +const EXTERNAL_SOURCEMAP_REGEX = /^[@#][ \t]+sourceMappingURL=([^\s'"`]+)[ \t]*$/; +function* normalizeFile(pluginPasses, options, code, ast) { + code = `${code || ""}`; + if (ast) { + if (ast.type === "Program") { + ast = file(ast, [], []); + } else if (ast.type !== "File") { + throw new Error("AST root must be a Program or File node"); + } + if (options.cloneInputAst) { + ast = (0, _cloneDeep.default)(ast); + } + } else { + ast = yield* (0, _index.default)(pluginPasses, options, code); + } + let inputMap = null; + if (options.inputSourceMap !== false) { + if (typeof options.inputSourceMap === "object") { + inputMap = _convertSourceMap().fromObject(options.inputSourceMap); + } + if (!inputMap) { + const lastComment = extractComments(INLINE_SOURCEMAP_REGEX, ast); + if (lastComment) { + try { + inputMap = _convertSourceMap().fromComment("//" + lastComment); + } catch (err) { + { + debug("discarding unknown inline input sourcemap"); + } + } + } + } + if (!inputMap) { + const lastComment = extractComments(EXTERNAL_SOURCEMAP_REGEX, ast); + if (typeof options.filename === "string" && lastComment) { + try { + const match = EXTERNAL_SOURCEMAP_REGEX.exec(lastComment); + const inputMapContent = _fs().readFileSync(_path().resolve(_path().dirname(options.filename), match[1]), "utf8"); + inputMap = _convertSourceMap().fromJSON(inputMapContent); + } catch (err) { + debug("discarding unknown file input sourcemap", err); + } + } else if (lastComment) { + debug("discarding un-loadable file input sourcemap"); + } + } + } + return new _file.default(options, { + code, + ast: ast, + inputMap + }); +} +function extractCommentsFromList(regex, comments, lastComment) { + if (comments) { + comments = comments.filter(({ + value + }) => { + if (regex.test(value)) { + lastComment = value; + return false; + } + return true; + }); + } + return [comments, lastComment]; +} +function extractComments(regex, ast) { + let lastComment = null; + traverseFast(ast, node => { + [node.leadingComments, lastComment] = extractCommentsFromList(regex, node.leadingComments, lastComment); + [node.innerComments, lastComment] = extractCommentsFromList(regex, node.innerComments, lastComment); + [node.trailingComments, lastComment] = extractCommentsFromList(regex, node.trailingComments, lastComment); + }); + return lastComment; +} +0 && 0; + +//# sourceMappingURL=normalize-file.js.map diff --git a/node_modules/@babel/core/lib/transformation/normalize-file.js.map b/node_modules/@babel/core/lib/transformation/normalize-file.js.map new file mode 100644 index 0000000..6456f57 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/normalize-file.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_fs","data","require","_path","_debug","_t","_convertSourceMap","_file","_index","_cloneDeep","file","traverseFast","debug","buildDebug","INLINE_SOURCEMAP_REGEX","EXTERNAL_SOURCEMAP_REGEX","normalizeFile","pluginPasses","options","code","ast","type","Error","cloneInputAst","cloneDeep","parser","inputMap","inputSourceMap","convertSourceMap","fromObject","lastComment","extractComments","fromComment","err","filename","match","exec","inputMapContent","fs","readFileSync","path","resolve","dirname","fromJSON","File","extractCommentsFromList","regex","comments","filter","value","test","node","leadingComments","innerComments","trailingComments"],"sources":["../../src/transformation/normalize-file.ts"],"sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\nimport buildDebug from \"debug\";\nimport type { Handler } from \"gensync\";\nimport { file, traverseFast } from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport type { PluginPasses } from \"../config/index.ts\";\nimport convertSourceMap from \"convert-source-map\";\nimport type { SourceMapConverter as Converter } from \"convert-source-map\";\nimport File from \"./file/file.ts\";\nimport parser from \"../parser/index.ts\";\nimport cloneDeep from \"./util/clone-deep.ts\";\n\nconst debug = buildDebug(\"babel:transform:file\");\n\n// These regexps are copied from the convert-source-map package,\n// but without // or /* at the beginning of the comment.\n\nconst INLINE_SOURCEMAP_REGEX =\n /^[@#]\\s+sourceMappingURL=data:(?:application|text)\\/json;(?:charset[:=]\\S+?;)?base64,.*$/;\nconst EXTERNAL_SOURCEMAP_REGEX =\n /^[@#][ \\t]+sourceMappingURL=([^\\s'\"`]+)[ \\t]*$/;\n\nexport type NormalizedFile = {\n code: string;\n ast: t.File;\n inputMap: Converter | null;\n};\n\nexport default function* normalizeFile(\n pluginPasses: PluginPasses,\n options: { [key: string]: any },\n code: string,\n ast?: t.File | t.Program | null,\n): Handler {\n code = `${code || \"\"}`;\n\n if (ast) {\n if (ast.type === \"Program\") {\n ast = file(ast, [], []);\n } else if (ast.type !== \"File\") {\n throw new Error(\"AST root must be a Program or File node\");\n }\n\n if (options.cloneInputAst) {\n ast = cloneDeep(ast);\n }\n } else {\n // @ts-expect-error todo: use babel-types ast typings in Babel parser\n ast = yield* parser(pluginPasses, options, code);\n }\n\n let inputMap = null;\n if (options.inputSourceMap !== false) {\n // If an explicit object is passed in, it overrides the processing of\n // source maps that may be in the file itself.\n if (typeof options.inputSourceMap === \"object\") {\n inputMap = convertSourceMap.fromObject(options.inputSourceMap);\n }\n\n if (!inputMap) {\n const lastComment = extractComments(INLINE_SOURCEMAP_REGEX, ast);\n if (lastComment) {\n try {\n inputMap = convertSourceMap.fromComment(\"//\" + lastComment);\n } catch (err) {\n if (process.env.BABEL_8_BREAKING) {\n console.warn(\n \"discarding unknown inline input sourcemap\",\n options.filename,\n err,\n );\n } else {\n debug(\"discarding unknown inline input sourcemap\");\n }\n }\n }\n }\n\n if (!inputMap) {\n const lastComment = extractComments(EXTERNAL_SOURCEMAP_REGEX, ast);\n if (typeof options.filename === \"string\" && lastComment) {\n try {\n // when `lastComment` is non-null, EXTERNAL_SOURCEMAP_REGEX must have matches\n const match: [string, string] = EXTERNAL_SOURCEMAP_REGEX.exec(\n lastComment,\n ) as any;\n const inputMapContent = fs.readFileSync(\n path.resolve(path.dirname(options.filename), match[1]),\n \"utf8\",\n );\n inputMap = convertSourceMap.fromJSON(inputMapContent);\n } catch (err) {\n debug(\"discarding unknown file input sourcemap\", err);\n }\n } else if (lastComment) {\n debug(\"discarding un-loadable file input sourcemap\");\n }\n }\n }\n\n return new File(options, {\n code,\n ast: ast as t.File,\n inputMap,\n });\n}\n\nfunction extractCommentsFromList(\n regex: RegExp,\n comments: t.Comment[],\n lastComment: string | null,\n): [t.Comment[], string | null] {\n if (comments) {\n comments = comments.filter(({ value }) => {\n if (regex.test(value)) {\n lastComment = value;\n return false;\n }\n return true;\n });\n }\n return [comments, lastComment];\n}\n\nfunction extractComments(regex: RegExp, ast: t.Node) {\n let lastComment: string = null;\n traverseFast(ast, node => {\n [node.leadingComments, lastComment] = extractCommentsFromList(\n regex,\n node.leadingComments,\n lastComment,\n );\n [node.innerComments, lastComment] = extractCommentsFromList(\n regex,\n node.innerComments,\n lastComment,\n );\n [node.trailingComments, lastComment] = extractCommentsFromList(\n regex,\n node.trailingComments,\n lastComment,\n );\n });\n return lastComment;\n}\n"],"mappings":";;;;;;AAAA,SAAAA,IAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,GAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,MAAA;EAAA,MAAAF,IAAA,GAAAC,OAAA;EAAAC,KAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAG,OAAA;EAAA,MAAAH,IAAA,GAAAC,OAAA;EAAAE,MAAA,YAAAA,CAAA;IAAA,OAAAH,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,SAAAI,GAAA;EAAA,MAAAJ,IAAA,GAAAC,OAAA;EAAAG,EAAA,YAAAA,CAAA;IAAA,OAAAJ,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAGA,SAAAK,kBAAA;EAAA,MAAAL,IAAA,GAAAC,OAAA;EAAAI,iBAAA,YAAAA,CAAA;IAAA,OAAAL,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,IAAAM,KAAA,GAAAL,OAAA;AACA,IAAAM,MAAA,GAAAN,OAAA;AACA,IAAAO,UAAA,GAAAP,OAAA;AAA6C;EAPpCQ,IAAI;EAAEC;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AW,CAAC;AAChC;AAEA,SAASC,eAAeA,CAACe,KAAa,EAAE1B,GAAW,EAAE;EACnD,IAAIU,WAAmB,GAAG,IAAI;EAC9BnB,YAAY,CAACS,GAAG,EAAE+B,IAAI,IAAI;IACxB,CAACA,IAAI,CAACC,eAAe,EAAEtB,WAAW,CAAC,GAAGe,uBAAuB,CAC3DC,KAAK,EACLK,IAAI,CAACC,eAAe,EACpBtB,WACF,CAAC;IACD,CAACqB,IAAI,CAACE,aAAa,EAAEvB,WAAW,CAAC,GAAGe,uBAAuB,CACzDC,KAAK,EACLK,IAAI,CAACE,aAAa,EAClBvB,WACF,CAAC;IACD,CAACqB,IAAI,CAACG,gBAAgB,EAAExB,WAAW,CAAC,GAAGe,uBAAuB,CAC5DC,KAAK,EACLK,IAAI,CAACG,gBAAgB,EACrBxB,WACF,CAAC;EACH,CAAC,CAAC;EACF,OAAOA,WAAW;AACpB;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/normalize-opts.js b/node_modules/@babel/core/lib/transformation/normalize-opts.js new file mode 100644 index 0000000..20826fc --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/normalize-opts.js @@ -0,0 +1,59 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = normalizeOptions; +function _path() { + const data = require("path"); + _path = function () { + return data; + }; + return data; +} +function normalizeOptions(config) { + const { + filename, + cwd, + filenameRelative = typeof filename === "string" ? _path().relative(cwd, filename) : "unknown", + sourceType = "module", + inputSourceMap, + sourceMaps = !!inputSourceMap, + sourceRoot = config.options.moduleRoot, + sourceFileName = _path().basename(filenameRelative), + comments = true, + compact = "auto" + } = config.options; + const opts = config.options; + const options = Object.assign({}, opts, { + parserOpts: Object.assign({ + sourceType: _path().extname(filenameRelative) === ".mjs" ? "module" : sourceType, + sourceFileName: filename, + plugins: [] + }, opts.parserOpts), + generatorOpts: Object.assign({ + filename, + auxiliaryCommentBefore: opts.auxiliaryCommentBefore, + auxiliaryCommentAfter: opts.auxiliaryCommentAfter, + retainLines: opts.retainLines, + comments, + shouldPrintComment: opts.shouldPrintComment, + compact, + minified: opts.minified, + sourceMaps, + sourceRoot, + sourceFileName + }, opts.generatorOpts) + }); + for (const plugins of config.passes) { + for (const plugin of plugins) { + if (plugin.manipulateOptions) { + plugin.manipulateOptions(options, options.parserOpts); + } + } + } + return options; +} +0 && 0; + +//# sourceMappingURL=normalize-opts.js.map diff --git a/node_modules/@babel/core/lib/transformation/normalize-opts.js.map b/node_modules/@babel/core/lib/transformation/normalize-opts.js.map new file mode 100644 index 0000000..24121da --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/normalize-opts.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_path","data","require","normalizeOptions","config","filename","cwd","filenameRelative","path","relative","sourceType","inputSourceMap","sourceMaps","sourceRoot","options","moduleRoot","sourceFileName","basename","comments","compact","opts","Object","assign","parserOpts","extname","plugins","generatorOpts","auxiliaryCommentBefore","auxiliaryCommentAfter","retainLines","shouldPrintComment","minified","passes","plugin","manipulateOptions"],"sources":["../../src/transformation/normalize-opts.ts"],"sourcesContent":["import path from \"path\";\nimport type { ResolvedConfig } from \"../config/index.ts\";\n\nexport default function normalizeOptions(config: ResolvedConfig) {\n const {\n filename,\n cwd,\n filenameRelative = typeof filename === \"string\"\n ? path.relative(cwd, filename)\n : \"unknown\",\n sourceType = \"module\",\n inputSourceMap,\n sourceMaps = !!inputSourceMap,\n sourceRoot = process.env.BABEL_8_BREAKING\n ? undefined\n : config.options.moduleRoot,\n\n sourceFileName = path.basename(filenameRelative),\n\n comments = true,\n compact = \"auto\",\n } = config.options;\n\n const opts = config.options;\n\n const options = {\n ...opts,\n\n parserOpts: {\n sourceType:\n path.extname(filenameRelative) === \".mjs\" ? \"module\" : sourceType,\n\n sourceFileName: filename,\n plugins: [],\n ...opts.parserOpts,\n },\n\n generatorOpts: {\n // General generator flags.\n filename,\n\n auxiliaryCommentBefore: opts.auxiliaryCommentBefore,\n auxiliaryCommentAfter: opts.auxiliaryCommentAfter,\n retainLines: opts.retainLines,\n comments,\n shouldPrintComment: opts.shouldPrintComment,\n compact,\n minified: opts.minified,\n\n // Source-map generation flags.\n sourceMaps,\n\n sourceRoot,\n sourceFileName,\n ...opts.generatorOpts,\n },\n };\n\n for (const plugins of config.passes) {\n for (const plugin of plugins) {\n if (plugin.manipulateOptions) {\n plugin.manipulateOptions(options, options.parserOpts);\n }\n }\n }\n\n return options;\n}\n"],"mappings":";;;;;;AAAA,SAAAA,MAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,KAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAGe,SAASE,gBAAgBA,CAACC,MAAsB,EAAE;EAC/D,MAAM;IACJC,QAAQ;IACRC,GAAG;IACHC,gBAAgB,GAAG,OAAOF,QAAQ,KAAK,QAAQ,GAC3CG,MAAGA,CAAC,CAACC,QAAQ,CAACH,GAAG,EAAED,QAAQ,CAAC,GAC5B,SAAS;IACbK,UAAU,GAAG,QAAQ;IACrBC,cAAc;IACdC,UAAU,GAAG,CAAC,CAACD,cAAc;IAC7BE,UAAU,GAENT,MAAM,CAACU,OAAO,CAACC,UAAU;IAE7BC,cAAc,GAAGR,MAAGA,CAAC,CAACS,QAAQ,CAACV,gBAAgB,CAAC;IAEhDW,QAAQ,GAAG,IAAI;IACfC,OAAO,GAAG;EACZ,CAAC,GAAGf,MAAM,CAACU,OAAO;EAElB,MAAMM,IAAI,GAAGhB,MAAM,CAACU,OAAO;EAE3B,MAAMA,OAAO,GAAAO,MAAA,CAAAC,MAAA,KACRF,IAAI;IAEPG,UAAU,EAAAF,MAAA,CAAAC,MAAA;MACRZ,UAAU,EACRF,MAAGA,CAAC,CAACgB,OAAO,CAACjB,gBAAgB,CAAC,KAAK,MAAM,GAAG,QAAQ,GAAGG,UAAU;MAEnEM,cAAc,EAAEX,QAAQ;MACxBoB,OAAO,EAAE;IAAE,GACRL,IAAI,CAACG,UAAU,CACnB;IAEDG,aAAa,EAAAL,MAAA,CAAAC,MAAA;MAEXjB,QAAQ;MAERsB,sBAAsB,EAAEP,IAAI,CAACO,sBAAsB;MACnDC,qBAAqB,EAAER,IAAI,CAACQ,qBAAqB;MACjDC,WAAW,EAAET,IAAI,CAACS,WAAW;MAC7BX,QAAQ;MACRY,kBAAkB,EAAEV,IAAI,CAACU,kBAAkB;MAC3CX,OAAO;MACPY,QAAQ,EAAEX,IAAI,CAACW,QAAQ;MAGvBnB,UAAU;MAEVC,UAAU;MACVG;IAAc,GACXI,IAAI,CAACM,aAAa;EACtB,EACF;EAED,KAAK,MAAMD,OAAO,IAAIrB,MAAM,CAAC4B,MAAM,EAAE;IACnC,KAAK,MAAMC,MAAM,IAAIR,OAAO,EAAE;MAC5B,IAAIQ,MAAM,CAACC,iBAAiB,EAAE;QAC5BD,MAAM,CAACC,iBAAiB,CAACpB,OAAO,EAAEA,OAAO,CAACS,UAAU,CAAC;MACvD;IACF;EACF;EAEA,OAAOT,OAAO;AAChB;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/plugin-pass.js b/node_modules/@babel/core/lib/transformation/plugin-pass.js new file mode 100644 index 0000000..e39c885 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/plugin-pass.js @@ -0,0 +1,48 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +class PluginPass { + constructor(file, key, options) { + this._map = new Map(); + this.key = void 0; + this.file = void 0; + this.opts = void 0; + this.cwd = void 0; + this.filename = void 0; + this.key = key; + this.file = file; + this.opts = options || {}; + this.cwd = file.opts.cwd; + this.filename = file.opts.filename; + } + set(key, val) { + this._map.set(key, val); + } + get(key) { + return this._map.get(key); + } + availableHelper(name, versionRange) { + return this.file.availableHelper(name, versionRange); + } + addHelper(name) { + return this.file.addHelper(name); + } + buildCodeFrameError(node, msg, _Error) { + return this.file.buildCodeFrameError(node, msg, _Error); + } +} +exports.default = PluginPass; +{ + PluginPass.prototype.getModuleName = function getModuleName() { + return this.file.getModuleName(); + }; + PluginPass.prototype.addImport = function addImport() { + this.file.addImport(); + }; +} +0 && 0; + +//# sourceMappingURL=plugin-pass.js.map diff --git a/node_modules/@babel/core/lib/transformation/plugin-pass.js.map b/node_modules/@babel/core/lib/transformation/plugin-pass.js.map new file mode 100644 index 0000000..c716f7a --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/plugin-pass.js.map @@ -0,0 +1 @@ +{"version":3,"names":["PluginPass","constructor","file","key","options","_map","Map","opts","cwd","filename","set","val","get","availableHelper","name","versionRange","addHelper","buildCodeFrameError","node","msg","_Error","exports","default","prototype","getModuleName","addImport"],"sources":["../../src/transformation/plugin-pass.ts"],"sourcesContent":["import type * as t from \"@babel/types\";\nimport type File from \"./file/file.ts\";\n\nexport default class PluginPass {\n _map: Map = new Map();\n key: string | undefined | null;\n file: File;\n opts: Partial;\n\n // The working directory that Babel's programmatic options are loaded\n // relative to.\n cwd: string;\n\n // The absolute path of the file being compiled.\n filename: string | void;\n\n constructor(file: File, key?: string | null, options?: Options) {\n this.key = key;\n this.file = file;\n this.opts = options || {};\n this.cwd = file.opts.cwd;\n this.filename = file.opts.filename;\n }\n\n set(key: unknown, val: unknown) {\n this._map.set(key, val);\n }\n\n get(key: unknown): any {\n return this._map.get(key);\n }\n\n availableHelper(name: string, versionRange?: string | null) {\n return this.file.availableHelper(name, versionRange);\n }\n\n addHelper(name: string) {\n return this.file.addHelper(name);\n }\n\n buildCodeFrameError(\n node: t.Node | undefined | null,\n msg: string,\n _Error?: typeof Error,\n ) {\n return this.file.buildCodeFrameError(node, msg, _Error);\n }\n}\n\nif (!process.env.BABEL_8_BREAKING) {\n (PluginPass as any).prototype.getModuleName = function getModuleName(\n this: PluginPass,\n ): string | undefined {\n // @ts-expect-error only exists in Babel 7\n return this.file.getModuleName();\n };\n (PluginPass as any).prototype.addImport = function addImport(\n this: PluginPass,\n ): void {\n // @ts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AAS,CAACC,aAAa,GAAG,SAASA,aAAaA,CAAA,EAE9C;IAEpB,OAAO,IAAI,CAACtB,IAAI,CAACsB,aAAa,CAAC,CAAC;EAClC,CAAC;EACAxB,UAAU,CAASuB,SAAS,CAACE,SAAS,GAAG,SAASA,SAASA,CAAA,EAEpD;IAEN,IAAI,CAACvB,IAAI,CAACuB,SAAS,CAAC,CAAC;EACvB,CAAC;AACH;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/util/clone-deep.js b/node_modules/@babel/core/lib/transformation/util/clone-deep.js new file mode 100644 index 0000000..fc4148f --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/util/clone-deep.js @@ -0,0 +1,36 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; +function deepClone(value, cache) { + if (value !== null) { + if (cache.has(value)) return cache.get(value); + let cloned; + if (Array.isArray(value)) { + cloned = new Array(value.length); + cache.set(value, cloned); + for (let i = 0; i < value.length; i++) { + cloned[i] = typeof value[i] !== "object" ? value[i] : deepClone(value[i], cache); + } + } else { + cloned = {}; + cache.set(value, cloned); + const keys = Object.keys(value); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + cloned[key] = typeof value[key] !== "object" ? value[key] : deepClone(value[key], cache); + } + } + return cloned; + } + return value; +} +function _default(value) { + if (typeof value !== "object") return value; + return deepClone(value, new Map()); +} +0 && 0; + +//# sourceMappingURL=clone-deep.js.map diff --git a/node_modules/@babel/core/lib/transformation/util/clone-deep.js.map b/node_modules/@babel/core/lib/transformation/util/clone-deep.js.map new file mode 100644 index 0000000..4a1c619 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/util/clone-deep.js.map @@ -0,0 +1 @@ +{"version":3,"names":["deepClone","value","cache","has","get","cloned","Array","isArray","length","set","i","keys","Object","key","_default","Map"],"sources":["../../../src/transformation/util/clone-deep.ts"],"sourcesContent":["//https://github.com/babel/babel/pull/14583#discussion_r882828856\nfunction deepClone(value: any, cache: Map): any {\n if (value !== null) {\n if (cache.has(value)) return cache.get(value);\n let cloned: any;\n if (Array.isArray(value)) {\n cloned = new Array(value.length);\n cache.set(value, cloned);\n for (let i = 0; i < value.length; i++) {\n cloned[i] =\n typeof value[i] !== \"object\" ? value[i] : deepClone(value[i], cache);\n }\n } else {\n cloned = {};\n cache.set(value, cloned);\n const keys = Object.keys(value);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n cloned[key] =\n typeof value[key] !== \"object\"\n ? value[key]\n : deepClone(value[key], cache);\n }\n }\n return cloned;\n }\n return value;\n}\n\nexport default function (value: T): T {\n if (typeof value !== \"object\") return value;\n return deepClone(value, new Map());\n}\n"],"mappings":";;;;;;AACA,SAASA,SAASA,CAACC,KAAU,EAAEC,KAAoB,EAAO;EACxD,IAAID,KAAK,KAAK,IAAI,EAAE;IAClB,IAAIC,KAAK,CAACC,GAAG,CAACF,KAAK,CAAC,EAAE,OAAOC,KAAK,CAACE,GAAG,CAACH,KAAK,CAAC;IAC7C,IAAII,MAAW;IACf,IAAIC,KAAK,CAACC,OAAO,CAACN,KAAK,CAAC,EAAE;MACxBI,MAAM,GAAG,IAAIC,KAAK,CAACL,KAAK,CAACO,MAAM,CAAC;MAChCN,KAAK,CAACO,GAAG,CAACR,KAAK,EAAEI,MAAM,CAAC;MACxB,KAAK,IAAIK,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGT,KAAK,CAACO,MAAM,EAAEE,CAAC,EAAE,EAAE;QACrCL,MAAM,CAACK,CAAC,CAAC,GACP,OAAOT,KAAK,CAACS,CAAC,CAAC,KAAK,QAAQ,GAAGT,KAAK,CAACS,CAAC,CAAC,GAAGV,SAAS,CAACC,KAAK,CAACS,CAAC,CAAC,EAAER,KAAK,CAAC;MACxE;IACF,CAAC,MAAM;MACLG,MAAM,GAAG,CAAC,CAAC;MACXH,KAAK,CAACO,GAAG,CAACR,KAAK,EAAEI,MAAM,CAAC;MACxB,MAAMM,IAAI,GAAGC,MAAM,CAACD,IAAI,CAACV,KAAK,CAAC;MAC/B,KAAK,IAAIS,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGC,IAAI,CAACH,MAAM,EAAEE,CAAC,EAAE,EAAE;QACpC,MAAMG,GAAG,GAAGF,IAAI,CAACD,CAAC,CAAC;QACnBL,MAAM,CAACQ,GAAG,CAAC,GACT,OAAOZ,KAAK,CAACY,GAAG,CAAC,KAAK,QAAQ,GAC1BZ,KAAK,CAACY,GAAG,CAAC,GACVb,SAAS,CAACC,KAAK,CAACY,GAAG,CAAC,EAAEX,KAAK,CAAC;MACpC;IACF;IACA,OAAOG,MAAM;EACf;EACA,OAAOJ,KAAK;AACd;AAEe,SAAAa,SAAab,KAAQ,EAAK;EACvC,IAAI,OAAOA,KAAK,KAAK,QAAQ,EAAE,OAAOA,KAAK;EAC3C,OAAOD,SAAS,CAACC,KAAK,EAAE,IAAIc,GAAG,CAAC,CAAC,CAAC;AACpC;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/vendor/import-meta-resolve.js b/node_modules/@babel/core/lib/vendor/import-meta-resolve.js new file mode 100644 index 0000000..73d05ae --- /dev/null +++ b/node_modules/@babel/core/lib/vendor/import-meta-resolve.js @@ -0,0 +1,1043 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.moduleResolve = moduleResolve; +exports.resolve = resolve; +function _assert() { + const data = require("assert"); + _assert = function () { + return data; + }; + return data; +} +function _fs() { + const data = _interopRequireWildcard(require("fs"), true); + _fs = function () { + return data; + }; + return data; +} +function _process() { + const data = require("process"); + _process = function () { + return data; + }; + return data; +} +function _url() { + const data = require("url"); + _url = function () { + return data; + }; + return data; +} +function _path() { + const data = require("path"); + _path = function () { + return data; + }; + return data; +} +function _module() { + const data = require("module"); + _module = function () { + return data; + }; + return data; +} +function _v() { + const data = require("v8"); + _v = function () { + return data; + }; + return data; +} +function _util() { + const data = require("util"); + _util = function () { + return data; + }; + return data; +} +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +const own$1 = {}.hasOwnProperty; +const classRegExp = /^([A-Z][a-z\d]*)+$/; +const kTypes = new Set(['string', 'function', 'number', 'object', 'Function', 'Object', 'boolean', 'bigint', 'symbol']); +const codes = {}; +function formatList(array, type = 'and') { + return array.length < 3 ? array.join(` ${type} `) : `${array.slice(0, -1).join(', ')}, ${type} ${array[array.length - 1]}`; +} +const messages = new Map(); +const nodeInternalPrefix = '__node_internal_'; +let userStackTraceLimit; +codes.ERR_INVALID_ARG_TYPE = createError('ERR_INVALID_ARG_TYPE', (name, expected, actual) => { + _assert()(typeof name === 'string', "'name' must be a string"); + if (!Array.isArray(expected)) { + expected = [expected]; + } + let message = 'The '; + if (name.endsWith(' argument')) { + message += `${name} `; + } else { + const type = name.includes('.') ? 'property' : 'argument'; + message += `"${name}" ${type} `; + } + message += 'must be '; + const types = []; + const instances = []; + const other = []; + for (const value of expected) { + _assert()(typeof value === 'string', 'All expected entries have to be of type string'); + if (kTypes.has(value)) { + types.push(value.toLowerCase()); + } else if (classRegExp.exec(value) === null) { + _assert()(value !== 'object', 'The value "object" should be written as "Object"'); + other.push(value); + } else { + instances.push(value); + } + } + if (instances.length > 0) { + const pos = types.indexOf('object'); + if (pos !== -1) { + types.slice(pos, 1); + instances.push('Object'); + } + } + if (types.length > 0) { + message += `${types.length > 1 ? 'one of type' : 'of type'} ${formatList(types, 'or')}`; + if (instances.length > 0 || other.length > 0) message += ' or '; + } + if (instances.length > 0) { + message += `an instance of ${formatList(instances, 'or')}`; + if (other.length > 0) message += ' or '; + } + if (other.length > 0) { + if (other.length > 1) { + message += `one of ${formatList(other, 'or')}`; + } else { + if (other[0].toLowerCase() !== other[0]) message += 'an '; + message += `${other[0]}`; + } + } + message += `. Received ${determineSpecificType(actual)}`; + return message; +}, TypeError); +codes.ERR_INVALID_MODULE_SPECIFIER = createError('ERR_INVALID_MODULE_SPECIFIER', (request, reason, base = undefined) => { + return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ''}`; +}, TypeError); +codes.ERR_INVALID_PACKAGE_CONFIG = createError('ERR_INVALID_PACKAGE_CONFIG', (path, base, message) => { + return `Invalid package config ${path}${base ? ` while importing ${base}` : ''}${message ? `. ${message}` : ''}`; +}, Error); +codes.ERR_INVALID_PACKAGE_TARGET = createError('ERR_INVALID_PACKAGE_TARGET', (packagePath, key, target, isImport = false, base = undefined) => { + const relatedError = typeof target === 'string' && !isImport && target.length > 0 && !target.startsWith('./'); + if (key === '.') { + _assert()(isImport === false); + return `Invalid "exports" main target ${JSON.stringify(target)} defined ` + `in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ''}${relatedError ? '; targets must start with "./"' : ''}`; + } + return `Invalid "${isImport ? 'imports' : 'exports'}" target ${JSON.stringify(target)} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ''}${relatedError ? '; targets must start with "./"' : ''}`; +}, Error); +codes.ERR_MODULE_NOT_FOUND = createError('ERR_MODULE_NOT_FOUND', (path, base, exactUrl = false) => { + return `Cannot find ${exactUrl ? 'module' : 'package'} '${path}' imported from ${base}`; +}, Error); +codes.ERR_NETWORK_IMPORT_DISALLOWED = createError('ERR_NETWORK_IMPORT_DISALLOWED', "import of '%s' by %s is not supported: %s", Error); +codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError('ERR_PACKAGE_IMPORT_NOT_DEFINED', (specifier, packagePath, base) => { + return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath}package.json` : ''} imported from ${base}`; +}, TypeError); +codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError('ERR_PACKAGE_PATH_NOT_EXPORTED', (packagePath, subpath, base = undefined) => { + if (subpath === '.') return `No "exports" main defined in ${packagePath}package.json${base ? ` imported from ${base}` : ''}`; + return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${base ? ` imported from ${base}` : ''}`; +}, Error); +codes.ERR_UNSUPPORTED_DIR_IMPORT = createError('ERR_UNSUPPORTED_DIR_IMPORT', "Directory import '%s' is not supported " + 'resolving ES modules imported from %s', Error); +codes.ERR_UNSUPPORTED_RESOLVE_REQUEST = createError('ERR_UNSUPPORTED_RESOLVE_REQUEST', 'Failed to resolve module specifier "%s" from "%s": Invalid relative URL or base scheme is not hierarchical.', TypeError); +codes.ERR_UNKNOWN_FILE_EXTENSION = createError('ERR_UNKNOWN_FILE_EXTENSION', (extension, path) => { + return `Unknown file extension "${extension}" for ${path}`; +}, TypeError); +codes.ERR_INVALID_ARG_VALUE = createError('ERR_INVALID_ARG_VALUE', (name, value, reason = 'is invalid') => { + let inspected = (0, _util().inspect)(value); + if (inspected.length > 128) { + inspected = `${inspected.slice(0, 128)}...`; + } + const type = name.includes('.') ? 'property' : 'argument'; + return `The ${type} '${name}' ${reason}. Received ${inspected}`; +}, TypeError); +function createError(sym, value, constructor) { + messages.set(sym, value); + return makeNodeErrorWithCode(constructor, sym); +} +function makeNodeErrorWithCode(Base, key) { + return NodeError; + function NodeError(...parameters) { + const limit = Error.stackTraceLimit; + if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0; + const error = new Base(); + if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit; + const message = getMessage(key, parameters, error); + Object.defineProperties(error, { + message: { + value: message, + enumerable: false, + writable: true, + configurable: true + }, + toString: { + value() { + return `${this.name} [${key}]: ${this.message}`; + }, + enumerable: false, + writable: true, + configurable: true + } + }); + captureLargerStackTrace(error); + error.code = key; + return error; + } +} +function isErrorStackTraceLimitWritable() { + try { + if (_v().startupSnapshot.isBuildingSnapshot()) { + return false; + } + } catch (_unused) {} + const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit'); + if (desc === undefined) { + return Object.isExtensible(Error); + } + return own$1.call(desc, 'writable') && desc.writable !== undefined ? desc.writable : desc.set !== undefined; +} +function hideStackFrames(wrappedFunction) { + const hidden = nodeInternalPrefix + wrappedFunction.name; + Object.defineProperty(wrappedFunction, 'name', { + value: hidden + }); + return wrappedFunction; +} +const captureLargerStackTrace = hideStackFrames(function (error) { + const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable(); + if (stackTraceLimitIsWritable) { + userStackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = Number.POSITIVE_INFINITY; + } + Error.captureStackTrace(error); + if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit; + return error; +}); +function getMessage(key, parameters, self) { + const message = messages.get(key); + _assert()(message !== undefined, 'expected `message` to be found'); + if (typeof message === 'function') { + _assert()(message.length <= parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not ` + `match the required ones (${message.length}).`); + return Reflect.apply(message, self, parameters); + } + const regex = /%[dfijoOs]/g; + let expectedLength = 0; + while (regex.exec(message) !== null) expectedLength++; + _assert()(expectedLength === parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not ` + `match the required ones (${expectedLength}).`); + if (parameters.length === 0) return message; + parameters.unshift(message); + return Reflect.apply(_util().format, null, parameters); +} +function determineSpecificType(value) { + if (value === null || value === undefined) { + return String(value); + } + if (typeof value === 'function' && value.name) { + return `function ${value.name}`; + } + if (typeof value === 'object') { + if (value.constructor && value.constructor.name) { + return `an instance of ${value.constructor.name}`; + } + return `${(0, _util().inspect)(value, { + depth: -1 + })}`; + } + let inspected = (0, _util().inspect)(value, { + colors: false + }); + if (inspected.length > 28) { + inspected = `${inspected.slice(0, 25)}...`; + } + return `type ${typeof value} (${inspected})`; +} +const hasOwnProperty$1 = {}.hasOwnProperty; +const { + ERR_INVALID_PACKAGE_CONFIG: ERR_INVALID_PACKAGE_CONFIG$1 +} = codes; +const cache = new Map(); +function read(jsonPath, { + base, + specifier +}) { + const existing = cache.get(jsonPath); + if (existing) { + return existing; + } + let string; + try { + string = _fs().default.readFileSync(_path().toNamespacedPath(jsonPath), 'utf8'); + } catch (error) { + const exception = error; + if (exception.code !== 'ENOENT') { + throw exception; + } + } + const result = { + exists: false, + pjsonPath: jsonPath, + main: undefined, + name: undefined, + type: 'none', + exports: undefined, + imports: undefined + }; + if (string !== undefined) { + let parsed; + try { + parsed = JSON.parse(string); + } catch (error_) { + const cause = error_; + const error = new ERR_INVALID_PACKAGE_CONFIG$1(jsonPath, (base ? `"${specifier}" from ` : '') + (0, _url().fileURLToPath)(base || specifier), cause.message); + error.cause = cause; + throw error; + } + result.exists = true; + if (hasOwnProperty$1.call(parsed, 'name') && typeof parsed.name === 'string') { + result.name = parsed.name; + } + if (hasOwnProperty$1.call(parsed, 'main') && typeof parsed.main === 'string') { + result.main = parsed.main; + } + if (hasOwnProperty$1.call(parsed, 'exports')) { + result.exports = parsed.exports; + } + if (hasOwnProperty$1.call(parsed, 'imports')) { + result.imports = parsed.imports; + } + if (hasOwnProperty$1.call(parsed, 'type') && (parsed.type === 'commonjs' || parsed.type === 'module')) { + result.type = parsed.type; + } + } + cache.set(jsonPath, result); + return result; +} +function getPackageScopeConfig(resolved) { + let packageJSONUrl = new URL('package.json', resolved); + while (true) { + const packageJSONPath = packageJSONUrl.pathname; + if (packageJSONPath.endsWith('node_modules/package.json')) { + break; + } + const packageConfig = read((0, _url().fileURLToPath)(packageJSONUrl), { + specifier: resolved + }); + if (packageConfig.exists) { + return packageConfig; + } + const lastPackageJSONUrl = packageJSONUrl; + packageJSONUrl = new URL('../package.json', packageJSONUrl); + if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) { + break; + } + } + const packageJSONPath = (0, _url().fileURLToPath)(packageJSONUrl); + return { + pjsonPath: packageJSONPath, + exists: false, + type: 'none' + }; +} +function getPackageType(url) { + return getPackageScopeConfig(url).type; +} +const { + ERR_UNKNOWN_FILE_EXTENSION +} = codes; +const hasOwnProperty = {}.hasOwnProperty; +const extensionFormatMap = { + __proto__: null, + '.cjs': 'commonjs', + '.js': 'module', + '.json': 'json', + '.mjs': 'module' +}; +function mimeToFormat(mime) { + if (mime && /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime)) return 'module'; + if (mime === 'application/json') return 'json'; + return null; +} +const protocolHandlers = { + __proto__: null, + 'data:': getDataProtocolModuleFormat, + 'file:': getFileProtocolModuleFormat, + 'http:': getHttpProtocolModuleFormat, + 'https:': getHttpProtocolModuleFormat, + 'node:'() { + return 'builtin'; + } +}; +function getDataProtocolModuleFormat(parsed) { + const { + 1: mime + } = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(parsed.pathname) || [null, null, null]; + return mimeToFormat(mime); +} +function extname(url) { + const pathname = url.pathname; + let index = pathname.length; + while (index--) { + const code = pathname.codePointAt(index); + if (code === 47) { + return ''; + } + if (code === 46) { + return pathname.codePointAt(index - 1) === 47 ? '' : pathname.slice(index); + } + } + return ''; +} +function getFileProtocolModuleFormat(url, _context, ignoreErrors) { + const value = extname(url); + if (value === '.js') { + const packageType = getPackageType(url); + if (packageType !== 'none') { + return packageType; + } + return 'commonjs'; + } + if (value === '') { + const packageType = getPackageType(url); + if (packageType === 'none' || packageType === 'commonjs') { + return 'commonjs'; + } + return 'module'; + } + const format = extensionFormatMap[value]; + if (format) return format; + if (ignoreErrors) { + return undefined; + } + const filepath = (0, _url().fileURLToPath)(url); + throw new ERR_UNKNOWN_FILE_EXTENSION(value, filepath); +} +function getHttpProtocolModuleFormat() {} +function defaultGetFormatWithoutErrors(url, context) { + const protocol = url.protocol; + if (!hasOwnProperty.call(protocolHandlers, protocol)) { + return null; + } + return protocolHandlers[protocol](url, context, true) || null; +} +const { + ERR_INVALID_ARG_VALUE +} = codes; +const DEFAULT_CONDITIONS = Object.freeze(['node', 'import']); +const DEFAULT_CONDITIONS_SET = new Set(DEFAULT_CONDITIONS); +function getDefaultConditions() { + return DEFAULT_CONDITIONS; +} +function getDefaultConditionsSet() { + return DEFAULT_CONDITIONS_SET; +} +function getConditionsSet(conditions) { + if (conditions !== undefined && conditions !== getDefaultConditions()) { + if (!Array.isArray(conditions)) { + throw new ERR_INVALID_ARG_VALUE('conditions', conditions, 'expected an array'); + } + return new Set(conditions); + } + return getDefaultConditionsSet(); +} +const RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace]; +const { + ERR_NETWORK_IMPORT_DISALLOWED, + ERR_INVALID_MODULE_SPECIFIER, + ERR_INVALID_PACKAGE_CONFIG, + ERR_INVALID_PACKAGE_TARGET, + ERR_MODULE_NOT_FOUND, + ERR_PACKAGE_IMPORT_NOT_DEFINED, + ERR_PACKAGE_PATH_NOT_EXPORTED, + ERR_UNSUPPORTED_DIR_IMPORT, + ERR_UNSUPPORTED_RESOLVE_REQUEST +} = codes; +const own = {}.hasOwnProperty; +const invalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i; +const deprecatedInvalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i; +const invalidPackageNameRegEx = /^\.|%|\\/; +const patternRegEx = /\*/g; +const encodedSeparatorRegEx = /%2f|%5c/i; +const emittedPackageWarnings = new Set(); +const doubleSlashRegEx = /[/\\]{2}/; +function emitInvalidSegmentDeprecation(target, request, match, packageJsonUrl, internal, base, isTarget) { + if (_process().noDeprecation) { + return; + } + const pjsonPath = (0, _url().fileURLToPath)(packageJsonUrl); + const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null; + _process().emitWarning(`Use of deprecated ${double ? 'double slash' : 'leading or trailing slash matching'} resolving "${target}" for module ` + `request "${request}" ${request === match ? '' : `matched to "${match}" `}in the "${internal ? 'imports' : 'exports'}" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${(0, _url().fileURLToPath)(base)}` : ''}.`, 'DeprecationWarning', 'DEP0166'); +} +function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) { + if (_process().noDeprecation) { + return; + } + const format = defaultGetFormatWithoutErrors(url, { + parentURL: base.href + }); + if (format !== 'module') return; + const urlPath = (0, _url().fileURLToPath)(url.href); + const packagePath = (0, _url().fileURLToPath)(new (_url().URL)('.', packageJsonUrl)); + const basePath = (0, _url().fileURLToPath)(base); + if (!main) { + _process().emitWarning(`No "main" or "exports" field defined in the package.json for ${packagePath} resolving the main entry point "${urlPath.slice(packagePath.length)}", imported from ${basePath}.\nDefault "index" lookups for the main are deprecated for ES modules.`, 'DeprecationWarning', 'DEP0151'); + } else if (_path().resolve(packagePath, main) !== urlPath) { + _process().emitWarning(`Package ${packagePath} has a "main" field set to "${main}", ` + `excluding the full filename and extension to the resolved file at "${urlPath.slice(packagePath.length)}", imported from ${basePath}.\n Automatic extension resolution of the "main" field is ` + 'deprecated for ES modules.', 'DeprecationWarning', 'DEP0151'); + } +} +function tryStatSync(path) { + try { + return (0, _fs().statSync)(path); + } catch (_unused2) {} +} +function fileExists(url) { + const stats = (0, _fs().statSync)(url, { + throwIfNoEntry: false + }); + const isFile = stats ? stats.isFile() : undefined; + return isFile === null || isFile === undefined ? false : isFile; +} +function legacyMainResolve(packageJsonUrl, packageConfig, base) { + let guess; + if (packageConfig.main !== undefined) { + guess = new (_url().URL)(packageConfig.main, packageJsonUrl); + if (fileExists(guess)) return guess; + const tries = [`./${packageConfig.main}.js`, `./${packageConfig.main}.json`, `./${packageConfig.main}.node`, `./${packageConfig.main}/index.js`, `./${packageConfig.main}/index.json`, `./${packageConfig.main}/index.node`]; + let i = -1; + while (++i < tries.length) { + guess = new (_url().URL)(tries[i], packageJsonUrl); + if (fileExists(guess)) break; + guess = undefined; + } + if (guess) { + emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main); + return guess; + } + } + const tries = ['./index.js', './index.json', './index.node']; + let i = -1; + while (++i < tries.length) { + guess = new (_url().URL)(tries[i], packageJsonUrl); + if (fileExists(guess)) break; + guess = undefined; + } + if (guess) { + emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main); + return guess; + } + throw new ERR_MODULE_NOT_FOUND((0, _url().fileURLToPath)(new (_url().URL)('.', packageJsonUrl)), (0, _url().fileURLToPath)(base)); +} +function finalizeResolution(resolved, base, preserveSymlinks) { + if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) { + throw new ERR_INVALID_MODULE_SPECIFIER(resolved.pathname, 'must not include encoded "/" or "\\" characters', (0, _url().fileURLToPath)(base)); + } + let filePath; + try { + filePath = (0, _url().fileURLToPath)(resolved); + } catch (error) { + const cause = error; + Object.defineProperty(cause, 'input', { + value: String(resolved) + }); + Object.defineProperty(cause, 'module', { + value: String(base) + }); + throw cause; + } + const stats = tryStatSync(filePath.endsWith('/') ? filePath.slice(-1) : filePath); + if (stats && stats.isDirectory()) { + const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, (0, _url().fileURLToPath)(base)); + error.url = String(resolved); + throw error; + } + if (!stats || !stats.isFile()) { + const error = new ERR_MODULE_NOT_FOUND(filePath || resolved.pathname, base && (0, _url().fileURLToPath)(base), true); + error.url = String(resolved); + throw error; + } + if (!preserveSymlinks) { + const real = (0, _fs().realpathSync)(filePath); + const { + search, + hash + } = resolved; + resolved = (0, _url().pathToFileURL)(real + (filePath.endsWith(_path().sep) ? '/' : '')); + resolved.search = search; + resolved.hash = hash; + } + return resolved; +} +function importNotDefined(specifier, packageJsonUrl, base) { + return new ERR_PACKAGE_IMPORT_NOT_DEFINED(specifier, packageJsonUrl && (0, _url().fileURLToPath)(new (_url().URL)('.', packageJsonUrl)), (0, _url().fileURLToPath)(base)); +} +function exportsNotFound(subpath, packageJsonUrl, base) { + return new ERR_PACKAGE_PATH_NOT_EXPORTED((0, _url().fileURLToPath)(new (_url().URL)('.', packageJsonUrl)), subpath, base && (0, _url().fileURLToPath)(base)); +} +function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) { + const reason = `request is not a valid match in pattern "${match}" for the "${internal ? 'imports' : 'exports'}" resolution of ${(0, _url().fileURLToPath)(packageJsonUrl)}`; + throw new ERR_INVALID_MODULE_SPECIFIER(request, reason, base && (0, _url().fileURLToPath)(base)); +} +function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) { + target = typeof target === 'object' && target !== null ? JSON.stringify(target, null, '') : `${target}`; + return new ERR_INVALID_PACKAGE_TARGET((0, _url().fileURLToPath)(new (_url().URL)('.', packageJsonUrl)), subpath, target, internal, base && (0, _url().fileURLToPath)(base)); +} +function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) { + if (subpath !== '' && !pattern && target[target.length - 1] !== '/') throw invalidPackageTarget(match, target, packageJsonUrl, internal, base); + if (!target.startsWith('./')) { + if (internal && !target.startsWith('../') && !target.startsWith('/')) { + let isURL = false; + try { + new (_url().URL)(target); + isURL = true; + } catch (_unused3) {} + if (!isURL) { + const exportTarget = pattern ? RegExpPrototypeSymbolReplace.call(patternRegEx, target, () => subpath) : target + subpath; + return packageResolve(exportTarget, packageJsonUrl, conditions); + } + } + throw invalidPackageTarget(match, target, packageJsonUrl, internal, base); + } + if (invalidSegmentRegEx.exec(target.slice(2)) !== null) { + if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) { + if (!isPathMap) { + const request = pattern ? match.replace('*', () => subpath) : match + subpath; + const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(patternRegEx, target, () => subpath) : target; + emitInvalidSegmentDeprecation(resolvedTarget, request, match, packageJsonUrl, internal, base, true); + } + } else { + throw invalidPackageTarget(match, target, packageJsonUrl, internal, base); + } + } + const resolved = new (_url().URL)(target, packageJsonUrl); + const resolvedPath = resolved.pathname; + const packagePath = new (_url().URL)('.', packageJsonUrl).pathname; + if (!resolvedPath.startsWith(packagePath)) throw invalidPackageTarget(match, target, packageJsonUrl, internal, base); + if (subpath === '') return resolved; + if (invalidSegmentRegEx.exec(subpath) !== null) { + const request = pattern ? match.replace('*', () => subpath) : match + subpath; + if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) { + if (!isPathMap) { + const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(patternRegEx, target, () => subpath) : target; + emitInvalidSegmentDeprecation(resolvedTarget, request, match, packageJsonUrl, internal, base, false); + } + } else { + throwInvalidSubpath(request, match, packageJsonUrl, internal, base); + } + } + if (pattern) { + return new (_url().URL)(RegExpPrototypeSymbolReplace.call(patternRegEx, resolved.href, () => subpath)); + } + return new (_url().URL)(subpath, resolved); +} +function isArrayIndex(key) { + const keyNumber = Number(key); + if (`${keyNumber}` !== key) return false; + return keyNumber >= 0 && keyNumber < 0xffffffff; +} +function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) { + if (typeof target === 'string') { + return resolvePackageTargetString(target, subpath, packageSubpath, packageJsonUrl, base, pattern, internal, isPathMap, conditions); + } + if (Array.isArray(target)) { + const targetList = target; + if (targetList.length === 0) return null; + let lastException; + let i = -1; + while (++i < targetList.length) { + const targetItem = targetList[i]; + let resolveResult; + try { + resolveResult = resolvePackageTarget(packageJsonUrl, targetItem, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions); + } catch (error) { + const exception = error; + lastException = exception; + if (exception.code === 'ERR_INVALID_PACKAGE_TARGET') continue; + throw error; + } + if (resolveResult === undefined) continue; + if (resolveResult === null) { + lastException = null; + continue; + } + return resolveResult; + } + if (lastException === undefined || lastException === null) { + return null; + } + throw lastException; + } + if (typeof target === 'object' && target !== null) { + const keys = Object.getOwnPropertyNames(target); + let i = -1; + while (++i < keys.length) { + const key = keys[i]; + if (isArrayIndex(key)) { + throw new ERR_INVALID_PACKAGE_CONFIG((0, _url().fileURLToPath)(packageJsonUrl), base, '"exports" cannot contain numeric property keys.'); + } + } + i = -1; + while (++i < keys.length) { + const key = keys[i]; + if (key === 'default' || conditions && conditions.has(key)) { + const conditionalTarget = target[key]; + const resolveResult = resolvePackageTarget(packageJsonUrl, conditionalTarget, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions); + if (resolveResult === undefined) continue; + return resolveResult; + } + } + return null; + } + if (target === null) { + return null; + } + throw invalidPackageTarget(packageSubpath, target, packageJsonUrl, internal, base); +} +function isConditionalExportsMainSugar(exports, packageJsonUrl, base) { + if (typeof exports === 'string' || Array.isArray(exports)) return true; + if (typeof exports !== 'object' || exports === null) return false; + const keys = Object.getOwnPropertyNames(exports); + let isConditionalSugar = false; + let i = 0; + let keyIndex = -1; + while (++keyIndex < keys.length) { + const key = keys[keyIndex]; + const currentIsConditionalSugar = key === '' || key[0] !== '.'; + if (i++ === 0) { + isConditionalSugar = currentIsConditionalSugar; + } else if (isConditionalSugar !== currentIsConditionalSugar) { + throw new ERR_INVALID_PACKAGE_CONFIG((0, _url().fileURLToPath)(packageJsonUrl), base, '"exports" cannot contain some keys starting with \'.\' and some not.' + ' The exports object must either be an object of package subpath keys' + ' or an object of main entry condition name keys only.'); + } + } + return isConditionalSugar; +} +function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) { + if (_process().noDeprecation) { + return; + } + const pjsonPath = (0, _url().fileURLToPath)(pjsonUrl); + if (emittedPackageWarnings.has(pjsonPath + '|' + match)) return; + emittedPackageWarnings.add(pjsonPath + '|' + match); + _process().emitWarning(`Use of deprecated trailing slash pattern mapping "${match}" in the ` + `"exports" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${(0, _url().fileURLToPath)(base)}` : ''}. Mapping specifiers ending in "/" is no longer supported.`, 'DeprecationWarning', 'DEP0155'); +} +function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) { + let exports = packageConfig.exports; + if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) { + exports = { + '.': exports + }; + } + if (own.call(exports, packageSubpath) && !packageSubpath.includes('*') && !packageSubpath.endsWith('/')) { + const target = exports[packageSubpath]; + const resolveResult = resolvePackageTarget(packageJsonUrl, target, '', packageSubpath, base, false, false, false, conditions); + if (resolveResult === null || resolveResult === undefined) { + throw exportsNotFound(packageSubpath, packageJsonUrl, base); + } + return resolveResult; + } + let bestMatch = ''; + let bestMatchSubpath = ''; + const keys = Object.getOwnPropertyNames(exports); + let i = -1; + while (++i < keys.length) { + const key = keys[i]; + const patternIndex = key.indexOf('*'); + if (patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex))) { + if (packageSubpath.endsWith('/')) { + emitTrailingSlashPatternDeprecation(packageSubpath, packageJsonUrl, base); + } + const patternTrailer = key.slice(patternIndex + 1); + if (packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf('*') === patternIndex) { + bestMatch = key; + bestMatchSubpath = packageSubpath.slice(patternIndex, packageSubpath.length - patternTrailer.length); + } + } + } + if (bestMatch) { + const target = exports[bestMatch]; + const resolveResult = resolvePackageTarget(packageJsonUrl, target, bestMatchSubpath, bestMatch, base, true, false, packageSubpath.endsWith('/'), conditions); + if (resolveResult === null || resolveResult === undefined) { + throw exportsNotFound(packageSubpath, packageJsonUrl, base); + } + return resolveResult; + } + throw exportsNotFound(packageSubpath, packageJsonUrl, base); +} +function patternKeyCompare(a, b) { + const aPatternIndex = a.indexOf('*'); + const bPatternIndex = b.indexOf('*'); + const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; + const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1; + if (baseLengthA > baseLengthB) return -1; + if (baseLengthB > baseLengthA) return 1; + if (aPatternIndex === -1) return 1; + if (bPatternIndex === -1) return -1; + if (a.length > b.length) return -1; + if (b.length > a.length) return 1; + return 0; +} +function packageImportsResolve(name, base, conditions) { + if (name === '#' || name.startsWith('#/') || name.endsWith('/')) { + const reason = 'is not a valid internal imports specifier name'; + throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, (0, _url().fileURLToPath)(base)); + } + let packageJsonUrl; + const packageConfig = getPackageScopeConfig(base); + if (packageConfig.exists) { + packageJsonUrl = (0, _url().pathToFileURL)(packageConfig.pjsonPath); + const imports = packageConfig.imports; + if (imports) { + if (own.call(imports, name) && !name.includes('*')) { + const resolveResult = resolvePackageTarget(packageJsonUrl, imports[name], '', name, base, false, true, false, conditions); + if (resolveResult !== null && resolveResult !== undefined) { + return resolveResult; + } + } else { + let bestMatch = ''; + let bestMatchSubpath = ''; + const keys = Object.getOwnPropertyNames(imports); + let i = -1; + while (++i < keys.length) { + const key = keys[i]; + const patternIndex = key.indexOf('*'); + if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) { + const patternTrailer = key.slice(patternIndex + 1); + if (name.length >= key.length && name.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf('*') === patternIndex) { + bestMatch = key; + bestMatchSubpath = name.slice(patternIndex, name.length - patternTrailer.length); + } + } + } + if (bestMatch) { + const target = imports[bestMatch]; + const resolveResult = resolvePackageTarget(packageJsonUrl, target, bestMatchSubpath, bestMatch, base, true, true, false, conditions); + if (resolveResult !== null && resolveResult !== undefined) { + return resolveResult; + } + } + } + } + } + throw importNotDefined(name, packageJsonUrl, base); +} +function parsePackageName(specifier, base) { + let separatorIndex = specifier.indexOf('/'); + let validPackageName = true; + let isScoped = false; + if (specifier[0] === '@') { + isScoped = true; + if (separatorIndex === -1 || specifier.length === 0) { + validPackageName = false; + } else { + separatorIndex = specifier.indexOf('/', separatorIndex + 1); + } + } + const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex); + if (invalidPackageNameRegEx.exec(packageName) !== null) { + validPackageName = false; + } + if (!validPackageName) { + throw new ERR_INVALID_MODULE_SPECIFIER(specifier, 'is not a valid package name', (0, _url().fileURLToPath)(base)); + } + const packageSubpath = '.' + (separatorIndex === -1 ? '' : specifier.slice(separatorIndex)); + return { + packageName, + packageSubpath, + isScoped + }; +} +function packageResolve(specifier, base, conditions) { + if (_module().builtinModules.includes(specifier)) { + return new (_url().URL)('node:' + specifier); + } + const { + packageName, + packageSubpath, + isScoped + } = parsePackageName(specifier, base); + const packageConfig = getPackageScopeConfig(base); + if (packageConfig.exists) { + const packageJsonUrl = (0, _url().pathToFileURL)(packageConfig.pjsonPath); + if (packageConfig.name === packageName && packageConfig.exports !== undefined && packageConfig.exports !== null) { + return packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions); + } + } + let packageJsonUrl = new (_url().URL)('./node_modules/' + packageName + '/package.json', base); + let packageJsonPath = (0, _url().fileURLToPath)(packageJsonUrl); + let lastPath; + do { + const stat = tryStatSync(packageJsonPath.slice(0, -13)); + if (!stat || !stat.isDirectory()) { + lastPath = packageJsonPath; + packageJsonUrl = new (_url().URL)((isScoped ? '../../../../node_modules/' : '../../../node_modules/') + packageName + '/package.json', packageJsonUrl); + packageJsonPath = (0, _url().fileURLToPath)(packageJsonUrl); + continue; + } + const packageConfig = read(packageJsonPath, { + base, + specifier + }); + if (packageConfig.exports !== undefined && packageConfig.exports !== null) { + return packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions); + } + if (packageSubpath === '.') { + return legacyMainResolve(packageJsonUrl, packageConfig, base); + } + return new (_url().URL)(packageSubpath, packageJsonUrl); + } while (packageJsonPath.length !== lastPath.length); + throw new ERR_MODULE_NOT_FOUND(packageName, (0, _url().fileURLToPath)(base), false); +} +function isRelativeSpecifier(specifier) { + if (specifier[0] === '.') { + if (specifier.length === 1 || specifier[1] === '/') return true; + if (specifier[1] === '.' && (specifier.length === 2 || specifier[2] === '/')) { + return true; + } + } + return false; +} +function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) { + if (specifier === '') return false; + if (specifier[0] === '/') return true; + return isRelativeSpecifier(specifier); +} +function moduleResolve(specifier, base, conditions, preserveSymlinks) { + const protocol = base.protocol; + const isData = protocol === 'data:'; + const isRemote = isData || protocol === 'http:' || protocol === 'https:'; + let resolved; + if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) { + try { + resolved = new (_url().URL)(specifier, base); + } catch (error_) { + const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base); + error.cause = error_; + throw error; + } + } else if (protocol === 'file:' && specifier[0] === '#') { + resolved = packageImportsResolve(specifier, base, conditions); + } else { + try { + resolved = new (_url().URL)(specifier); + } catch (error_) { + if (isRemote && !_module().builtinModules.includes(specifier)) { + const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base); + error.cause = error_; + throw error; + } + resolved = packageResolve(specifier, base, conditions); + } + } + _assert()(resolved !== undefined, 'expected to be defined'); + if (resolved.protocol !== 'file:') { + return resolved; + } + return finalizeResolution(resolved, base, preserveSymlinks); +} +function checkIfDisallowedImport(specifier, parsed, parsedParentURL) { + if (parsedParentURL) { + const parentProtocol = parsedParentURL.protocol; + if (parentProtocol === 'http:' || parentProtocol === 'https:') { + if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) { + const parsedProtocol = parsed == null ? void 0 : parsed.protocol; + if (parsedProtocol && parsedProtocol !== 'https:' && parsedProtocol !== 'http:') { + throw new ERR_NETWORK_IMPORT_DISALLOWED(specifier, parsedParentURL, 'remote imports cannot import from a local location.'); + } + return { + url: (parsed == null ? void 0 : parsed.href) || '' + }; + } + if (_module().builtinModules.includes(specifier)) { + throw new ERR_NETWORK_IMPORT_DISALLOWED(specifier, parsedParentURL, 'remote imports cannot import from a local location.'); + } + throw new ERR_NETWORK_IMPORT_DISALLOWED(specifier, parsedParentURL, 'only relative and absolute specifiers are supported.'); + } + } +} +function isURL(self) { + return Boolean(self && typeof self === 'object' && 'href' in self && typeof self.href === 'string' && 'protocol' in self && typeof self.protocol === 'string' && self.href && self.protocol); +} +function throwIfInvalidParentURL(parentURL) { + if (parentURL === undefined) { + return; + } + if (typeof parentURL !== 'string' && !isURL(parentURL)) { + throw new codes.ERR_INVALID_ARG_TYPE('parentURL', ['string', 'URL'], parentURL); + } +} +function defaultResolve(specifier, context = {}) { + const { + parentURL + } = context; + _assert()(parentURL !== undefined, 'expected `parentURL` to be defined'); + throwIfInvalidParentURL(parentURL); + let parsedParentURL; + if (parentURL) { + try { + parsedParentURL = new (_url().URL)(parentURL); + } catch (_unused4) {} + } + let parsed; + let protocol; + try { + parsed = shouldBeTreatedAsRelativeOrAbsolutePath(specifier) ? new (_url().URL)(specifier, parsedParentURL) : new (_url().URL)(specifier); + protocol = parsed.protocol; + if (protocol === 'data:') { + return { + url: parsed.href, + format: null + }; + } + } catch (_unused5) {} + const maybeReturn = checkIfDisallowedImport(specifier, parsed, parsedParentURL); + if (maybeReturn) return maybeReturn; + if (protocol === undefined && parsed) { + protocol = parsed.protocol; + } + if (protocol === 'node:') { + return { + url: specifier + }; + } + if (parsed && parsed.protocol === 'node:') return { + url: specifier + }; + const conditions = getConditionsSet(context.conditions); + const url = moduleResolve(specifier, new (_url().URL)(parentURL), conditions, false); + return { + url: url.href, + format: defaultGetFormatWithoutErrors(url, { + parentURL + }) + }; +} +function resolve(specifier, parent) { + if (!parent) { + throw new Error('Please pass `parent`: `import-meta-resolve` cannot ponyfill that'); + } + try { + return defaultResolve(specifier, { + parentURL: parent + }).url; + } catch (error) { + const exception = error; + if ((exception.code === 'ERR_UNSUPPORTED_DIR_IMPORT' || exception.code === 'ERR_MODULE_NOT_FOUND') && typeof exception.url === 'string') { + return exception.url; + } + throw error; + } +} +0 && 0; + +//# sourceMappingURL=import-meta-resolve.js.map diff --git a/node_modules/@babel/core/lib/vendor/import-meta-resolve.js.map b/node_modules/@babel/core/lib/vendor/import-meta-resolve.js.map new file mode 100644 index 0000000..5265b7c --- /dev/null +++ b/node_modules/@babel/core/lib/vendor/import-meta-resolve.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_assert","data","require","_fs","_interopRequireWildcard","_process","_url","_path","_module","_v","_util","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","hasOwnProperty","call","i","set","own$1","classRegExp","kTypes","Set","codes","formatList","array","type","length","join","slice","messages","Map","nodeInternalPrefix","userStackTraceLimit","ERR_INVALID_ARG_TYPE","createError","name","expected","actual","assert","Array","isArray","message","endsWith","includes","types","instances","other","value","push","toLowerCase","exec","pos","indexOf","determineSpecificType","TypeError","ERR_INVALID_MODULE_SPECIFIER","request","reason","base","undefined","ERR_INVALID_PACKAGE_CONFIG","path","Error","ERR_INVALID_PACKAGE_TARGET","packagePath","key","target","isImport","relatedError","startsWith","JSON","stringify","ERR_MODULE_NOT_FOUND","exactUrl","ERR_NETWORK_IMPORT_DISALLOWED","ERR_PACKAGE_IMPORT_NOT_DEFINED","specifier","ERR_PACKAGE_PATH_NOT_EXPORTED","subpath","ERR_UNSUPPORTED_DIR_IMPORT","ERR_UNSUPPORTED_RESOLVE_REQUEST","ERR_UNKNOWN_FILE_EXTENSION","extension","ERR_INVALID_ARG_VALUE","inspected","inspect","sym","constructor","makeNodeErrorWithCode","Base","NodeError","parameters","limit","stackTraceLimit","isErrorStackTraceLimitWritable","error","getMessage","defineProperties","enumerable","writable","configurable","toString","captureLargerStackTrace","code","v8","startupSnapshot","isBuildingSnapshot","_unused","desc","isExtensible","hideStackFrames","wrappedFunction","hidden","stackTraceLimitIsWritable","Number","POSITIVE_INFINITY","captureStackTrace","self","Reflect","apply","regex","expectedLength","unshift","format","String","depth","colors","hasOwnProperty$1","ERR_INVALID_PACKAGE_CONFIG$1","cache","read","jsonPath","existing","string","fs","readFileSync","toNamespacedPath","exception","result","exists","pjsonPath","main","exports","imports","parsed","parse","error_","cause","fileURLToPath","getPackageScopeConfig","resolved","packageJSONUrl","URL","packageJSONPath","pathname","packageConfig","lastPackageJSONUrl","getPackageType","url","extensionFormatMap","mimeToFormat","mime","test","protocolHandlers","getDataProtocolModuleFormat","getFileProtocolModuleFormat","getHttpProtocolModuleFormat","node:","extname","index","codePointAt","_context","ignoreErrors","packageType","filepath","defaultGetFormatWithoutErrors","context","protocol","DEFAULT_CONDITIONS","freeze","DEFAULT_CONDITIONS_SET","getDefaultConditions","getDefaultConditionsSet","getConditionsSet","conditions","RegExpPrototypeSymbolReplace","RegExp","prototype","Symbol","replace","own","invalidSegmentRegEx","deprecatedInvalidSegmentRegEx","invalidPackageNameRegEx","patternRegEx","encodedSeparatorRegEx","emittedPackageWarnings","doubleSlashRegEx","emitInvalidSegmentDeprecation","match","packageJsonUrl","internal","isTarget","process","noDeprecation","double","emitWarning","emitLegacyIndexDeprecation","parentURL","href","urlPath","URL$1","basePath","resolve","tryStatSync","statSync","_unused2","fileExists","stats","throwIfNoEntry","isFile","legacyMainResolve","guess","tries","finalizeResolution","preserveSymlinks","filePath","isDirectory","real","realpathSync","search","hash","pathToFileURL","sep","importNotDefined","exportsNotFound","throwInvalidSubpath","invalidPackageTarget","resolvePackageTargetString","pattern","isPathMap","isURL","_unused3","exportTarget","packageResolve","resolvedTarget","resolvedPath","isArrayIndex","keyNumber","resolvePackageTarget","packageSubpath","targetList","lastException","targetItem","resolveResult","keys","getOwnPropertyNames","conditionalTarget","isConditionalExportsMainSugar","isConditionalSugar","keyIndex","currentIsConditionalSugar","emitTrailingSlashPatternDeprecation","pjsonUrl","add","packageExportsResolve","bestMatch","bestMatchSubpath","patternIndex","patternTrailer","patternKeyCompare","lastIndexOf","b","aPatternIndex","bPatternIndex","baseLengthA","baseLengthB","packageImportsResolve","parsePackageName","separatorIndex","validPackageName","isScoped","packageName","builtinModules","packageJsonPath","lastPath","stat","isRelativeSpecifier","shouldBeTreatedAsRelativeOrAbsolutePath","moduleResolve","isData","isRemote","checkIfDisallowedImport","parsedParentURL","parentProtocol","parsedProtocol","Boolean","throwIfInvalidParentURL","defaultResolve","_unused4","_unused5","maybeReturn","parent"],"sources":["../../src/vendor/import-meta-resolve.js"],"sourcesContent":["\n/****************************************************************************\\\n * NOTE FROM BABEL AUTHORS *\n * This file is inlined from https://github.com/wooorm/import-meta-resolve, *\n * because we need to compile it to CommonJS. *\n\\****************************************************************************/\n\n/*\n(The MIT License)\n\nCopyright (c) 2021 Titus Wormer \n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n---\n\nThis is a derivative work based on:\n.\nWhich is licensed:\n\n\"\"\"\nCopyright Node.js contributors. All rights reserved.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to\ndeal in the Software without restriction, including without limitation the\nrights to use, copy, modify, merge, publish, distribute, sublicense, and/or\nsell copies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\nIN THE SOFTWARE.\n\"\"\"\n\nThis license applies to parts of Node.js originating from the\nhttps://github.com/joyent/node repository:\n\n\"\"\"\nCopyright Joyent, Inc. and other Node contributors. All rights reserved.\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to\ndeal in the Software without restriction, including without limitation the\nrights to use, copy, modify, merge, publish, distribute, sublicense, and/or\nsell copies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\nIN THE SOFTWARE.\n\"\"\"\n*/\n\nimport assert from 'assert';\nimport fs, { realpathSync, statSync } from 'fs';\nimport process from 'process';\nimport { fileURLToPath, URL as URL$1, pathToFileURL } from 'url';\nimport path from 'path';\nimport { builtinModules } from 'module';\nimport v8 from 'v8';\nimport { format, inspect } from 'util';\n\n/**\n * @typedef ErrnoExceptionFields\n * @property {number | undefined} [errnode]\n * @property {string | undefined} [code]\n * @property {string | undefined} [path]\n * @property {string | undefined} [syscall]\n * @property {string | undefined} [url]\n *\n * @typedef {Error & ErrnoExceptionFields} ErrnoException\n */\n\n\nconst own$1 = {}.hasOwnProperty;\n\nconst classRegExp = /^([A-Z][a-z\\d]*)+$/;\n// Sorted by a rough estimate on most frequently used entries.\nconst kTypes = new Set([\n 'string',\n 'function',\n 'number',\n 'object',\n // Accept 'Function' and 'Object' as alternative to the lower cased version.\n 'Function',\n 'Object',\n 'boolean',\n 'bigint',\n 'symbol'\n]);\n\nconst codes = {};\n\n/**\n * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.\n * We cannot use Intl.ListFormat because it's not available in\n * --without-intl builds.\n *\n * @param {Array} array\n * An array of strings.\n * @param {string} [type]\n * The list type to be inserted before the last element.\n * @returns {string}\n */\nfunction formatList(array, type = 'and') {\n return array.length < 3\n ? array.join(` ${type} `)\n : `${array.slice(0, -1).join(', ')}, ${type} ${array[array.length - 1]}`\n}\n\n/** @type {Map} */\nconst messages = new Map();\nconst nodeInternalPrefix = '__node_internal_';\n/** @type {number} */\nlet userStackTraceLimit;\n\ncodes.ERR_INVALID_ARG_TYPE = createError(\n 'ERR_INVALID_ARG_TYPE',\n /**\n * @param {string} name\n * @param {Array | string} expected\n * @param {unknown} actual\n */\n (name, expected, actual) => {\n assert(typeof name === 'string', \"'name' must be a string\");\n if (!Array.isArray(expected)) {\n expected = [expected];\n }\n\n let message = 'The ';\n if (name.endsWith(' argument')) {\n // For cases like 'first argument'\n message += `${name} `;\n } else {\n const type = name.includes('.') ? 'property' : 'argument';\n message += `\"${name}\" ${type} `;\n }\n\n message += 'must be ';\n\n /** @type {Array} */\n const types = [];\n /** @type {Array} */\n const instances = [];\n /** @type {Array} */\n const other = [];\n\n for (const value of expected) {\n assert(\n typeof value === 'string',\n 'All expected entries have to be of type string'\n );\n\n if (kTypes.has(value)) {\n types.push(value.toLowerCase());\n } else if (classRegExp.exec(value) === null) {\n assert(\n value !== 'object',\n 'The value \"object\" should be written as \"Object\"'\n );\n other.push(value);\n } else {\n instances.push(value);\n }\n }\n\n // Special handle `object` in case other instances are allowed to outline\n // the differences between each other.\n if (instances.length > 0) {\n const pos = types.indexOf('object');\n if (pos !== -1) {\n types.slice(pos, 1);\n instances.push('Object');\n }\n }\n\n if (types.length > 0) {\n message += `${types.length > 1 ? 'one of type' : 'of type'} ${formatList(\n types,\n 'or'\n )}`;\n if (instances.length > 0 || other.length > 0) message += ' or ';\n }\n\n if (instances.length > 0) {\n message += `an instance of ${formatList(instances, 'or')}`;\n if (other.length > 0) message += ' or ';\n }\n\n if (other.length > 0) {\n if (other.length > 1) {\n message += `one of ${formatList(other, 'or')}`;\n } else {\n if (other[0].toLowerCase() !== other[0]) message += 'an ';\n message += `${other[0]}`;\n }\n }\n\n message += `. Received ${determineSpecificType(actual)}`;\n\n return message\n },\n TypeError\n);\n\ncodes.ERR_INVALID_MODULE_SPECIFIER = createError(\n 'ERR_INVALID_MODULE_SPECIFIER',\n /**\n * @param {string} request\n * @param {string} reason\n * @param {string} [base]\n */\n (request, reason, base = undefined) => {\n return `Invalid module \"${request}\" ${reason}${\n base ? ` imported from ${base}` : ''\n }`\n },\n TypeError\n);\n\ncodes.ERR_INVALID_PACKAGE_CONFIG = createError(\n 'ERR_INVALID_PACKAGE_CONFIG',\n /**\n * @param {string} path\n * @param {string} [base]\n * @param {string} [message]\n */\n (path, base, message) => {\n return `Invalid package config ${path}${\n base ? ` while importing ${base}` : ''\n }${message ? `. ${message}` : ''}`\n },\n Error\n);\n\ncodes.ERR_INVALID_PACKAGE_TARGET = createError(\n 'ERR_INVALID_PACKAGE_TARGET',\n /**\n * @param {string} packagePath\n * @param {string} key\n * @param {unknown} target\n * @param {boolean} [isImport=false]\n * @param {string} [base]\n */\n (packagePath, key, target, isImport = false, base = undefined) => {\n const relatedError =\n typeof target === 'string' &&\n !isImport &&\n target.length > 0 &&\n !target.startsWith('./');\n if (key === '.') {\n assert(isImport === false);\n return (\n `Invalid \"exports\" main target ${JSON.stringify(target)} defined ` +\n `in the package config ${packagePath}package.json${\n base ? ` imported from ${base}` : ''\n }${relatedError ? '; targets must start with \"./\"' : ''}`\n )\n }\n\n return `Invalid \"${\n isImport ? 'imports' : 'exports'\n }\" target ${JSON.stringify(\n target\n )} defined for '${key}' in the package config ${packagePath}package.json${\n base ? ` imported from ${base}` : ''\n }${relatedError ? '; targets must start with \"./\"' : ''}`\n },\n Error\n);\n\ncodes.ERR_MODULE_NOT_FOUND = createError(\n 'ERR_MODULE_NOT_FOUND',\n /**\n * @param {string} path\n * @param {string} base\n * @param {boolean} [exactUrl]\n */\n (path, base, exactUrl = false) => {\n return `Cannot find ${\n exactUrl ? 'module' : 'package'\n } '${path}' imported from ${base}`\n },\n Error\n);\n\ncodes.ERR_NETWORK_IMPORT_DISALLOWED = createError(\n 'ERR_NETWORK_IMPORT_DISALLOWED',\n \"import of '%s' by %s is not supported: %s\",\n Error\n);\n\ncodes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError(\n 'ERR_PACKAGE_IMPORT_NOT_DEFINED',\n /**\n * @param {string} specifier\n * @param {string} packagePath\n * @param {string} base\n */\n (specifier, packagePath, base) => {\n return `Package import specifier \"${specifier}\" is not defined${\n packagePath ? ` in package ${packagePath}package.json` : ''\n } imported from ${base}`\n },\n TypeError\n);\n\ncodes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError(\n 'ERR_PACKAGE_PATH_NOT_EXPORTED',\n /**\n * @param {string} packagePath\n * @param {string} subpath\n * @param {string} [base]\n */\n (packagePath, subpath, base = undefined) => {\n if (subpath === '.')\n return `No \"exports\" main defined in ${packagePath}package.json${\n base ? ` imported from ${base}` : ''\n }`\n return `Package subpath '${subpath}' is not defined by \"exports\" in ${packagePath}package.json${\n base ? ` imported from ${base}` : ''\n }`\n },\n Error\n);\n\ncodes.ERR_UNSUPPORTED_DIR_IMPORT = createError(\n 'ERR_UNSUPPORTED_DIR_IMPORT',\n \"Directory import '%s' is not supported \" +\n 'resolving ES modules imported from %s',\n Error\n);\n\ncodes.ERR_UNSUPPORTED_RESOLVE_REQUEST = createError(\n 'ERR_UNSUPPORTED_RESOLVE_REQUEST',\n 'Failed to resolve module specifier \"%s\" from \"%s\": Invalid relative URL or base scheme is not hierarchical.',\n TypeError\n);\n\ncodes.ERR_UNKNOWN_FILE_EXTENSION = createError(\n 'ERR_UNKNOWN_FILE_EXTENSION',\n /**\n * @param {string} extension\n * @param {string} path\n */\n (extension, path) => {\n return `Unknown file extension \"${extension}\" for ${path}`\n },\n TypeError\n);\n\ncodes.ERR_INVALID_ARG_VALUE = createError(\n 'ERR_INVALID_ARG_VALUE',\n /**\n * @param {string} name\n * @param {unknown} value\n * @param {string} [reason='is invalid']\n */\n (name, value, reason = 'is invalid') => {\n let inspected = inspect(value);\n\n if (inspected.length > 128) {\n inspected = `${inspected.slice(0, 128)}...`;\n }\n\n const type = name.includes('.') ? 'property' : 'argument';\n\n return `The ${type} '${name}' ${reason}. Received ${inspected}`\n },\n TypeError\n // Note: extra classes have been shaken out.\n // , RangeError\n);\n\n/**\n * Utility function for registering the error codes. Only used here. Exported\n * *only* to allow for testing.\n * @param {string} sym\n * @param {MessageFunction | string} value\n * @param {ErrorConstructor} constructor\n * @returns {new (...parameters: Array) => Error}\n */\nfunction createError(sym, value, constructor) {\n // Special case for SystemError that formats the error message differently\n // The SystemErrors only have SystemError as their base classes.\n messages.set(sym, value);\n\n return makeNodeErrorWithCode(constructor, sym)\n}\n\n/**\n * @param {ErrorConstructor} Base\n * @param {string} key\n * @returns {ErrorConstructor}\n */\nfunction makeNodeErrorWithCode(Base, key) {\n // @ts-expect-error It’s a Node error.\n return NodeError\n /**\n * @param {Array} parameters\n */\n function NodeError(...parameters) {\n const limit = Error.stackTraceLimit;\n if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;\n const error = new Base();\n // Reset the limit and setting the name property.\n if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;\n const message = getMessage(key, parameters, error);\n Object.defineProperties(error, {\n // Note: no need to implement `kIsNodeError` symbol, would be hard,\n // probably.\n message: {\n value: message,\n enumerable: false,\n writable: true,\n configurable: true\n },\n toString: {\n /** @this {Error} */\n value() {\n return `${this.name} [${key}]: ${this.message}`\n },\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n\n captureLargerStackTrace(error);\n // @ts-expect-error It’s a Node error.\n error.code = key;\n return error\n }\n}\n\n/**\n * @returns {boolean}\n */\nfunction isErrorStackTraceLimitWritable() {\n // Do no touch Error.stackTraceLimit as V8 would attempt to install\n // it again during deserialization.\n try {\n if (v8.startupSnapshot.isBuildingSnapshot()) {\n return false\n }\n } catch {}\n\n const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit');\n if (desc === undefined) {\n return Object.isExtensible(Error)\n }\n\n return own$1.call(desc, 'writable') && desc.writable !== undefined\n ? desc.writable\n : desc.set !== undefined\n}\n\n/**\n * This function removes unnecessary frames from Node.js core errors.\n * @template {(...parameters: unknown[]) => unknown} T\n * @param {T} wrappedFunction\n * @returns {T}\n */\nfunction hideStackFrames(wrappedFunction) {\n // We rename the functions that will be hidden to cut off the stacktrace\n // at the outermost one\n const hidden = nodeInternalPrefix + wrappedFunction.name;\n Object.defineProperty(wrappedFunction, 'name', {value: hidden});\n return wrappedFunction\n}\n\nconst captureLargerStackTrace = hideStackFrames(\n /**\n * @param {Error} error\n * @returns {Error}\n */\n // @ts-expect-error: fine\n function (error) {\n const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();\n if (stackTraceLimitIsWritable) {\n userStackTraceLimit = Error.stackTraceLimit;\n Error.stackTraceLimit = Number.POSITIVE_INFINITY;\n }\n\n Error.captureStackTrace(error);\n\n // Reset the limit\n if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;\n\n return error\n }\n);\n\n/**\n * @param {string} key\n * @param {Array} parameters\n * @param {Error} self\n * @returns {string}\n */\nfunction getMessage(key, parameters, self) {\n const message = messages.get(key);\n assert(message !== undefined, 'expected `message` to be found');\n\n if (typeof message === 'function') {\n assert(\n message.length <= parameters.length, // Default options do not count.\n `Code: ${key}; The provided arguments length (${parameters.length}) does not ` +\n `match the required ones (${message.length}).`\n );\n return Reflect.apply(message, self, parameters)\n }\n\n const regex = /%[dfijoOs]/g;\n let expectedLength = 0;\n while (regex.exec(message) !== null) expectedLength++;\n assert(\n expectedLength === parameters.length,\n `Code: ${key}; The provided arguments length (${parameters.length}) does not ` +\n `match the required ones (${expectedLength}).`\n );\n if (parameters.length === 0) return message\n\n parameters.unshift(message);\n return Reflect.apply(format, null, parameters)\n}\n\n/**\n * Determine the specific type of a value for type-mismatch errors.\n * @param {unknown} value\n * @returns {string}\n */\nfunction determineSpecificType(value) {\n if (value === null || value === undefined) {\n return String(value)\n }\n\n if (typeof value === 'function' && value.name) {\n return `function ${value.name}`\n }\n\n if (typeof value === 'object') {\n if (value.constructor && value.constructor.name) {\n return `an instance of ${value.constructor.name}`\n }\n\n return `${inspect(value, {depth: -1})}`\n }\n\n let inspected = inspect(value, {colors: false});\n\n if (inspected.length > 28) {\n inspected = `${inspected.slice(0, 25)}...`;\n }\n\n return `type ${typeof value} (${inspected})`\n}\n\n// Manually “tree shaken” from:\n// \n// Last checked on: Apr 29, 2023.\n// Removed the native dependency.\n// Also: no need to cache, we do that in resolve already.\n\n\nconst hasOwnProperty$1 = {}.hasOwnProperty;\n\nconst {ERR_INVALID_PACKAGE_CONFIG: ERR_INVALID_PACKAGE_CONFIG$1} = codes;\n\n/** @type {Map} */\nconst cache = new Map();\n\n/**\n * @param {string} jsonPath\n * @param {{specifier: URL | string, base?: URL}} options\n * @returns {PackageConfig}\n */\nfunction read(jsonPath, {base, specifier}) {\n const existing = cache.get(jsonPath);\n\n if (existing) {\n return existing\n }\n\n /** @type {string | undefined} */\n let string;\n\n try {\n string = fs.readFileSync(path.toNamespacedPath(jsonPath), 'utf8');\n } catch (error) {\n const exception = /** @type {ErrnoException} */ (error);\n\n if (exception.code !== 'ENOENT') {\n throw exception\n }\n }\n\n /** @type {PackageConfig} */\n const result = {\n exists: false,\n pjsonPath: jsonPath,\n main: undefined,\n name: undefined,\n type: 'none', // Ignore unknown types for forwards compatibility\n exports: undefined,\n imports: undefined\n };\n\n if (string !== undefined) {\n /** @type {Record} */\n let parsed;\n\n try {\n parsed = JSON.parse(string);\n } catch (error_) {\n const cause = /** @type {ErrnoException} */ (error_);\n const error = new ERR_INVALID_PACKAGE_CONFIG$1(\n jsonPath,\n (base ? `\"${specifier}\" from ` : '') + fileURLToPath(base || specifier),\n cause.message\n );\n error.cause = cause;\n throw error\n }\n\n result.exists = true;\n\n if (\n hasOwnProperty$1.call(parsed, 'name') &&\n typeof parsed.name === 'string'\n ) {\n result.name = parsed.name;\n }\n\n if (\n hasOwnProperty$1.call(parsed, 'main') &&\n typeof parsed.main === 'string'\n ) {\n result.main = parsed.main;\n }\n\n if (hasOwnProperty$1.call(parsed, 'exports')) {\n // @ts-expect-error: assume valid.\n result.exports = parsed.exports;\n }\n\n if (hasOwnProperty$1.call(parsed, 'imports')) {\n // @ts-expect-error: assume valid.\n result.imports = parsed.imports;\n }\n\n // Ignore unknown types for forwards compatibility\n if (\n hasOwnProperty$1.call(parsed, 'type') &&\n (parsed.type === 'commonjs' || parsed.type === 'module')\n ) {\n result.type = parsed.type;\n }\n }\n\n cache.set(jsonPath, result);\n\n return result\n}\n\n/**\n * @param {URL | string} resolved\n * @returns {PackageConfig}\n */\nfunction getPackageScopeConfig(resolved) {\n // Note: in Node, this is now a native module.\n let packageJSONUrl = new URL('package.json', resolved);\n\n while (true) {\n const packageJSONPath = packageJSONUrl.pathname;\n if (packageJSONPath.endsWith('node_modules/package.json')) {\n break\n }\n\n const packageConfig = read(fileURLToPath(packageJSONUrl), {\n specifier: resolved\n });\n\n if (packageConfig.exists) {\n return packageConfig\n }\n\n const lastPackageJSONUrl = packageJSONUrl;\n packageJSONUrl = new URL('../package.json', packageJSONUrl);\n\n // Terminates at root where ../package.json equals ../../package.json\n // (can't just check \"/package.json\" for Windows support).\n if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) {\n break\n }\n }\n\n const packageJSONPath = fileURLToPath(packageJSONUrl);\n // ^^ Note: in Node, this is now a native module.\n\n return {\n pjsonPath: packageJSONPath,\n exists: false,\n type: 'none'\n }\n}\n\n/**\n * Returns the package type for a given URL.\n * @param {URL} url - The URL to get the package type for.\n * @returns {PackageType}\n */\nfunction getPackageType(url) {\n // To do @anonrig: Write a C++ function that returns only \"type\".\n return getPackageScopeConfig(url).type\n}\n\n// Manually “tree shaken” from:\n// \n// Last checked on: Apr 29, 2023.\n\n\nconst {ERR_UNKNOWN_FILE_EXTENSION} = codes;\n\nconst hasOwnProperty = {}.hasOwnProperty;\n\n/** @type {Record} */\nconst extensionFormatMap = {\n // @ts-expect-error: hush.\n __proto__: null,\n '.cjs': 'commonjs',\n '.js': 'module',\n '.json': 'json',\n '.mjs': 'module'\n};\n\n/**\n * @param {string | null} mime\n * @returns {string | null}\n */\nfunction mimeToFormat(mime) {\n if (\n mime &&\n /\\s*(text|application)\\/javascript\\s*(;\\s*charset=utf-?8\\s*)?/i.test(mime)\n )\n return 'module'\n if (mime === 'application/json') return 'json'\n return null\n}\n\n/**\n * @callback ProtocolHandler\n * @param {URL} parsed\n * @param {{parentURL: string, source?: Buffer}} context\n * @param {boolean} ignoreErrors\n * @returns {string | null | void}\n */\n\n/**\n * @type {Record}\n */\nconst protocolHandlers = {\n // @ts-expect-error: hush.\n __proto__: null,\n 'data:': getDataProtocolModuleFormat,\n 'file:': getFileProtocolModuleFormat,\n 'http:': getHttpProtocolModuleFormat,\n 'https:': getHttpProtocolModuleFormat,\n 'node:'() {\n return 'builtin'\n }\n};\n\n/**\n * @param {URL} parsed\n */\nfunction getDataProtocolModuleFormat(parsed) {\n const {1: mime} = /^([^/]+\\/[^;,]+)[^,]*?(;base64)?,/.exec(\n parsed.pathname\n ) || [null, null, null];\n return mimeToFormat(mime)\n}\n\n/**\n * Returns the file extension from a URL.\n *\n * Should give similar result to\n * `require('node:path').extname(require('node:url').fileURLToPath(url))`\n * when used with a `file:` URL.\n *\n * @param {URL} url\n * @returns {string}\n */\nfunction extname(url) {\n const pathname = url.pathname;\n let index = pathname.length;\n\n while (index--) {\n const code = pathname.codePointAt(index);\n\n if (code === 47 /* `/` */) {\n return ''\n }\n\n if (code === 46 /* `.` */) {\n return pathname.codePointAt(index - 1) === 47 /* `/` */\n ? ''\n : pathname.slice(index)\n }\n }\n\n return ''\n}\n\n/**\n * @type {ProtocolHandler}\n */\nfunction getFileProtocolModuleFormat(url, _context, ignoreErrors) {\n const value = extname(url);\n\n if (value === '.js') {\n const packageType = getPackageType(url);\n\n if (packageType !== 'none') {\n return packageType\n }\n\n return 'commonjs'\n }\n\n if (value === '') {\n const packageType = getPackageType(url);\n\n // Legacy behavior\n if (packageType === 'none' || packageType === 'commonjs') {\n return 'commonjs'\n }\n\n // Note: we don’t implement WASM, so we don’t need\n // `getFormatOfExtensionlessFile` from `formats`.\n return 'module'\n }\n\n const format = extensionFormatMap[value];\n if (format) return format\n\n // Explicit undefined return indicates load hook should rerun format check\n if (ignoreErrors) {\n return undefined\n }\n\n const filepath = fileURLToPath(url);\n throw new ERR_UNKNOWN_FILE_EXTENSION(value, filepath)\n}\n\nfunction getHttpProtocolModuleFormat() {\n // To do: HTTPS imports.\n}\n\n/**\n * @param {URL} url\n * @param {{parentURL: string}} context\n * @returns {string | null}\n */\nfunction defaultGetFormatWithoutErrors(url, context) {\n const protocol = url.protocol;\n\n if (!hasOwnProperty.call(protocolHandlers, protocol)) {\n return null\n }\n\n return protocolHandlers[protocol](url, context, true) || null\n}\n\n// Manually “tree shaken” from:\n// \n// Last checked on: Apr 29, 2023.\n\n\nconst {ERR_INVALID_ARG_VALUE} = codes;\n\n// In Node itself these values are populated from CLI arguments, before any\n// user code runs.\n// Here we just define the defaults.\nconst DEFAULT_CONDITIONS = Object.freeze(['node', 'import']);\nconst DEFAULT_CONDITIONS_SET = new Set(DEFAULT_CONDITIONS);\n\n/**\n * Returns the default conditions for ES module loading.\n */\nfunction getDefaultConditions() {\n return DEFAULT_CONDITIONS\n}\n\n/**\n * Returns the default conditions for ES module loading, as a Set.\n */\nfunction getDefaultConditionsSet() {\n return DEFAULT_CONDITIONS_SET\n}\n\n/**\n * @param {Array} [conditions]\n * @returns {Set}\n */\nfunction getConditionsSet(conditions) {\n if (conditions !== undefined && conditions !== getDefaultConditions()) {\n if (!Array.isArray(conditions)) {\n throw new ERR_INVALID_ARG_VALUE(\n 'conditions',\n conditions,\n 'expected an array'\n )\n }\n\n return new Set(conditions)\n }\n\n return getDefaultConditionsSet()\n}\n\n// Manually “tree shaken” from:\n// \n// Last checked on: Apr 29, 2023.\n\n\nconst RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];\n\nconst {\n ERR_NETWORK_IMPORT_DISALLOWED,\n ERR_INVALID_MODULE_SPECIFIER,\n ERR_INVALID_PACKAGE_CONFIG,\n ERR_INVALID_PACKAGE_TARGET,\n ERR_MODULE_NOT_FOUND,\n ERR_PACKAGE_IMPORT_NOT_DEFINED,\n ERR_PACKAGE_PATH_NOT_EXPORTED,\n ERR_UNSUPPORTED_DIR_IMPORT,\n ERR_UNSUPPORTED_RESOLVE_REQUEST\n} = codes;\n\nconst own = {}.hasOwnProperty;\n\nconst invalidSegmentRegEx =\n /(^|\\\\|\\/)((\\.|%2e)(\\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\\\|\\/|$)/i;\nconst deprecatedInvalidSegmentRegEx =\n /(^|\\\\|\\/)((\\.|%2e)(\\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\\\|\\/|$)/i;\nconst invalidPackageNameRegEx = /^\\.|%|\\\\/;\nconst patternRegEx = /\\*/g;\nconst encodedSeparatorRegEx = /%2f|%5c/i;\n/** @type {Set} */\nconst emittedPackageWarnings = new Set();\n\nconst doubleSlashRegEx = /[/\\\\]{2}/;\n\n/**\n *\n * @param {string} target\n * @param {string} request\n * @param {string} match\n * @param {URL} packageJsonUrl\n * @param {boolean} internal\n * @param {URL} base\n * @param {boolean} isTarget\n */\nfunction emitInvalidSegmentDeprecation(\n target,\n request,\n match,\n packageJsonUrl,\n internal,\n base,\n isTarget\n) {\n // @ts-expect-error: apparently it does exist, TS.\n if (process.noDeprecation) {\n return\n }\n\n const pjsonPath = fileURLToPath(packageJsonUrl);\n const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;\n process.emitWarning(\n `Use of deprecated ${\n double ? 'double slash' : 'leading or trailing slash matching'\n } resolving \"${target}\" for module ` +\n `request \"${request}\" ${\n request === match ? '' : `matched to \"${match}\" `\n }in the \"${\n internal ? 'imports' : 'exports'\n }\" field module resolution of the package at ${pjsonPath}${\n base ? ` imported from ${fileURLToPath(base)}` : ''\n }.`,\n 'DeprecationWarning',\n 'DEP0166'\n );\n}\n\n/**\n * @param {URL} url\n * @param {URL} packageJsonUrl\n * @param {URL} base\n * @param {string} [main]\n * @returns {void}\n */\nfunction emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {\n // @ts-expect-error: apparently it does exist, TS.\n if (process.noDeprecation) {\n return\n }\n\n const format = defaultGetFormatWithoutErrors(url, {parentURL: base.href});\n if (format !== 'module') return\n const urlPath = fileURLToPath(url.href);\n const packagePath = fileURLToPath(new URL$1('.', packageJsonUrl));\n const basePath = fileURLToPath(base);\n if (!main) {\n process.emitWarning(\n `No \"main\" or \"exports\" field defined in the package.json for ${packagePath} resolving the main entry point \"${urlPath.slice(\n packagePath.length\n )}\", imported from ${basePath}.\\nDefault \"index\" lookups for the main are deprecated for ES modules.`,\n 'DeprecationWarning',\n 'DEP0151'\n );\n } else if (path.resolve(packagePath, main) !== urlPath) {\n process.emitWarning(\n `Package ${packagePath} has a \"main\" field set to \"${main}\", ` +\n `excluding the full filename and extension to the resolved file at \"${urlPath.slice(\n packagePath.length\n )}\", imported from ${basePath}.\\n Automatic extension resolution of the \"main\" field is ` +\n 'deprecated for ES modules.',\n 'DeprecationWarning',\n 'DEP0151'\n );\n }\n}\n\n/**\n * @param {string} path\n * @returns {Stats | undefined}\n */\nfunction tryStatSync(path) {\n // Note: from Node 15 onwards we can use `throwIfNoEntry: false` instead.\n try {\n return statSync(path)\n } catch {\n // Note: in Node code this returns `new Stats`,\n // but in Node 22 that’s marked as a deprecated internal API.\n // Which, well, we kinda are, but still to prevent that warning,\n // just yield `undefined`.\n }\n}\n\n/**\n * Legacy CommonJS main resolution:\n * 1. let M = pkg_url + (json main field)\n * 2. TRY(M, M.js, M.json, M.node)\n * 3. TRY(M/index.js, M/index.json, M/index.node)\n * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node)\n * 5. NOT_FOUND\n *\n * @param {URL} url\n * @returns {boolean}\n */\nfunction fileExists(url) {\n const stats = statSync(url, {throwIfNoEntry: false});\n const isFile = stats ? stats.isFile() : undefined;\n return isFile === null || isFile === undefined ? false : isFile\n}\n\n/**\n * @param {URL} packageJsonUrl\n * @param {PackageConfig} packageConfig\n * @param {URL} base\n * @returns {URL}\n */\nfunction legacyMainResolve(packageJsonUrl, packageConfig, base) {\n /** @type {URL | undefined} */\n let guess;\n if (packageConfig.main !== undefined) {\n guess = new URL$1(packageConfig.main, packageJsonUrl);\n // Note: fs check redundances will be handled by Descriptor cache here.\n if (fileExists(guess)) return guess\n\n const tries = [\n `./${packageConfig.main}.js`,\n `./${packageConfig.main}.json`,\n `./${packageConfig.main}.node`,\n `./${packageConfig.main}/index.js`,\n `./${packageConfig.main}/index.json`,\n `./${packageConfig.main}/index.node`\n ];\n let i = -1;\n\n while (++i < tries.length) {\n guess = new URL$1(tries[i], packageJsonUrl);\n if (fileExists(guess)) break\n guess = undefined;\n }\n\n if (guess) {\n emitLegacyIndexDeprecation(\n guess,\n packageJsonUrl,\n base,\n packageConfig.main\n );\n return guess\n }\n // Fallthrough.\n }\n\n const tries = ['./index.js', './index.json', './index.node'];\n let i = -1;\n\n while (++i < tries.length) {\n guess = new URL$1(tries[i], packageJsonUrl);\n if (fileExists(guess)) break\n guess = undefined;\n }\n\n if (guess) {\n emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);\n return guess\n }\n\n // Not found.\n throw new ERR_MODULE_NOT_FOUND(\n fileURLToPath(new URL$1('.', packageJsonUrl)),\n fileURLToPath(base)\n )\n}\n\n/**\n * @param {URL} resolved\n * @param {URL} base\n * @param {boolean} [preserveSymlinks]\n * @returns {URL}\n */\nfunction finalizeResolution(resolved, base, preserveSymlinks) {\n if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) {\n throw new ERR_INVALID_MODULE_SPECIFIER(\n resolved.pathname,\n 'must not include encoded \"/\" or \"\\\\\" characters',\n fileURLToPath(base)\n )\n }\n\n /** @type {string} */\n let filePath;\n\n try {\n filePath = fileURLToPath(resolved);\n } catch (error) {\n const cause = /** @type {ErrnoException} */ (error);\n Object.defineProperty(cause, 'input', {value: String(resolved)});\n Object.defineProperty(cause, 'module', {value: String(base)});\n throw cause\n }\n\n const stats = tryStatSync(\n filePath.endsWith('/') ? filePath.slice(-1) : filePath\n );\n\n if (stats && stats.isDirectory()) {\n const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath(base));\n // @ts-expect-error Add this for `import.meta.resolve`.\n error.url = String(resolved);\n throw error\n }\n\n if (!stats || !stats.isFile()) {\n const error = new ERR_MODULE_NOT_FOUND(\n filePath || resolved.pathname,\n base && fileURLToPath(base),\n true\n );\n // @ts-expect-error Add this for `import.meta.resolve`.\n error.url = String(resolved);\n throw error\n }\n\n if (!preserveSymlinks) {\n const real = realpathSync(filePath);\n const {search, hash} = resolved;\n resolved = pathToFileURL(real + (filePath.endsWith(path.sep) ? '/' : ''));\n resolved.search = search;\n resolved.hash = hash;\n }\n\n return resolved\n}\n\n/**\n * @param {string} specifier\n * @param {URL | undefined} packageJsonUrl\n * @param {URL} base\n * @returns {Error}\n */\nfunction importNotDefined(specifier, packageJsonUrl, base) {\n return new ERR_PACKAGE_IMPORT_NOT_DEFINED(\n specifier,\n packageJsonUrl && fileURLToPath(new URL$1('.', packageJsonUrl)),\n fileURLToPath(base)\n )\n}\n\n/**\n * @param {string} subpath\n * @param {URL} packageJsonUrl\n * @param {URL} base\n * @returns {Error}\n */\nfunction exportsNotFound(subpath, packageJsonUrl, base) {\n return new ERR_PACKAGE_PATH_NOT_EXPORTED(\n fileURLToPath(new URL$1('.', packageJsonUrl)),\n subpath,\n base && fileURLToPath(base)\n )\n}\n\n/**\n * @param {string} request\n * @param {string} match\n * @param {URL} packageJsonUrl\n * @param {boolean} internal\n * @param {URL} [base]\n * @returns {never}\n */\nfunction throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {\n const reason = `request is not a valid match in pattern \"${match}\" for the \"${\n internal ? 'imports' : 'exports'\n }\" resolution of ${fileURLToPath(packageJsonUrl)}`;\n throw new ERR_INVALID_MODULE_SPECIFIER(\n request,\n reason,\n base && fileURLToPath(base)\n )\n}\n\n/**\n * @param {string} subpath\n * @param {unknown} target\n * @param {URL} packageJsonUrl\n * @param {boolean} internal\n * @param {URL} [base]\n * @returns {Error}\n */\nfunction invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {\n target =\n typeof target === 'object' && target !== null\n ? JSON.stringify(target, null, '')\n : `${target}`;\n\n return new ERR_INVALID_PACKAGE_TARGET(\n fileURLToPath(new URL$1('.', packageJsonUrl)),\n subpath,\n target,\n internal,\n base && fileURLToPath(base)\n )\n}\n\n/**\n * @param {string} target\n * @param {string} subpath\n * @param {string} match\n * @param {URL} packageJsonUrl\n * @param {URL} base\n * @param {boolean} pattern\n * @param {boolean} internal\n * @param {boolean} isPathMap\n * @param {Set | undefined} conditions\n * @returns {URL}\n */\nfunction resolvePackageTargetString(\n target,\n subpath,\n match,\n packageJsonUrl,\n base,\n pattern,\n internal,\n isPathMap,\n conditions\n) {\n if (subpath !== '' && !pattern && target[target.length - 1] !== '/')\n throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)\n\n if (!target.startsWith('./')) {\n if (internal && !target.startsWith('../') && !target.startsWith('/')) {\n let isURL = false;\n\n try {\n new URL$1(target);\n isURL = true;\n } catch {\n // Continue regardless of error.\n }\n\n if (!isURL) {\n const exportTarget = pattern\n ? RegExpPrototypeSymbolReplace.call(\n patternRegEx,\n target,\n () => subpath\n )\n : target + subpath;\n\n return packageResolve(exportTarget, packageJsonUrl, conditions)\n }\n }\n\n throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)\n }\n\n if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {\n if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {\n if (!isPathMap) {\n const request = pattern\n ? match.replace('*', () => subpath)\n : match + subpath;\n const resolvedTarget = pattern\n ? RegExpPrototypeSymbolReplace.call(\n patternRegEx,\n target,\n () => subpath\n )\n : target;\n emitInvalidSegmentDeprecation(\n resolvedTarget,\n request,\n match,\n packageJsonUrl,\n internal,\n base,\n true\n );\n }\n } else {\n throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)\n }\n }\n\n const resolved = new URL$1(target, packageJsonUrl);\n const resolvedPath = resolved.pathname;\n const packagePath = new URL$1('.', packageJsonUrl).pathname;\n\n if (!resolvedPath.startsWith(packagePath))\n throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)\n\n if (subpath === '') return resolved\n\n if (invalidSegmentRegEx.exec(subpath) !== null) {\n const request = pattern\n ? match.replace('*', () => subpath)\n : match + subpath;\n if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {\n if (!isPathMap) {\n const resolvedTarget = pattern\n ? RegExpPrototypeSymbolReplace.call(\n patternRegEx,\n target,\n () => subpath\n )\n : target;\n emitInvalidSegmentDeprecation(\n resolvedTarget,\n request,\n match,\n packageJsonUrl,\n internal,\n base,\n false\n );\n }\n } else {\n throwInvalidSubpath(request, match, packageJsonUrl, internal, base);\n }\n }\n\n if (pattern) {\n return new URL$1(\n RegExpPrototypeSymbolReplace.call(\n patternRegEx,\n resolved.href,\n () => subpath\n )\n )\n }\n\n return new URL$1(subpath, resolved)\n}\n\n/**\n * @param {string} key\n * @returns {boolean}\n */\nfunction isArrayIndex(key) {\n const keyNumber = Number(key);\n if (`${keyNumber}` !== key) return false\n return keyNumber >= 0 && keyNumber < 0xff_ff_ff_ff\n}\n\n/**\n * @param {URL} packageJsonUrl\n * @param {unknown} target\n * @param {string} subpath\n * @param {string} packageSubpath\n * @param {URL} base\n * @param {boolean} pattern\n * @param {boolean} internal\n * @param {boolean} isPathMap\n * @param {Set | undefined} conditions\n * @returns {URL | null}\n */\nfunction resolvePackageTarget(\n packageJsonUrl,\n target,\n subpath,\n packageSubpath,\n base,\n pattern,\n internal,\n isPathMap,\n conditions\n) {\n if (typeof target === 'string') {\n return resolvePackageTargetString(\n target,\n subpath,\n packageSubpath,\n packageJsonUrl,\n base,\n pattern,\n internal,\n isPathMap,\n conditions\n )\n }\n\n if (Array.isArray(target)) {\n /** @type {Array} */\n const targetList = target;\n if (targetList.length === 0) return null\n\n /** @type {ErrnoException | null | undefined} */\n let lastException;\n let i = -1;\n\n while (++i < targetList.length) {\n const targetItem = targetList[i];\n /** @type {URL | null} */\n let resolveResult;\n try {\n resolveResult = resolvePackageTarget(\n packageJsonUrl,\n targetItem,\n subpath,\n packageSubpath,\n base,\n pattern,\n internal,\n isPathMap,\n conditions\n );\n } catch (error) {\n const exception = /** @type {ErrnoException} */ (error);\n lastException = exception;\n if (exception.code === 'ERR_INVALID_PACKAGE_TARGET') continue\n throw error\n }\n\n if (resolveResult === undefined) continue\n\n if (resolveResult === null) {\n lastException = null;\n continue\n }\n\n return resolveResult\n }\n\n if (lastException === undefined || lastException === null) {\n return null\n }\n\n throw lastException\n }\n\n if (typeof target === 'object' && target !== null) {\n const keys = Object.getOwnPropertyNames(target);\n let i = -1;\n\n while (++i < keys.length) {\n const key = keys[i];\n if (isArrayIndex(key)) {\n throw new ERR_INVALID_PACKAGE_CONFIG(\n fileURLToPath(packageJsonUrl),\n base,\n '\"exports\" cannot contain numeric property keys.'\n )\n }\n }\n\n i = -1;\n\n while (++i < keys.length) {\n const key = keys[i];\n if (key === 'default' || (conditions && conditions.has(key))) {\n // @ts-expect-error: indexable.\n const conditionalTarget = /** @type {unknown} */ (target[key]);\n const resolveResult = resolvePackageTarget(\n packageJsonUrl,\n conditionalTarget,\n subpath,\n packageSubpath,\n base,\n pattern,\n internal,\n isPathMap,\n conditions\n );\n if (resolveResult === undefined) continue\n return resolveResult\n }\n }\n\n return null\n }\n\n if (target === null) {\n return null\n }\n\n throw invalidPackageTarget(\n packageSubpath,\n target,\n packageJsonUrl,\n internal,\n base\n )\n}\n\n/**\n * @param {unknown} exports\n * @param {URL} packageJsonUrl\n * @param {URL} base\n * @returns {boolean}\n */\nfunction isConditionalExportsMainSugar(exports, packageJsonUrl, base) {\n if (typeof exports === 'string' || Array.isArray(exports)) return true\n if (typeof exports !== 'object' || exports === null) return false\n\n const keys = Object.getOwnPropertyNames(exports);\n let isConditionalSugar = false;\n let i = 0;\n let keyIndex = -1;\n while (++keyIndex < keys.length) {\n const key = keys[keyIndex];\n const currentIsConditionalSugar = key === '' || key[0] !== '.';\n if (i++ === 0) {\n isConditionalSugar = currentIsConditionalSugar;\n } else if (isConditionalSugar !== currentIsConditionalSugar) {\n throw new ERR_INVALID_PACKAGE_CONFIG(\n fileURLToPath(packageJsonUrl),\n base,\n '\"exports\" cannot contain some keys starting with \\'.\\' and some not.' +\n ' The exports object must either be an object of package subpath keys' +\n ' or an object of main entry condition name keys only.'\n )\n }\n }\n\n return isConditionalSugar\n}\n\n/**\n * @param {string} match\n * @param {URL} pjsonUrl\n * @param {URL} base\n */\nfunction emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {\n // @ts-expect-error: apparently it does exist, TS.\n if (process.noDeprecation) {\n return\n }\n\n const pjsonPath = fileURLToPath(pjsonUrl);\n if (emittedPackageWarnings.has(pjsonPath + '|' + match)) return\n emittedPackageWarnings.add(pjsonPath + '|' + match);\n process.emitWarning(\n `Use of deprecated trailing slash pattern mapping \"${match}\" in the ` +\n `\"exports\" field module resolution of the package at ${pjsonPath}${\n base ? ` imported from ${fileURLToPath(base)}` : ''\n }. Mapping specifiers ending in \"/\" is no longer supported.`,\n 'DeprecationWarning',\n 'DEP0155'\n );\n}\n\n/**\n * @param {URL} packageJsonUrl\n * @param {string} packageSubpath\n * @param {Record} packageConfig\n * @param {URL} base\n * @param {Set | undefined} conditions\n * @returns {URL}\n */\nfunction packageExportsResolve(\n packageJsonUrl,\n packageSubpath,\n packageConfig,\n base,\n conditions\n) {\n let exports = packageConfig.exports;\n\n if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {\n exports = {'.': exports};\n }\n\n if (\n own.call(exports, packageSubpath) &&\n !packageSubpath.includes('*') &&\n !packageSubpath.endsWith('/')\n ) {\n // @ts-expect-error: indexable.\n const target = exports[packageSubpath];\n const resolveResult = resolvePackageTarget(\n packageJsonUrl,\n target,\n '',\n packageSubpath,\n base,\n false,\n false,\n false,\n conditions\n );\n if (resolveResult === null || resolveResult === undefined) {\n throw exportsNotFound(packageSubpath, packageJsonUrl, base)\n }\n\n return resolveResult\n }\n\n let bestMatch = '';\n let bestMatchSubpath = '';\n const keys = Object.getOwnPropertyNames(exports);\n let i = -1;\n\n while (++i < keys.length) {\n const key = keys[i];\n const patternIndex = key.indexOf('*');\n\n if (\n patternIndex !== -1 &&\n packageSubpath.startsWith(key.slice(0, patternIndex))\n ) {\n // When this reaches EOL, this can throw at the top of the whole function:\n //\n // if (StringPrototypeEndsWith(packageSubpath, '/'))\n // throwInvalidSubpath(packageSubpath)\n //\n // To match \"imports\" and the spec.\n if (packageSubpath.endsWith('/')) {\n emitTrailingSlashPatternDeprecation(\n packageSubpath,\n packageJsonUrl,\n base\n );\n }\n\n const patternTrailer = key.slice(patternIndex + 1);\n\n if (\n packageSubpath.length >= key.length &&\n packageSubpath.endsWith(patternTrailer) &&\n patternKeyCompare(bestMatch, key) === 1 &&\n key.lastIndexOf('*') === patternIndex\n ) {\n bestMatch = key;\n bestMatchSubpath = packageSubpath.slice(\n patternIndex,\n packageSubpath.length - patternTrailer.length\n );\n }\n }\n }\n\n if (bestMatch) {\n // @ts-expect-error: indexable.\n const target = /** @type {unknown} */ (exports[bestMatch]);\n const resolveResult = resolvePackageTarget(\n packageJsonUrl,\n target,\n bestMatchSubpath,\n bestMatch,\n base,\n true,\n false,\n packageSubpath.endsWith('/'),\n conditions\n );\n\n if (resolveResult === null || resolveResult === undefined) {\n throw exportsNotFound(packageSubpath, packageJsonUrl, base)\n }\n\n return resolveResult\n }\n\n throw exportsNotFound(packageSubpath, packageJsonUrl, base)\n}\n\n/**\n * @param {string} a\n * @param {string} b\n */\nfunction patternKeyCompare(a, b) {\n const aPatternIndex = a.indexOf('*');\n const bPatternIndex = b.indexOf('*');\n const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;\n const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;\n if (baseLengthA > baseLengthB) return -1\n if (baseLengthB > baseLengthA) return 1\n if (aPatternIndex === -1) return 1\n if (bPatternIndex === -1) return -1\n if (a.length > b.length) return -1\n if (b.length > a.length) return 1\n return 0\n}\n\n/**\n * @param {string} name\n * @param {URL} base\n * @param {Set} [conditions]\n * @returns {URL}\n */\nfunction packageImportsResolve(name, base, conditions) {\n if (name === '#' || name.startsWith('#/') || name.endsWith('/')) {\n const reason = 'is not a valid internal imports specifier name';\n throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath(base))\n }\n\n /** @type {URL | undefined} */\n let packageJsonUrl;\n\n const packageConfig = getPackageScopeConfig(base);\n\n if (packageConfig.exists) {\n packageJsonUrl = pathToFileURL(packageConfig.pjsonPath);\n const imports = packageConfig.imports;\n if (imports) {\n if (own.call(imports, name) && !name.includes('*')) {\n const resolveResult = resolvePackageTarget(\n packageJsonUrl,\n imports[name],\n '',\n name,\n base,\n false,\n true,\n false,\n conditions\n );\n if (resolveResult !== null && resolveResult !== undefined) {\n return resolveResult\n }\n } else {\n let bestMatch = '';\n let bestMatchSubpath = '';\n const keys = Object.getOwnPropertyNames(imports);\n let i = -1;\n\n while (++i < keys.length) {\n const key = keys[i];\n const patternIndex = key.indexOf('*');\n\n if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) {\n const patternTrailer = key.slice(patternIndex + 1);\n if (\n name.length >= key.length &&\n name.endsWith(patternTrailer) &&\n patternKeyCompare(bestMatch, key) === 1 &&\n key.lastIndexOf('*') === patternIndex\n ) {\n bestMatch = key;\n bestMatchSubpath = name.slice(\n patternIndex,\n name.length - patternTrailer.length\n );\n }\n }\n }\n\n if (bestMatch) {\n const target = imports[bestMatch];\n const resolveResult = resolvePackageTarget(\n packageJsonUrl,\n target,\n bestMatchSubpath,\n bestMatch,\n base,\n true,\n true,\n false,\n conditions\n );\n\n if (resolveResult !== null && resolveResult !== undefined) {\n return resolveResult\n }\n }\n }\n }\n }\n\n throw importNotDefined(name, packageJsonUrl, base)\n}\n\n/**\n * @param {string} specifier\n * @param {URL} base\n */\nfunction parsePackageName(specifier, base) {\n let separatorIndex = specifier.indexOf('/');\n let validPackageName = true;\n let isScoped = false;\n if (specifier[0] === '@') {\n isScoped = true;\n if (separatorIndex === -1 || specifier.length === 0) {\n validPackageName = false;\n } else {\n separatorIndex = specifier.indexOf('/', separatorIndex + 1);\n }\n }\n\n const packageName =\n separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);\n\n // Package name cannot have leading . and cannot have percent-encoding or\n // \\\\ separators.\n if (invalidPackageNameRegEx.exec(packageName) !== null) {\n validPackageName = false;\n }\n\n if (!validPackageName) {\n throw new ERR_INVALID_MODULE_SPECIFIER(\n specifier,\n 'is not a valid package name',\n fileURLToPath(base)\n )\n }\n\n const packageSubpath =\n '.' + (separatorIndex === -1 ? '' : specifier.slice(separatorIndex));\n\n return {packageName, packageSubpath, isScoped}\n}\n\n/**\n * @param {string} specifier\n * @param {URL} base\n * @param {Set | undefined} conditions\n * @returns {URL}\n */\nfunction packageResolve(specifier, base, conditions) {\n if (builtinModules.includes(specifier)) {\n return new URL$1('node:' + specifier)\n }\n\n const {packageName, packageSubpath, isScoped} = parsePackageName(\n specifier,\n base\n );\n\n // ResolveSelf\n const packageConfig = getPackageScopeConfig(base);\n\n // Can’t test.\n /* c8 ignore next 16 */\n if (packageConfig.exists) {\n const packageJsonUrl = pathToFileURL(packageConfig.pjsonPath);\n if (\n packageConfig.name === packageName &&\n packageConfig.exports !== undefined &&\n packageConfig.exports !== null\n ) {\n return packageExportsResolve(\n packageJsonUrl,\n packageSubpath,\n packageConfig,\n base,\n conditions\n )\n }\n }\n\n let packageJsonUrl = new URL$1(\n './node_modules/' + packageName + '/package.json',\n base\n );\n let packageJsonPath = fileURLToPath(packageJsonUrl);\n /** @type {string} */\n let lastPath;\n do {\n const stat = tryStatSync(packageJsonPath.slice(0, -13));\n if (!stat || !stat.isDirectory()) {\n lastPath = packageJsonPath;\n packageJsonUrl = new URL$1(\n (isScoped ? '../../../../node_modules/' : '../../../node_modules/') +\n packageName +\n '/package.json',\n packageJsonUrl\n );\n packageJsonPath = fileURLToPath(packageJsonUrl);\n continue\n }\n\n // Package match.\n const packageConfig = read(packageJsonPath, {base, specifier});\n if (packageConfig.exports !== undefined && packageConfig.exports !== null) {\n return packageExportsResolve(\n packageJsonUrl,\n packageSubpath,\n packageConfig,\n base,\n conditions\n )\n }\n\n if (packageSubpath === '.') {\n return legacyMainResolve(packageJsonUrl, packageConfig, base)\n }\n\n return new URL$1(packageSubpath, packageJsonUrl)\n // Cross-platform root check.\n } while (packageJsonPath.length !== lastPath.length)\n\n throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath(base), false)\n}\n\n/**\n * @param {string} specifier\n * @returns {boolean}\n */\nfunction isRelativeSpecifier(specifier) {\n if (specifier[0] === '.') {\n if (specifier.length === 1 || specifier[1] === '/') return true\n if (\n specifier[1] === '.' &&\n (specifier.length === 2 || specifier[2] === '/')\n ) {\n return true\n }\n }\n\n return false\n}\n\n/**\n * @param {string} specifier\n * @returns {boolean}\n */\nfunction shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {\n if (specifier === '') return false\n if (specifier[0] === '/') return true\n return isRelativeSpecifier(specifier)\n}\n\n/**\n * The “Resolver Algorithm Specification” as detailed in the Node docs (which is\n * sync and slightly lower-level than `resolve`).\n *\n * @param {string} specifier\n * `/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`, etc.\n * @param {URL} base\n * Full URL (to a file) that `specifier` is resolved relative from.\n * @param {Set} [conditions]\n * Conditions.\n * @param {boolean} [preserveSymlinks]\n * Keep symlinks instead of resolving them.\n * @returns {URL}\n * A URL object to the found thing.\n */\nfunction moduleResolve(specifier, base, conditions, preserveSymlinks) {\n // Note: The Node code supports `base` as a string (in this internal API) too,\n // we don’t.\n const protocol = base.protocol;\n const isData = protocol === 'data:';\n const isRemote = isData || protocol === 'http:' || protocol === 'https:';\n // Order swapped from spec for minor perf gain.\n // Ok since relative URLs cannot parse as URLs.\n /** @type {URL | undefined} */\n let resolved;\n\n if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {\n try {\n resolved = new URL$1(specifier, base);\n } catch (error_) {\n const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);\n error.cause = error_;\n throw error\n }\n } else if (protocol === 'file:' && specifier[0] === '#') {\n resolved = packageImportsResolve(specifier, base, conditions);\n } else {\n try {\n resolved = new URL$1(specifier);\n } catch (error_) {\n // Note: actual code uses `canBeRequiredWithoutScheme`.\n if (isRemote && !builtinModules.includes(specifier)) {\n const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);\n error.cause = error_;\n throw error\n }\n\n resolved = packageResolve(specifier, base, conditions);\n }\n }\n\n assert(resolved !== undefined, 'expected to be defined');\n\n if (resolved.protocol !== 'file:') {\n return resolved\n }\n\n return finalizeResolution(resolved, base, preserveSymlinks)\n}\n\n/**\n * @param {string} specifier\n * @param {URL | undefined} parsed\n * @param {URL | undefined} parsedParentURL\n */\nfunction checkIfDisallowedImport(specifier, parsed, parsedParentURL) {\n if (parsedParentURL) {\n // Avoid accessing the `protocol` property due to the lazy getters.\n const parentProtocol = parsedParentURL.protocol;\n\n if (parentProtocol === 'http:' || parentProtocol === 'https:') {\n if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {\n // Avoid accessing the `protocol` property due to the lazy getters.\n const parsedProtocol = parsed?.protocol;\n\n // `data:` and `blob:` disallowed due to allowing file: access via\n // indirection\n if (\n parsedProtocol &&\n parsedProtocol !== 'https:' &&\n parsedProtocol !== 'http:'\n ) {\n throw new ERR_NETWORK_IMPORT_DISALLOWED(\n specifier,\n parsedParentURL,\n 'remote imports cannot import from a local location.'\n )\n }\n\n return {url: parsed?.href || ''}\n }\n\n if (builtinModules.includes(specifier)) {\n throw new ERR_NETWORK_IMPORT_DISALLOWED(\n specifier,\n parsedParentURL,\n 'remote imports cannot import from a local location.'\n )\n }\n\n throw new ERR_NETWORK_IMPORT_DISALLOWED(\n specifier,\n parsedParentURL,\n 'only relative and absolute specifiers are supported.'\n )\n }\n }\n}\n\n// Note: this is from:\n// \n/**\n * Checks if a value has the shape of a WHATWG URL object.\n *\n * Using a symbol or instanceof would not be able to recognize URL objects\n * coming from other implementations (e.g. in Electron), so instead we are\n * checking some well known properties for a lack of a better test.\n *\n * We use `href` and `protocol` as they are the only properties that are\n * easy to retrieve and calculate due to the lazy nature of the getters.\n *\n * @template {unknown} Value\n * @param {Value} self\n * @returns {Value is URL}\n */\nfunction isURL(self) {\n return Boolean(\n self &&\n typeof self === 'object' &&\n 'href' in self &&\n typeof self.href === 'string' &&\n 'protocol' in self &&\n typeof self.protocol === 'string' &&\n self.href &&\n self.protocol\n )\n}\n\n/**\n * Validate user-input in `context` supplied by a custom loader.\n *\n * @param {unknown} parentURL\n * @returns {asserts parentURL is URL | string | undefined}\n */\nfunction throwIfInvalidParentURL(parentURL) {\n if (parentURL === undefined) {\n return // Main entry point, so no parent\n }\n\n if (typeof parentURL !== 'string' && !isURL(parentURL)) {\n throw new codes.ERR_INVALID_ARG_TYPE(\n 'parentURL',\n ['string', 'URL'],\n parentURL\n )\n }\n}\n\n/**\n * @param {string} specifier\n * @param {{parentURL?: string, conditions?: Array}} context\n * @returns {{url: string, format?: string | null}}\n */\nfunction defaultResolve(specifier, context = {}) {\n const {parentURL} = context;\n assert(parentURL !== undefined, 'expected `parentURL` to be defined');\n throwIfInvalidParentURL(parentURL);\n\n /** @type {URL | undefined} */\n let parsedParentURL;\n if (parentURL) {\n try {\n parsedParentURL = new URL$1(parentURL);\n } catch {\n // Ignore exception\n }\n }\n\n /** @type {URL | undefined} */\n let parsed;\n /** @type {string | undefined} */\n let protocol;\n\n try {\n parsed = shouldBeTreatedAsRelativeOrAbsolutePath(specifier)\n ? new URL$1(specifier, parsedParentURL)\n : new URL$1(specifier);\n\n // Avoid accessing the `protocol` property due to the lazy getters.\n protocol = parsed.protocol;\n\n if (protocol === 'data:') {\n return {url: parsed.href, format: null}\n }\n } catch {\n // Ignore exception\n }\n\n // There are multiple deep branches that can either throw or return; instead\n // of duplicating that deeply nested logic for the possible returns, DRY and\n // check for a return. This seems the least gnarly.\n const maybeReturn = checkIfDisallowedImport(\n specifier,\n parsed,\n parsedParentURL\n );\n\n if (maybeReturn) return maybeReturn\n\n // This must come after checkIfDisallowedImport\n if (protocol === undefined && parsed) {\n protocol = parsed.protocol;\n }\n\n if (protocol === 'node:') {\n return {url: specifier}\n }\n\n // This must come after checkIfDisallowedImport\n if (parsed && parsed.protocol === 'node:') return {url: specifier}\n\n const conditions = getConditionsSet(context.conditions);\n\n const url = moduleResolve(specifier, new URL$1(parentURL), conditions, false);\n\n return {\n // Do NOT cast `url` to a string: that will work even when there are real\n // problems, silencing them\n url: url.href,\n format: defaultGetFormatWithoutErrors(url, {parentURL})\n }\n}\n\n/**\n * @typedef {import('./lib/errors.js').ErrnoException} ErrnoException\n */\n\n\n/**\n * Match `import.meta.resolve` except that `parent` is required (you can pass\n * `import.meta.url`).\n *\n * @param {string} specifier\n * The module specifier to resolve relative to parent\n * (`/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`,\n * etc).\n * @param {string} parent\n * The absolute parent module URL to resolve from.\n * You must pass `import.meta.url` or something else.\n * @returns {string}\n * Returns a string to a full `file:`, `data:`, or `node:` URL\n * to the found thing.\n */\nfunction resolve(specifier, parent) {\n if (!parent) {\n throw new Error(\n 'Please pass `parent`: `import-meta-resolve` cannot ponyfill that'\n )\n }\n\n try {\n return defaultResolve(specifier, {parentURL: parent}).url\n } catch (error) {\n // See: \n const exception = /** @type {ErrnoException} */ (error);\n\n if (\n (exception.code === 'ERR_UNSUPPORTED_DIR_IMPORT' ||\n exception.code === 'ERR_MODULE_NOT_FOUND') &&\n typeof exception.url === 'string'\n ) {\n return exception.url\n }\n\n throw error\n }\n}\n\nexport { moduleResolve, resolve };\n"],"mappings":";;;;;;;AAoFA,SAAAA,QAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,OAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,IAAA;EAAA,MAAAF,IAAA,GAAAG,uBAAA,CAAAF,OAAA;EAAAC,GAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAA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,OAAO/D,KAAK,EAAE;IAEd,MAAM0C,SAAS,GAAkC1C,KAAM;IAEvD,IACE,CAAC0C,SAAS,CAAClC,IAAI,KAAK,4BAA4B,IAC9CkC,SAAS,CAAClC,IAAI,KAAK,sBAAsB,KAC3C,OAAOkC,SAAS,CAACqB,GAAG,KAAK,QAAQ,EACjC;MACA,OAAOrB,SAAS,CAACqB,GAAG;IACtB;IAEA,MAAM/D,KAAK;EACb;AACF;AAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/core/package.json b/node_modules/@babel/core/package.json new file mode 100644 index 0000000..3a1cd98 --- /dev/null +++ b/node_modules/@babel/core/package.json @@ -0,0 +1,82 @@ +{ + "name": "@babel/core", + "version": "7.25.2", + "description": "Babel compiler core.", + "main": "./lib/index.js", + "author": "The Babel Team (https://babel.dev/team)", + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "https://github.com/babel/babel.git", + "directory": "packages/babel-core" + }, + "homepage": "https://babel.dev/docs/en/next/babel-core", + "bugs": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20core%22+is%3Aopen", + "keywords": [ + "6to5", + "babel", + "classes", + "const", + "es6", + "harmony", + "let", + "modules", + "transpile", + "transpiler", + "var", + "babel-core", + "compiler" + ], + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + }, + "browser": { + "./lib/config/files/index.js": "./lib/config/files/index-browser.js", + "./lib/config/resolve-targets.js": "./lib/config/resolve-targets-browser.js", + "./lib/transform-file.js": "./lib/transform-file-browser.js", + "./src/config/files/index.ts": "./src/config/files/index-browser.ts", + "./src/config/resolve-targets.ts": "./src/config/resolve-targets-browser.ts", + "./src/transform-file.ts": "./src/transform-file-browser.ts" + }, + "dependencies": { + "@ampproject/remapping": "^2.2.0", + "@babel/code-frame": "^7.24.7", + "@babel/generator": "^7.25.0", + "@babel/helper-compilation-targets": "^7.25.2", + "@babel/helper-module-transforms": "^7.25.2", + "@babel/helpers": "^7.25.0", + "@babel/parser": "^7.25.0", + "@babel/template": "^7.25.0", + "@babel/traverse": "^7.25.2", + "@babel/types": "^7.25.2", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "devDependencies": { + "@babel/helper-transform-fixture-test-runner": "^7.25.2", + "@babel/plugin-syntax-flow": "^7.24.7", + "@babel/plugin-transform-flow-strip-types": "^7.25.2", + "@babel/plugin-transform-modules-commonjs": "^7.24.8", + "@babel/preset-env": "^7.25.2", + "@babel/preset-typescript": "^7.24.7", + "@jridgewell/trace-mapping": "^0.3.25", + "@types/convert-source-map": "^2.0.0", + "@types/debug": "^4.1.0", + "@types/gensync": "^1.0.0", + "@types/resolve": "^1.3.2", + "@types/semver": "^5.4.0", + "rimraf": "^3.0.0", + "ts-node": "^11.0.0-beta.1" + }, + "type": "commonjs" +} \ No newline at end of file diff --git a/node_modules/@babel/core/src/config/files/index-browser.ts b/node_modules/@babel/core/src/config/files/index-browser.ts new file mode 100644 index 0000000..d257363 --- /dev/null +++ b/node_modules/@babel/core/src/config/files/index-browser.ts @@ -0,0 +1,109 @@ +import type { Handler } from "gensync"; + +import type { + ConfigFile, + IgnoreFile, + RelativeConfig, + FilePackageData, +} from "./types.ts"; + +import type { CallerMetadata } from "../validation/options.ts"; + +export type { ConfigFile, IgnoreFile, RelativeConfig, FilePackageData }; + +export function findConfigUpwards( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + rootDir: string, +): string | null { + return null; +} + +// eslint-disable-next-line require-yield +export function* findPackageData(filepath: string): Handler { + return { + filepath, + directories: [], + pkg: null, + isPackage: false, + }; +} + +// eslint-disable-next-line require-yield +export function* findRelativeConfig( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + pkgData: FilePackageData, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + envName: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + caller: CallerMetadata | undefined, +): Handler { + return { config: null, ignore: null }; +} + +// eslint-disable-next-line require-yield +export function* findRootConfig( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + dirname: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + envName: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + caller: CallerMetadata | undefined, +): Handler { + return null; +} + +// eslint-disable-next-line require-yield +export function* loadConfig( + name: string, + dirname: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + envName: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + caller: CallerMetadata | undefined, +): Handler { + throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`); +} + +// eslint-disable-next-line require-yield +export function* resolveShowConfigPath( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + dirname: string, +): Handler { + return null; +} + +export const ROOT_CONFIG_FILENAMES: string[] = []; + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export function resolvePlugin(name: string, dirname: string): string | null { + return null; +} + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export function resolvePreset(name: string, dirname: string): string | null { + return null; +} + +export function loadPlugin( + name: string, + dirname: string, +): Handler<{ + filepath: string; + value: unknown; +}> { + throw new Error( + `Cannot load plugin ${name} relative to ${dirname} in a browser`, + ); +} + +export function loadPreset( + name: string, + dirname: string, +): Handler<{ + filepath: string; + value: unknown; +}> { + throw new Error( + `Cannot load preset ${name} relative to ${dirname} in a browser`, + ); +} diff --git a/node_modules/@babel/core/src/config/files/index.ts b/node_modules/@babel/core/src/config/files/index.ts new file mode 100644 index 0000000..b138e8d --- /dev/null +++ b/node_modules/@babel/core/src/config/files/index.ts @@ -0,0 +1,29 @@ +type indexBrowserType = typeof import("./index-browser"); +type indexType = typeof import("./index"); + +// Kind of gross, but essentially asserting that the exports of this module are the same as the +// exports of index-browser, since this file may be replaced at bundle time with index-browser. +({}) as any as indexBrowserType as indexType; + +export { findPackageData } from "./package.ts"; + +export { + findConfigUpwards, + findRelativeConfig, + findRootConfig, + loadConfig, + resolveShowConfigPath, + ROOT_CONFIG_FILENAMES, +} from "./configuration.ts"; +export type { + ConfigFile, + IgnoreFile, + RelativeConfig, + FilePackageData, +} from "./types.ts"; +export { + loadPlugin, + loadPreset, + resolvePlugin, + resolvePreset, +} from "./plugins.ts"; diff --git a/node_modules/@babel/core/src/config/resolve-targets-browser.ts b/node_modules/@babel/core/src/config/resolve-targets-browser.ts new file mode 100644 index 0000000..f93294d --- /dev/null +++ b/node_modules/@babel/core/src/config/resolve-targets-browser.ts @@ -0,0 +1,40 @@ +import type { ValidatedOptions } from "./validation/options.ts"; +import getTargets, { + type InputTargets, +} from "@babel/helper-compilation-targets"; + +import type { Targets } from "@babel/helper-compilation-targets"; + +export function resolveBrowserslistConfigFile( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + browserslistConfigFile: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + configFilePath: string, +): string | void { + return undefined; +} + +export function resolveTargets( + options: ValidatedOptions, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + root: string, +): Targets { + const optTargets = options.targets; + let targets: InputTargets; + + if (typeof optTargets === "string" || Array.isArray(optTargets)) { + targets = { browsers: optTargets }; + } else if (optTargets) { + if ("esmodules" in optTargets) { + targets = { ...optTargets, esmodules: "intersect" }; + } else { + // https://github.com/microsoft/TypeScript/issues/17002 + targets = optTargets as InputTargets; + } + } + + return getTargets(targets, { + ignoreBrowserslistConfig: true, + browserslistEnv: options.browserslistEnv, + }); +} diff --git a/node_modules/@babel/core/src/config/resolve-targets.ts b/node_modules/@babel/core/src/config/resolve-targets.ts new file mode 100644 index 0000000..6271c9f --- /dev/null +++ b/node_modules/@babel/core/src/config/resolve-targets.ts @@ -0,0 +1,56 @@ +type browserType = typeof import("./resolve-targets-browser"); +type nodeType = typeof import("./resolve-targets"); + +// Kind of gross, but essentially asserting that the exports of this module are the same as the +// exports of index-browser, since this file may be replaced at bundle time with index-browser. +({}) as any as browserType as nodeType; + +import type { ValidatedOptions } from "./validation/options.ts"; +import path from "path"; +import getTargets, { + type InputTargets, +} from "@babel/helper-compilation-targets"; + +import type { Targets } from "@babel/helper-compilation-targets"; + +export function resolveBrowserslistConfigFile( + browserslistConfigFile: string, + configFileDir: string, +): string | undefined { + return path.resolve(configFileDir, browserslistConfigFile); +} + +export function resolveTargets( + options: ValidatedOptions, + root: string, +): Targets { + const optTargets = options.targets; + let targets: InputTargets; + + if (typeof optTargets === "string" || Array.isArray(optTargets)) { + targets = { browsers: optTargets }; + } else if (optTargets) { + if ("esmodules" in optTargets) { + targets = { ...optTargets, esmodules: "intersect" }; + } else { + // https://github.com/microsoft/TypeScript/issues/17002 + targets = optTargets as InputTargets; + } + } + + const { browserslistConfigFile } = options; + let configFile; + let ignoreBrowserslistConfig = false; + if (typeof browserslistConfigFile === "string") { + configFile = browserslistConfigFile; + } else { + ignoreBrowserslistConfig = browserslistConfigFile === false; + } + + return getTargets(targets, { + ignoreBrowserslistConfig, + configFile, + configPath: root, + browserslistEnv: options.browserslistEnv, + }); +} diff --git a/node_modules/@babel/core/src/transform-file-browser.ts b/node_modules/@babel/core/src/transform-file-browser.ts new file mode 100644 index 0000000..f316cb4 --- /dev/null +++ b/node_modules/@babel/core/src/transform-file-browser.ts @@ -0,0 +1,31 @@ +// duplicated from transform-file so we do not have to import anything here +type TransformFile = { + (filename: string, callback: (error: Error, file: null) => void): void; + ( + filename: string, + opts: any, + callback: (error: Error, file: null) => void, + ): void; +}; + +export const transformFile: TransformFile = function transformFile( + filename, + opts, + callback?: (error: Error, file: null) => void, +) { + if (typeof opts === "function") { + callback = opts; + } + + callback(new Error("Transforming files is not supported in browsers"), null); +}; + +export function transformFileSync(): never { + throw new Error("Transforming files is not supported in browsers"); +} + +export function transformFileAsync() { + return Promise.reject( + new Error("Transforming files is not supported in browsers"), + ); +} diff --git a/node_modules/@babel/core/src/transform-file.ts b/node_modules/@babel/core/src/transform-file.ts new file mode 100644 index 0000000..6bc2f83 --- /dev/null +++ b/node_modules/@babel/core/src/transform-file.ts @@ -0,0 +1,55 @@ +import gensync, { type Handler } from "gensync"; + +import loadConfig from "./config/index.ts"; +import type { InputOptions, ResolvedConfig } from "./config/index.ts"; +import { run } from "./transformation/index.ts"; +import type { FileResult, FileResultCallback } from "./transformation/index.ts"; +import * as fs from "./gensync-utils/fs.ts"; + +type transformFileBrowserType = typeof import("./transform-file-browser"); +type transformFileType = typeof import("./transform-file"); + +// Kind of gross, but essentially asserting that the exports of this module are the same as the +// exports of transform-file-browser, since this file may be replaced at bundle time with +// transform-file-browser. +({}) as any as transformFileBrowserType as transformFileType; + +const transformFileRunner = gensync(function* ( + filename: string, + opts?: InputOptions, +): Handler { + const options = { ...opts, filename }; + + const config: ResolvedConfig | null = yield* loadConfig(options); + if (config === null) return null; + + const code = yield* fs.readFile(filename, "utf8"); + return yield* run(config, code); +}); + +// @ts-expect-error TS doesn't detect that this signature is compatible +export function transformFile( + filename: string, + callback: FileResultCallback, +): void; +export function transformFile( + filename: string, + opts: InputOptions | undefined | null, + callback: FileResultCallback, +): void; +export function transformFile( + ...args: Parameters +) { + transformFileRunner.errback(...args); +} + +export function transformFileSync( + ...args: Parameters +) { + return transformFileRunner.sync(...args); +} +export function transformFileAsync( + ...args: Parameters +) { + return transformFileRunner.async(...args); +} diff --git a/node_modules/@babel/generator/LICENSE b/node_modules/@babel/generator/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/generator/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@babel/generator/README.md b/node_modules/@babel/generator/README.md new file mode 100644 index 0000000..d56149a --- /dev/null +++ b/node_modules/@babel/generator/README.md @@ -0,0 +1,19 @@ +# @babel/generator + +> Turns an AST into code. + +See our website [@babel/generator](https://babeljs.io/docs/babel-generator) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20generator%22+is%3Aopen) associated with this package. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/generator +``` + +or using yarn: + +```sh +yarn add @babel/generator --dev +``` diff --git a/node_modules/@babel/generator/lib/buffer.js b/node_modules/@babel/generator/lib/buffer.js new file mode 100644 index 0000000..23bedfa --- /dev/null +++ b/node_modules/@babel/generator/lib/buffer.js @@ -0,0 +1,317 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +class Buffer { + constructor(map, indentChar) { + this._map = null; + this._buf = ""; + this._str = ""; + this._appendCount = 0; + this._last = 0; + this._queue = []; + this._queueCursor = 0; + this._canMarkIdName = true; + this._indentChar = ""; + this._fastIndentations = []; + this._position = { + line: 1, + column: 0 + }; + this._sourcePosition = { + identifierName: undefined, + identifierNamePos: undefined, + line: undefined, + column: undefined, + filename: undefined + }; + this._map = map; + this._indentChar = indentChar; + for (let i = 0; i < 64; i++) { + this._fastIndentations.push(indentChar.repeat(i)); + } + this._allocQueue(); + } + _allocQueue() { + const queue = this._queue; + for (let i = 0; i < 16; i++) { + queue.push({ + char: 0, + repeat: 1, + line: undefined, + column: undefined, + identifierName: undefined, + identifierNamePos: undefined, + filename: "" + }); + } + } + _pushQueue(char, repeat, line, column, filename) { + const cursor = this._queueCursor; + if (cursor === this._queue.length) { + this._allocQueue(); + } + const item = this._queue[cursor]; + item.char = char; + item.repeat = repeat; + item.line = line; + item.column = column; + item.filename = filename; + this._queueCursor++; + } + _popQueue() { + if (this._queueCursor === 0) { + throw new Error("Cannot pop from empty queue"); + } + return this._queue[--this._queueCursor]; + } + get() { + this._flush(); + const map = this._map; + const result = { + code: (this._buf + this._str).trimRight(), + decodedMap: map == null ? void 0 : map.getDecoded(), + get __mergedMap() { + return this.map; + }, + get map() { + const resultMap = map ? map.get() : null; + result.map = resultMap; + return resultMap; + }, + set map(value) { + Object.defineProperty(result, "map", { + value, + writable: true + }); + }, + get rawMappings() { + const mappings = map == null ? void 0 : map.getRawMappings(); + result.rawMappings = mappings; + return mappings; + }, + set rawMappings(value) { + Object.defineProperty(result, "rawMappings", { + value, + writable: true + }); + } + }; + return result; + } + append(str, maybeNewline) { + this._flush(); + this._append(str, this._sourcePosition, maybeNewline); + } + appendChar(char) { + this._flush(); + this._appendChar(char, 1, this._sourcePosition); + } + queue(char) { + if (char === 10) { + while (this._queueCursor !== 0) { + const char = this._queue[this._queueCursor - 1].char; + if (char !== 32 && char !== 9) { + break; + } + this._queueCursor--; + } + } + const sourcePosition = this._sourcePosition; + this._pushQueue(char, 1, sourcePosition.line, sourcePosition.column, sourcePosition.filename); + } + queueIndentation(repeat) { + if (repeat === 0) return; + this._pushQueue(-1, repeat, undefined, undefined, undefined); + } + _flush() { + const queueCursor = this._queueCursor; + const queue = this._queue; + for (let i = 0; i < queueCursor; i++) { + const item = queue[i]; + this._appendChar(item.char, item.repeat, item); + } + this._queueCursor = 0; + } + _appendChar(char, repeat, sourcePos) { + this._last = char; + if (char === -1) { + const fastIndentation = this._fastIndentations[repeat]; + if (fastIndentation !== undefined) { + this._str += fastIndentation; + } else { + this._str += repeat > 1 ? this._indentChar.repeat(repeat) : this._indentChar; + } + } else { + this._str += repeat > 1 ? String.fromCharCode(char).repeat(repeat) : String.fromCharCode(char); + } + if (char !== 10) { + this._mark(sourcePos.line, sourcePos.column, sourcePos.identifierName, sourcePos.identifierNamePos, sourcePos.filename); + this._position.column += repeat; + } else { + this._position.line++; + this._position.column = 0; + } + if (this._canMarkIdName) { + sourcePos.identifierName = undefined; + sourcePos.identifierNamePos = undefined; + } + } + _append(str, sourcePos, maybeNewline) { + const len = str.length; + const position = this._position; + this._last = str.charCodeAt(len - 1); + if (++this._appendCount > 4096) { + +this._str; + this._buf += this._str; + this._str = str; + this._appendCount = 0; + } else { + this._str += str; + } + if (!maybeNewline && !this._map) { + position.column += len; + return; + } + const { + column, + identifierName, + identifierNamePos, + filename + } = sourcePos; + let line = sourcePos.line; + if ((identifierName != null || identifierNamePos != null) && this._canMarkIdName) { + sourcePos.identifierName = undefined; + sourcePos.identifierNamePos = undefined; + } + let i = str.indexOf("\n"); + let last = 0; + if (i !== 0) { + this._mark(line, column, identifierName, identifierNamePos, filename); + } + while (i !== -1) { + position.line++; + position.column = 0; + last = i + 1; + if (last < len && line !== undefined) { + this._mark(++line, 0, null, null, filename); + } + i = str.indexOf("\n", last); + } + position.column += len - last; + } + _mark(line, column, identifierName, identifierNamePos, filename) { + var _this$_map; + (_this$_map = this._map) == null || _this$_map.mark(this._position, line, column, identifierName, identifierNamePos, filename); + } + removeTrailingNewline() { + const queueCursor = this._queueCursor; + if (queueCursor !== 0 && this._queue[queueCursor - 1].char === 10) { + this._queueCursor--; + } + } + removeLastSemicolon() { + const queueCursor = this._queueCursor; + if (queueCursor !== 0 && this._queue[queueCursor - 1].char === 59) { + this._queueCursor--; + } + } + getLastChar() { + const queueCursor = this._queueCursor; + return queueCursor !== 0 ? this._queue[queueCursor - 1].char : this._last; + } + getNewlineCount() { + const queueCursor = this._queueCursor; + let count = 0; + if (queueCursor === 0) return this._last === 10 ? 1 : 0; + for (let i = queueCursor - 1; i >= 0; i--) { + if (this._queue[i].char !== 10) { + break; + } + count++; + } + return count === queueCursor && this._last === 10 ? count + 1 : count; + } + endsWithCharAndNewline() { + const queue = this._queue; + const queueCursor = this._queueCursor; + if (queueCursor !== 0) { + const lastCp = queue[queueCursor - 1].char; + if (lastCp !== 10) return; + if (queueCursor > 1) { + return queue[queueCursor - 2].char; + } else { + return this._last; + } + } + } + hasContent() { + return this._queueCursor !== 0 || !!this._last; + } + exactSource(loc, cb) { + if (!this._map) { + cb(); + return; + } + this.source("start", loc); + const identifierName = loc.identifierName; + const sourcePos = this._sourcePosition; + if (identifierName) { + this._canMarkIdName = false; + sourcePos.identifierName = identifierName; + } + cb(); + if (identifierName) { + this._canMarkIdName = true; + sourcePos.identifierName = undefined; + sourcePos.identifierNamePos = undefined; + } + this.source("end", loc); + } + source(prop, loc) { + if (!this._map) return; + this._normalizePosition(prop, loc, 0); + } + sourceWithOffset(prop, loc, columnOffset) { + if (!this._map) return; + this._normalizePosition(prop, loc, columnOffset); + } + _normalizePosition(prop, loc, columnOffset) { + const pos = loc[prop]; + const target = this._sourcePosition; + if (pos) { + target.line = pos.line; + target.column = Math.max(pos.column + columnOffset, 0); + target.filename = loc.filename; + } + } + getCurrentColumn() { + const queue = this._queue; + const queueCursor = this._queueCursor; + let lastIndex = -1; + let len = 0; + for (let i = 0; i < queueCursor; i++) { + const item = queue[i]; + if (item.char === 10) { + lastIndex = len; + } + len += item.repeat; + } + return lastIndex === -1 ? this._position.column + len : len - 1 - lastIndex; + } + getCurrentLine() { + let count = 0; + const queue = this._queue; + for (let i = 0; i < this._queueCursor; i++) { + if (queue[i].char === 10) { + count++; + } + } + return this._position.line + count; + } +} +exports.default = Buffer; + +//# sourceMappingURL=buffer.js.map diff --git a/node_modules/@babel/generator/lib/buffer.js.map b/node_modules/@babel/generator/lib/buffer.js.map new file mode 100644 index 0000000..87a96b4 --- /dev/null +++ b/node_modules/@babel/generator/lib/buffer.js.map @@ -0,0 +1 @@ +{"version":3,"names":["Buffer","constructor","map","indentChar","_map","_buf","_str","_appendCount","_last","_queue","_queueCursor","_canMarkIdName","_indentChar","_fastIndentations","_position","line","column","_sourcePosition","identifierName","undefined","identifierNamePos","filename","i","push","repeat","_allocQueue","queue","char","_pushQueue","cursor","length","item","_popQueue","Error","get","_flush","result","code","trimRight","decodedMap","getDecoded","__mergedMap","resultMap","value","Object","defineProperty","writable","rawMappings","mappings","getRawMappings","append","str","maybeNewline","_append","appendChar","_appendChar","sourcePosition","queueIndentation","queueCursor","sourcePos","fastIndentation","String","fromCharCode","_mark","len","position","charCodeAt","indexOf","last","_this$_map","mark","removeTrailingNewline","removeLastSemicolon","getLastChar","getNewlineCount","count","endsWithCharAndNewline","lastCp","hasContent","exactSource","loc","cb","source","prop","_normalizePosition","sourceWithOffset","columnOffset","pos","target","Math","max","getCurrentColumn","lastIndex","getCurrentLine","exports","default"],"sources":["../src/buffer.ts"],"sourcesContent":["import type SourceMap from \"./source-map.ts\";\n\n// We inline this package\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport * as charcodes from \"charcodes\";\n\nexport type Pos = {\n line: number;\n column: number;\n};\nexport type Loc = {\n start?: Pos;\n end?: Pos;\n filename?: string;\n};\ntype SourcePos = {\n line: number | undefined;\n column: number | undefined;\n identifierName: string | undefined;\n filename: string | undefined;\n};\ntype InternalSourcePos = SourcePos & { identifierNamePos: Pos };\n\ntype QueueItem = {\n char: number;\n repeat: number;\n line: number | undefined;\n column: number | undefined;\n identifierName: undefined; // Not used, it always undefined.\n identifierNamePos: undefined; // Not used, it always undefined.\n filename: string | undefined;\n};\n\nexport default class Buffer {\n constructor(map: SourceMap | null, indentChar: string) {\n this._map = map;\n this._indentChar = indentChar;\n\n for (let i = 0; i < 64; i++) {\n this._fastIndentations.push(indentChar.repeat(i));\n }\n\n this._allocQueue();\n }\n\n _map: SourceMap = null;\n _buf = \"\";\n _str = \"\";\n _appendCount = 0;\n _last = 0;\n _queue: QueueItem[] = [];\n _queueCursor = 0;\n _canMarkIdName = true;\n _indentChar = \"\";\n _fastIndentations: string[] = [];\n\n _position = {\n line: 1,\n column: 0,\n };\n _sourcePosition: InternalSourcePos = {\n identifierName: undefined,\n identifierNamePos: undefined,\n line: undefined,\n column: undefined,\n filename: undefined,\n };\n\n _allocQueue() {\n const queue = this._queue;\n\n for (let i = 0; i < 16; i++) {\n queue.push({\n char: 0,\n repeat: 1,\n line: undefined,\n column: undefined,\n identifierName: undefined,\n identifierNamePos: undefined,\n filename: \"\",\n });\n }\n }\n\n _pushQueue(\n char: number,\n repeat: number,\n line: number | undefined,\n column: number | undefined,\n filename: string | undefined,\n ) {\n const cursor = this._queueCursor;\n if (cursor === this._queue.length) {\n this._allocQueue();\n }\n const item = this._queue[cursor];\n item.char = char;\n item.repeat = repeat;\n item.line = line;\n item.column = column;\n item.filename = filename;\n\n this._queueCursor++;\n }\n\n _popQueue(): QueueItem {\n if (this._queueCursor === 0) {\n throw new Error(\"Cannot pop from empty queue\");\n }\n return this._queue[--this._queueCursor];\n }\n\n /**\n * Get the final string output from the buffer, along with the sourcemap if one exists.\n */\n\n get() {\n this._flush();\n\n const map = this._map;\n const result = {\n // Whatever trim is used here should not execute a regex against the\n // source string since it may be arbitrarily large after all transformations\n code: (this._buf + this._str).trimRight(),\n // Decoded sourcemap is free to generate.\n decodedMap: map?.getDecoded(),\n // Used as a marker for backwards compatibility. We moved input map merging\n // into the generator. We cannot merge the input map a second time, so the\n // presence of this field tells us we've already done the work.\n get __mergedMap() {\n return this.map;\n },\n // Encoding the sourcemap is moderately CPU expensive.\n get map() {\n const resultMap = map ? map.get() : null;\n result.map = resultMap;\n return resultMap;\n },\n set map(value) {\n Object.defineProperty(result, \"map\", { value, writable: true });\n },\n // Retrieving the raw mappings is very memory intensive.\n get rawMappings() {\n const mappings = map?.getRawMappings();\n result.rawMappings = mappings;\n return mappings;\n },\n set rawMappings(value) {\n Object.defineProperty(result, \"rawMappings\", { value, writable: true });\n },\n };\n\n return result;\n }\n\n /**\n * Add a string to the buffer that cannot be reverted.\n */\n\n append(str: string, maybeNewline: boolean): void {\n this._flush();\n\n this._append(str, this._sourcePosition, maybeNewline);\n }\n\n appendChar(char: number): void {\n this._flush();\n this._appendChar(char, 1, this._sourcePosition);\n }\n\n /**\n * Add a string to the buffer than can be reverted.\n */\n queue(char: number): void {\n // Drop trailing spaces when a newline is inserted.\n if (char === charcodes.lineFeed) {\n while (this._queueCursor !== 0) {\n const char = this._queue[this._queueCursor - 1].char;\n if (char !== charcodes.space && char !== charcodes.tab) {\n break;\n }\n\n this._queueCursor--;\n }\n }\n\n const sourcePosition = this._sourcePosition;\n this._pushQueue(\n char,\n 1,\n sourcePosition.line,\n sourcePosition.column,\n sourcePosition.filename,\n );\n }\n\n /**\n * Same as queue, but this indentation will never have a sourcemap marker.\n */\n queueIndentation(repeat: number): void {\n if (repeat === 0) return;\n this._pushQueue(-1, repeat, undefined, undefined, undefined);\n }\n\n _flush(): void {\n const queueCursor = this._queueCursor;\n const queue = this._queue;\n for (let i = 0; i < queueCursor; i++) {\n const item: QueueItem = queue[i];\n this._appendChar(item.char, item.repeat, item);\n }\n this._queueCursor = 0;\n }\n\n _appendChar(\n char: number,\n repeat: number,\n sourcePos: InternalSourcePos,\n ): void {\n this._last = char;\n\n if (char === -1) {\n const fastIndentation = this._fastIndentations[repeat];\n if (fastIndentation !== undefined) {\n this._str += fastIndentation;\n } else {\n this._str +=\n repeat > 1 ? this._indentChar.repeat(repeat) : this._indentChar;\n }\n } else {\n this._str +=\n repeat > 1\n ? String.fromCharCode(char).repeat(repeat)\n : String.fromCharCode(char);\n }\n\n if (char !== charcodes.lineFeed) {\n this._mark(\n sourcePos.line,\n sourcePos.column,\n sourcePos.identifierName,\n sourcePos.identifierNamePos,\n sourcePos.filename,\n );\n this._position.column += repeat;\n } else {\n this._position.line++;\n this._position.column = 0;\n }\n\n if (this._canMarkIdName) {\n sourcePos.identifierName = undefined;\n sourcePos.identifierNamePos = undefined;\n }\n }\n\n _append(\n str: string,\n sourcePos: InternalSourcePos,\n maybeNewline: boolean,\n ): void {\n const len = str.length;\n const position = this._position;\n\n this._last = str.charCodeAt(len - 1);\n\n if (++this._appendCount > 4096) {\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n +this._str; // Unexplainable huge performance boost. Ref: https://github.com/davidmarkclements/flatstr License: MIT\n this._buf += this._str;\n this._str = str;\n this._appendCount = 0;\n } else {\n this._str += str;\n }\n\n if (!maybeNewline && !this._map) {\n position.column += len;\n return;\n }\n\n const { column, identifierName, identifierNamePos, filename } = sourcePos;\n let line = sourcePos.line;\n\n if (\n (identifierName != null || identifierNamePos != null) &&\n this._canMarkIdName\n ) {\n sourcePos.identifierName = undefined;\n sourcePos.identifierNamePos = undefined;\n }\n\n // Search for newline chars. We search only for `\\n`, since both `\\r` and\n // `\\r\\n` are normalized to `\\n` during parse. We exclude `\\u2028` and\n // `\\u2029` for performance reasons, they're so uncommon that it's probably\n // ok. It's also unclear how other sourcemap utilities handle them...\n let i = str.indexOf(\"\\n\");\n let last = 0;\n\n // If the string starts with a newline char, then adding a mark is redundant.\n // This catches both \"no newlines\" and \"newline after several chars\".\n if (i !== 0) {\n this._mark(line, column, identifierName, identifierNamePos, filename);\n }\n\n // Now, find each remaining newline char in the string.\n while (i !== -1) {\n position.line++;\n position.column = 0;\n last = i + 1;\n\n // We mark the start of each line, which happens directly after this newline char\n // unless this is the last char.\n // When manually adding multi-line content (such as a comment), `line` will be `undefined`.\n if (last < len && line !== undefined) {\n this._mark(++line, 0, null, null, filename);\n }\n i = str.indexOf(\"\\n\", last);\n }\n position.column += len - last;\n }\n\n _mark(\n line: number | undefined,\n column: number | undefined,\n identifierName: string | undefined,\n identifierNamePos: Pos | undefined,\n filename: string | undefined,\n ): void {\n this._map?.mark(\n this._position,\n line,\n column,\n identifierName,\n identifierNamePos,\n filename,\n );\n }\n\n removeTrailingNewline(): void {\n const queueCursor = this._queueCursor;\n if (\n queueCursor !== 0 &&\n this._queue[queueCursor - 1].char === charcodes.lineFeed\n ) {\n this._queueCursor--;\n }\n }\n\n removeLastSemicolon(): void {\n const queueCursor = this._queueCursor;\n if (\n queueCursor !== 0 &&\n this._queue[queueCursor - 1].char === charcodes.semicolon\n ) {\n this._queueCursor--;\n }\n }\n\n getLastChar(): number {\n const queueCursor = this._queueCursor;\n return queueCursor !== 0 ? this._queue[queueCursor - 1].char : this._last;\n }\n\n /**\n * This will only detect at most 1 newline after a call to `flush()`,\n * but this has not been found so far, and an accurate count can be achieved if needed later.\n */\n getNewlineCount(): number {\n const queueCursor = this._queueCursor;\n let count = 0;\n if (queueCursor === 0) return this._last === charcodes.lineFeed ? 1 : 0;\n for (let i = queueCursor - 1; i >= 0; i--) {\n if (this._queue[i].char !== charcodes.lineFeed) {\n break;\n }\n count++;\n }\n return count === queueCursor && this._last === charcodes.lineFeed\n ? count + 1\n : count;\n }\n\n /**\n * check if current _last + queue ends with newline, return the character before newline\n */\n endsWithCharAndNewline(): number {\n const queue = this._queue;\n const queueCursor = this._queueCursor;\n if (queueCursor !== 0) {\n // every element in queue is one-length whitespace string\n const lastCp = queue[queueCursor - 1].char;\n if (lastCp !== charcodes.lineFeed) return;\n if (queueCursor > 1) {\n return queue[queueCursor - 2].char;\n } else {\n return this._last;\n }\n }\n // We assume that everything being matched is at most a single token plus some whitespace,\n // which everything currently is, but otherwise we'd have to expand _last or check _buf.\n }\n\n hasContent(): boolean {\n return this._queueCursor !== 0 || !!this._last;\n }\n\n /**\n * Certain sourcemap usecases expect mappings to be more accurate than\n * Babel's generic sourcemap handling allows. For now, we special-case\n * identifiers to allow for the primary cases to work.\n * The goal of this line is to ensure that the map output from Babel will\n * have an exact range on identifiers in the output code. Without this\n * line, Babel would potentially include some number of trailing tokens\n * that are printed after the identifier, but before another location has\n * been assigned.\n * This allows tooling like Rollup and Webpack to more accurately perform\n * their own transformations. Most importantly, this allows the import/export\n * transformations performed by those tools to loose less information when\n * applying their own transformations on top of the code and map results\n * generated by Babel itself.\n *\n * The primary example of this is the snippet:\n *\n * import mod from \"mod\";\n * mod();\n *\n * With this line, there will be one mapping range over \"mod\" and another\n * over \"();\", where previously it would have been a single mapping.\n */\n exactSource(loc: Loc | undefined, cb: () => void) {\n if (!this._map) {\n cb();\n return;\n }\n\n this.source(\"start\", loc);\n // @ts-expect-error identifierName is not defined\n const identifierName = loc.identifierName;\n const sourcePos = this._sourcePosition;\n if (identifierName) {\n this._canMarkIdName = false;\n sourcePos.identifierName = identifierName;\n }\n cb();\n\n if (identifierName) {\n this._canMarkIdName = true;\n sourcePos.identifierName = undefined;\n sourcePos.identifierNamePos = undefined;\n }\n this.source(\"end\", loc);\n }\n\n /**\n * Sets a given position as the current source location so generated code after this call\n * will be given this position in the sourcemap.\n */\n\n source(prop: \"start\" | \"end\", loc: Loc | undefined): void {\n if (!this._map) return;\n\n // Since this is called extremely often, we reuse the same _sourcePosition\n // object for the whole lifetime of the buffer.\n this._normalizePosition(prop, loc, 0);\n }\n\n sourceWithOffset(\n prop: \"start\" | \"end\",\n loc: Loc | undefined,\n columnOffset: number,\n ): void {\n if (!this._map) return;\n\n this._normalizePosition(prop, loc, columnOffset);\n }\n\n _normalizePosition(prop: \"start\" | \"end\", loc: Loc, columnOffset: number) {\n const pos = loc[prop];\n const target = this._sourcePosition;\n\n if (pos) {\n target.line = pos.line;\n // TODO: Fix https://github.com/babel/babel/issues/15712 in downstream\n target.column = Math.max(pos.column + columnOffset, 0);\n target.filename = loc.filename;\n }\n }\n\n getCurrentColumn(): number {\n const queue = this._queue;\n const queueCursor = this._queueCursor;\n\n let lastIndex = -1;\n let len = 0;\n for (let i = 0; i < queueCursor; i++) {\n const item = queue[i];\n if (item.char === charcodes.lineFeed) {\n lastIndex = len;\n }\n len += item.repeat;\n }\n\n return lastIndex === -1 ? this._position.column + len : len - 1 - lastIndex;\n }\n\n getCurrentLine(): number {\n let count = 0;\n\n const queue = this._queue;\n for (let i = 0; i < this._queueCursor; i++) {\n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,IAAI5B,GAAG,GAAG,CAAC;IACX,KAAK,IAAI1C,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGoC,WAAW,EAAEpC,CAAC,EAAE,EAAE;MACpC,MAAMS,IAAI,GAAGL,KAAK,CAACJ,CAAC,CAAC;MACrB,IAAIS,IAAI,CAACJ,IAAI,OAAuB,EAAE;QACpCiE,SAAS,GAAG5B,GAAG;MACjB;MACAA,GAAG,IAAIjC,IAAI,CAACP,MAAM;IACpB;IAEA,OAAOoE,SAAS,KAAK,CAAC,CAAC,GAAG,IAAI,CAAC9E,SAAS,CAACE,MAAM,GAAGgD,GAAG,GAAGA,GAAG,GAAG,CAAC,GAAG4B,SAAS;EAC7E;EAEAC,cAAcA,CAAA,EAAW;IACvB,IAAIlB,KAAK,GAAG,CAAC;IAEb,MAAMjD,KAAK,GAAG,IAAI,CAACjB,MAAM;IACzB,KAAK,IAAIa,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAG,IAAI,CAACZ,YAAY,EAAEY,CAAC,EAAE,EAAE;MAC1C,IAAII,KAAK,CAACJ,CAAC,CAAC,CAACK,IAAI,OAAuB,EAAE;QACxCgD,KAAK,EAAE;MACT;IACF;IAEA,OAAO,IAAI,CAAC7D,SAAS,CAACC,IAAI,GAAG4D,KAAK;EACpC;AACF;AAACmB,OAAA,CAAAC,OAAA,GAAA/F,MAAA","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/base.js b/node_modules/@babel/generator/lib/generators/base.js new file mode 100644 index 0000000..dd1e659 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/base.js @@ -0,0 +1,94 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.BlockStatement = BlockStatement; +exports.Directive = Directive; +exports.DirectiveLiteral = DirectiveLiteral; +exports.File = File; +exports.InterpreterDirective = InterpreterDirective; +exports.Placeholder = Placeholder; +exports.Program = Program; +function File(node) { + if (node.program) { + this.print(node.program.interpreter); + } + this.print(node.program); +} +function Program(node) { + var _node$directives; + this.noIndentInnerCommentsHere(); + this.printInnerComments(); + const directivesLen = (_node$directives = node.directives) == null ? void 0 : _node$directives.length; + if (directivesLen) { + var _node$directives$trai; + const newline = node.body.length ? 2 : 1; + this.printSequence(node.directives, { + trailingCommentsLineOffset: newline + }); + if (!((_node$directives$trai = node.directives[directivesLen - 1].trailingComments) != null && _node$directives$trai.length)) { + this.newline(newline); + } + } + this.printSequence(node.body); +} +function BlockStatement(node) { + var _node$directives2; + this.tokenChar(123); + const directivesLen = (_node$directives2 = node.directives) == null ? void 0 : _node$directives2.length; + if (directivesLen) { + var _node$directives$trai2; + const newline = node.body.length ? 2 : 1; + this.printSequence(node.directives, { + indent: true, + trailingCommentsLineOffset: newline + }); + if (!((_node$directives$trai2 = node.directives[directivesLen - 1].trailingComments) != null && _node$directives$trai2.length)) { + this.newline(newline); + } + } + const exit = this.enterForStatementInit(false); + this.printSequence(node.body, { + indent: true + }); + exit(); + this.rightBrace(node); +} +function Directive(node) { + this.print(node.value); + this.semicolon(); +} +const unescapedSingleQuoteRE = /(?:^|[^\\])(?:\\\\)*'/; +const unescapedDoubleQuoteRE = /(?:^|[^\\])(?:\\\\)*"/; +function DirectiveLiteral(node) { + const raw = this.getPossibleRaw(node); + if (!this.format.minified && raw !== undefined) { + this.token(raw); + return; + } + const { + value + } = node; + if (!unescapedDoubleQuoteRE.test(value)) { + this.token(`"${value}"`); + } else if (!unescapedSingleQuoteRE.test(value)) { + this.token(`'${value}'`); + } else { + throw new Error("Malformed AST: it is not possible to print a directive containing" + " both unescaped single and double quotes."); + } +} +function InterpreterDirective(node) { + this.token(`#!${node.value}`); + this.newline(1, true); +} +function Placeholder(node) { + this.token("%%"); + this.print(node.name); + this.token("%%"); + if (node.expectedNode === "Statement") { + this.semicolon(); + } +} + +//# sourceMappingURL=base.js.map diff --git a/node_modules/@babel/generator/lib/generators/base.js.map b/node_modules/@babel/generator/lib/generators/base.js.map new file mode 100644 index 0000000..1ff86d3 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/base.js.map @@ -0,0 +1 @@ +{"version":3,"names":["File","node","program","print","interpreter","Program","_node$directives","noIndentInnerCommentsHere","printInnerComments","directivesLen","directives","length","_node$directives$trai","newline","body","printSequence","trailingCommentsLineOffset","trailingComments","BlockStatement","_node$directives2","token","_node$directives$trai2","indent","exit","enterForStatementInit","rightBrace","Directive","value","semicolon","unescapedSingleQuoteRE","unescapedDoubleQuoteRE","DirectiveLiteral","raw","getPossibleRaw","format","minified","undefined","test","Error","InterpreterDirective","Placeholder","name","expectedNode"],"sources":["../../src/generators/base.ts"],"sourcesContent":["import type Printer from \"../printer.ts\";\nimport type * as t from \"@babel/types\";\n\nexport function File(this: Printer, node: t.File) {\n if (node.program) {\n // Print this here to ensure that Program node 'leadingComments' still\n // get printed after the hashbang.\n this.print(node.program.interpreter);\n }\n\n this.print(node.program);\n}\n\nexport function Program(this: Printer, node: t.Program) {\n // An empty Program doesn't have any inner tokens, so\n // we must explicitly print its inner comments.\n this.noIndentInnerCommentsHere();\n this.printInnerComments();\n\n const directivesLen = node.directives?.length;\n if (directivesLen) {\n const newline = node.body.length ? 2 : 1;\n this.printSequence(node.directives, {\n trailingCommentsLineOffset: newline,\n });\n if (!node.directives[directivesLen - 1].trailingComments?.length) {\n this.newline(newline);\n }\n }\n\n this.printSequence(node.body);\n}\n\nexport function BlockStatement(this: Printer, node: t.BlockStatement) {\n this.token(\"{\");\n\n const directivesLen = node.directives?.length;\n if (directivesLen) {\n const newline = node.body.length ? 2 : 1;\n this.printSequence(node.directives, {\n indent: true,\n trailingCommentsLineOffset: newline,\n });\n if (!node.directives[directivesLen - 1].trailingComments?.length) {\n this.newline(newline);\n }\n }\n\n const exit = this.enterForStatementInit(false);\n this.printSequence(node.body, { indent: true });\n exit();\n\n this.rightBrace(node);\n}\n\nexport function Directive(this: Printer, node: t.Directive) {\n this.print(node.value);\n this.semicolon();\n}\n\n// These regexes match an even number of \\ followed by a quote\nconst unescapedSingleQuoteRE = /(?:^|[^\\\\])(?:\\\\\\\\)*'/;\nconst unescapedDoubleQuoteRE = /(?:^|[^\\\\])(?:\\\\\\\\)*\"/;\n\nexport function DirectiveLiteral(this: Printer, node: t.DirectiveLiteral) {\n const raw = this.getPossibleRaw(node);\n if (!this.format.minified && raw !== undefined) {\n this.token(raw);\n return;\n }\n\n const { value } = node;\n\n // NOTE: In directives we can't change escapings,\n // because they change the behavior.\n // e.g. \"us\\x65 strict\" (\\x65 is e) is not a \"use strict\" directive.\n\n if (!unescapedDoubleQuoteRE.test(value)) {\n this.token(`\"${value}\"`);\n } else if (!unescapedSingleQuoteRE.test(value)) {\n this.token(`'${value}'`);\n } else {\n throw new Error(\n \"Malformed AST: it is not possible to print a directive containing\" +\n \" both unescaped single and double quotes.\",\n );\n }\n}\n\nexport function InterpreterDirective(\n this: Printer,\n node: t.InterpreterDirective,\n) {\n this.token(`#!${node.value}`);\n this.newline(1, true);\n}\n\nexport function Placeholder(this: Printer, node: t.Placeholder) {\n this.token(\"%%\");\n this.print(node.name);\n this.token(\"%%\");\n\n if (node.expectedNode === \"Statement\") {\n this.semicolon();\n }\n}\n"],"mappings":";;;;;;;;;;;;AAGO,SAASA,IAAIA,CAAgBC,IAAY,EAAE;EAChD,IAAIA,IAAI,CAACC,OAAO,EAAE;IAGhB,IAAI,CAACC,KAAK,CAACF,IAAI,CAACC,OAAO,CAACE,WAAW,CAAC;EACtC;EAEA,IAAI,CAACD,KAAK,CAACF,IAAI,CAACC,OAAO,CAAC;AAC1B;AAEO,SAASG,OAAOA,CAAgBJ,IAAe,EAAE;EAAA,IAAAK,gBAAA;EAGtD,IAAI,CAACC,yBAAyB,CAAC,CAAC;EAChC,IAAI,CAACC,kBAAkB,CAAC,CAAC;EAEzB,MAAMC,aAAa,IAAAH,gBAAA,GAAGL,IAAI,CAACS,UAAU,qBAAfJ,gBAAA,CAAiBK,MAAM;EAC7C,IAAIF,aAAa,EAAE;IAAA,IAAAG,qBAAA;IACjB,MAAM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K,CAAC,IAAI,CAAC;EAEhB,IAAInB,IAAI,CAACyC,YAAY,KAAK,WAAW,EAAE;IACrC,IAAI,CAACd,SAAS,CAAC,CAAC;EAClB;AACF","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/classes.js b/node_modules/@babel/generator/lib/generators/classes.js new file mode 100644 index 0000000..63a6499 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/classes.js @@ -0,0 +1,179 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ClassAccessorProperty = ClassAccessorProperty; +exports.ClassBody = ClassBody; +exports.ClassExpression = exports.ClassDeclaration = ClassDeclaration; +exports.ClassMethod = ClassMethod; +exports.ClassPrivateMethod = ClassPrivateMethod; +exports.ClassPrivateProperty = ClassPrivateProperty; +exports.ClassProperty = ClassProperty; +exports.StaticBlock = StaticBlock; +exports._classMethodHead = _classMethodHead; +var _t = require("@babel/types"); +const { + isExportDefaultDeclaration, + isExportNamedDeclaration +} = _t; +function ClassDeclaration(node, parent) { + const inExport = isExportDefaultDeclaration(parent) || isExportNamedDeclaration(parent); + if (!inExport || !this._shouldPrintDecoratorsBeforeExport(parent)) { + this.printJoin(node.decorators); + } + if (node.declare) { + this.word("declare"); + this.space(); + } + if (node.abstract) { + this.word("abstract"); + this.space(); + } + this.word("class"); + if (node.id) { + this.space(); + this.print(node.id); + } + this.print(node.typeParameters); + if (node.superClass) { + this.space(); + this.word("extends"); + this.space(); + this.print(node.superClass); + this.print(node.superTypeParameters); + } + if (node.implements) { + this.space(); + this.word("implements"); + this.space(); + this.printList(node.implements); + } + this.space(); + this.print(node.body); +} +function ClassBody(node) { + this.tokenChar(123); + if (node.body.length === 0) { + this.tokenChar(125); + } else { + this.newline(); + const exit = this.enterForStatementInit(false); + this.printSequence(node.body, { + indent: true + }); + exit(); + if (!this.endsWith(10)) this.newline(); + this.rightBrace(node); + } +} +function ClassProperty(node) { + var _node$key$loc; + this.printJoin(node.decorators); + const endLine = (_node$key$loc = node.key.loc) == null || (_node$key$loc = _node$key$loc.end) == null ? void 0 : _node$key$loc.line; + if (endLine) this.catchUp(endLine); + this.tsPrintClassMemberModifiers(node); + if (node.computed) { + this.tokenChar(91); + this.print(node.key); + this.tokenChar(93); + } else { + this._variance(node); + this.print(node.key); + } + if (node.optional) { + this.tokenChar(63); + } + if (node.definite) { + this.tokenChar(33); + } + this.print(node.typeAnnotation); + if (node.value) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.value); + } + this.semicolon(); +} +function ClassAccessorProperty(node) { + var _node$key$loc2; + this.printJoin(node.decorators); + const endLine = (_node$key$loc2 = node.key.loc) == null || (_node$key$loc2 = _node$key$loc2.end) == null ? void 0 : _node$key$loc2.line; + if (endLine) this.catchUp(endLine); + this.tsPrintClassMemberModifiers(node); + this.word("accessor", true); + this.space(); + if (node.computed) { + this.tokenChar(91); + this.print(node.key); + this.tokenChar(93); + } else { + this._variance(node); + this.print(node.key); + } + if (node.optional) { + this.tokenChar(63); + } + if (node.definite) { + this.tokenChar(33); + } + this.print(node.typeAnnotation); + if (node.value) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.value); + } + this.semicolon(); +} +function ClassPrivateProperty(node) { + this.printJoin(node.decorators); + if (node.static) { + this.word("static"); + this.space(); + } + this.print(node.key); + this.print(node.typeAnnotation); + if (node.value) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.value); + } + this.semicolon(); +} +function ClassMethod(node) { + this._classMethodHead(node); + this.space(); + this.print(node.body); +} +function ClassPrivateMethod(node) { + this._classMethodHead(node); + this.space(); + this.print(node.body); +} +function _classMethodHead(node) { + var _node$key$loc3; + this.printJoin(node.decorators); + const endLine = (_node$key$loc3 = node.key.loc) == null || (_node$key$loc3 = _node$key$loc3.end) == null ? void 0 : _node$key$loc3.line; + if (endLine) this.catchUp(endLine); + this.tsPrintClassMemberModifiers(node); + this._methodHead(node); +} +function StaticBlock(node) { + this.word("static"); + this.space(); + this.tokenChar(123); + if (node.body.length === 0) { + this.tokenChar(125); + } else { + this.newline(); + this.printSequence(node.body, { + indent: true + }); + this.rightBrace(node); + } +} + +//# sourceMappingURL=classes.js.map diff --git a/node_modules/@babel/generator/lib/generators/classes.js.map b/node_modules/@babel/generator/lib/generators/classes.js.map new file mode 100644 index 0000000..f327eb0 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/classes.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_t","require","isExportDefaultDeclaration","isExportNamedDeclaration","ClassDeclaration","node","parent","inExport","_shouldPrintDecoratorsBeforeExport","printJoin","decorators","declare","word","space","abstract","id","print","typeParameters","superClass","superTypeParameters","implements","printList","body","ClassBody","token","length","newline","exit","enterForStatementInit","printSequence","indent","endsWith","rightBrace","ClassProperty","_node$key$loc","endLine","key","loc","end","line","catchUp","tsPrintClassMemberModifiers","computed","_variance","optional","definite","typeAnnotation","value","semicolon","ClassAccessorProperty","_node$key$loc2","ClassPrivateProperty","static","ClassMethod","_classMethodHead","ClassPrivateMethod","_node$key$loc3","_methodHead","StaticBlock"],"sources":["../../src/generators/classes.ts"],"sourcesContent":["import type Printer from \"../printer.ts\";\nimport {\n isExportDefaultDeclaration,\n isExportNamedDeclaration,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\n\n// We inline this package\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport * as charCodes from \"charcodes\";\n\nexport function ClassDeclaration(\n this: Printer,\n node: t.ClassDeclaration,\n parent: t.Node,\n) {\n const inExport =\n isExportDefaultDeclaration(parent) || isExportNamedDeclaration(parent);\n\n if (\n !inExport ||\n !this._shouldPrintDecoratorsBeforeExport(\n parent as t.ExportDeclaration & { declaration: t.ClassDeclaration },\n )\n ) {\n this.printJoin(node.decorators);\n }\n\n if (node.declare) {\n // TS\n this.word(\"declare\");\n this.space();\n }\n\n if (node.abstract) {\n // TS\n this.word(\"abstract\");\n this.space();\n }\n\n this.word(\"class\");\n\n if (node.id) {\n this.space();\n this.print(node.id);\n }\n\n this.print(node.typeParameters);\n\n if (node.superClass) {\n this.space();\n this.word(\"extends\");\n this.space();\n this.print(node.superClass);\n this.print(node.superTypeParameters);\n }\n\n if (node.implements) {\n this.space();\n this.word(\"implements\");\n this.space();\n this.printList(node.implements);\n }\n\n this.space();\n this.print(node.body);\n}\n\nexport { ClassDeclaration as ClassExpression };\n\nexport function ClassBody(this: Printer, node: t.ClassBody) {\n this.token(\"{\");\n if (node.body.length === 0) {\n this.token(\"}\");\n } else {\n this.newline();\n\n const exit = this.enterForStatementInit(false);\n this.printSequence(node.body, { indent: true });\n exit();\n\n if (!this.endsWith(charCodes.lineFeed)) this.newline();\n\n this.rightBrace(node);\n }\n}\n\nexport function ClassProperty(this: Printer, node: t.ClassProperty) {\n this.printJoin(node.decorators);\n\n // catch up to property key, avoid line break\n // between member modifiers and the property key.\n const endLine = node.key.loc?.end?.line;\n if (endLine) this.catchUp(endLine);\n\n this.tsPrintClassMemberModifiers(node);\n\n if (node.computed) {\n this.token(\"[\");\n this.print(node.key);\n this.token(\"]\");\n } else {\n this._variance(node);\n this.print(node.key);\n }\n\n // TS\n if (node.optional) {\n this.token(\"?\");\n }\n if (node.definite) {\n this.token(\"!\");\n }\n\n this.print(node.typeAnnotation);\n if (node.value) {\n this.space();\n this.token(\"=\");\n this.space();\n this.print(node.value);\n }\n this.semicolon();\n}\n\nexport function ClassAccessorProperty(\n this: Printer,\n node: t.ClassAccessorProperty,\n) {\n this.printJoin(node.decorators);\n\n // catch up to property key, avoid line break\n // between member modifiers and the property key.\n const endLine = node.key.loc?.end?.line;\n if (endLine) this.catchUp(endLine);\n\n // TS does not support class accessor property yet\n this.tsPrintClassMemberModifiers(node);\n\n this.word(\"accessor\", true);\n this.space();\n\n if (node.computed) {\n this.token(\"[\");\n this.print(node.key);\n this.token(\"]\");\n } else {\n // Todo: Flow does not support class accessor property yet.\n this._variance(node);\n this.print(node.key);\n }\n\n // TS\n if (node.optional) {\n this.token(\"?\");\n }\n if (node.definite) {\n this.token(\"!\");\n }\n\n this.print(node.typeAnnotation);\n if (node.value) {\n this.space();\n this.token(\"=\");\n this.space();\n this.print(node.value);\n }\n this.semicolon();\n}\n\nexport function ClassPrivateProperty(\n this: Printer,\n node: t.ClassPrivateProperty,\n) {\n this.printJoin(node.decorators);\n if (node.static) {\n this.word(\"static\");\n this.space();\n }\n this.print(node.key);\n this.print(node.typeAnnotation);\n if (node.value) {\n this.space();\n this.token(\"=\");\n this.space();\n this.print(node.value);\n }\n this.semicolon();\n}\n\nexport function ClassMethod(this: Printer, node: t.ClassMethod) {\n this._classMethodHead(node);\n this.space();\n this.print(node.body);\n}\n\nexport function ClassPrivateMethod(this: Printer, node: t.ClassPrivateMethod) {\n this._classMethodHead(node);\n this.space();\n this.print(node.body);\n}\n\nexport function _classMethodHead(\n this: Printer,\n node: t.ClassMethod | t.ClassPrivateMethod | t.TSDeclareMethod,\n) {\n this.printJoin(node.decorators);\n\n // catch up to method key, avoid line break\n // between member modifiers/method heads and the method key.\n const endLine = node.key.loc?.end?.line;\n if (endLine) this.catchUp(endLine);\n\n this.tsPrintClassMemberModifiers(node);\n this._methodHead(node);\n}\n\nexport function StaticBlock(this: Printer, node: t.StaticBlock) {\n this.word(\"static\");\n this.space();\n this.token(\"{\");\n if (node.body.length === 0) {\n this.token(\"}\");\n } else {\n this.newline();\n this.printSequence(node.body, { indent: true });\n this.rightBrace(node);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AACA,IAAAA,EAAA,GAAAC,OAAA;AAGsB;EAFpBC,0BAA0B;EAC1BC;AAAwB,IAAAH,EAAA;AAQnB,SAASI,gBAAgBA,CAE9BC,IAAwB,EACxBC,MAAc,EACd;EACA,MAAMC,QAAQ,GACZL,0BAA0B,CAACI,MAAM,CAAC,IAAIH,wBAAwB,CAACG,MAAM,CAAC;EAExE,IACE,CAACC,QAAQ,IACT,CAAC,IAAI,CAACC,kCAAkC,CACtCF,MACF,CAAC,EACD;IACA,IAAI,CAACG,SAAS,CAACJ,IAAI,CAAC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AAC;EACZ,IAAI,CAACG,KAAK,CAACX,IAAI,CAACiB,IAAI,CAAC;AACvB;AAEO,SAASgC,gBAAgBA,CAE9BjD,IAA8D,EAC9D;EAAA,IAAAmD,cAAA;EACA,IAAI,CAAC/C,SAAS,CAACJ,IAAI,CAACK,UAAU,CAAC;EAI/B,MAAMyB,OAAO,IAAAqB,cAAA,GAAGnD,IAAI,CAAC+B,GAAG,CAACC,GAAG,cAAAmB,cAAA,GAAZA,cAAA,CAAclB,GAAG,qBAAjBkB,cAAA,CAAmBjB,IAAI;EACvC,IAAIJ,OAAO,EAAE,IAAI,CAACK,OAAO,CAACL,OAAO,CAAC;EAElC,IAAI,CAACM,2BAA2B,CAACpC,IAAI,CAAC;EACtC,IAAI,CAACoD,WAAW,CAACpD,IAAI,CAAC;AACxB;AAEO,SAASqD,WAAWA,CAAgBrD,IAAmB,EAAE;EAC9D,IAAI,CAACO,IAAI,CAAC,QAAQ,CAAC;EACnB,IAAI,CAACC,KAAK,CAAC,CAAC;EACZ,IAAI,CAACW,SAAK,IAAI,CAAC;EACf,IAAInB,IAAI,CAACiB,IAAI,CAACG,MAAM,KAAK,CAAC,EAAE;IAC1B,IAAI,CAACD,SAAK,IAAI,CAAC;EACjB,CAAC,MAAM;IACL,IAAI,CAACE,OAAO,CAAC,CAAC;IACd,IAAI,CAACG,aAAa,CAACxB,IAAI,CAACiB,IAAI,EAAE;MAAEQ,MAAM,EAAE;IAAK,CAAC,CAAC;IAC/C,IAAI,CAACE,UAAU,CAAC3B,IAAI,CAAC;EACvB;AACF","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/expressions.js b/node_modules/@babel/generator/lib/generators/expressions.js new file mode 100644 index 0000000..2ca5eb4 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/expressions.js @@ -0,0 +1,289 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LogicalExpression = exports.BinaryExpression = exports.AssignmentExpression = AssignmentExpression; +exports.AssignmentPattern = AssignmentPattern; +exports.AwaitExpression = AwaitExpression; +exports.BindExpression = BindExpression; +exports.CallExpression = CallExpression; +exports.ConditionalExpression = ConditionalExpression; +exports.Decorator = Decorator; +exports.DoExpression = DoExpression; +exports.EmptyStatement = EmptyStatement; +exports.ExpressionStatement = ExpressionStatement; +exports.Import = Import; +exports.MemberExpression = MemberExpression; +exports.MetaProperty = MetaProperty; +exports.ModuleExpression = ModuleExpression; +exports.NewExpression = NewExpression; +exports.OptionalCallExpression = OptionalCallExpression; +exports.OptionalMemberExpression = OptionalMemberExpression; +exports.ParenthesizedExpression = ParenthesizedExpression; +exports.PrivateName = PrivateName; +exports.SequenceExpression = SequenceExpression; +exports.Super = Super; +exports.ThisExpression = ThisExpression; +exports.UnaryExpression = UnaryExpression; +exports.UpdateExpression = UpdateExpression; +exports.V8IntrinsicIdentifier = V8IntrinsicIdentifier; +exports.YieldExpression = YieldExpression; +exports._shouldPrintDecoratorsBeforeExport = _shouldPrintDecoratorsBeforeExport; +var _t = require("@babel/types"); +var _index = require("../node/index.js"); +const { + isCallExpression, + isLiteral, + isMemberExpression, + isNewExpression +} = _t; +function UnaryExpression(node) { + const { + operator + } = node; + if (operator === "void" || operator === "delete" || operator === "typeof" || operator === "throw") { + this.word(operator); + this.space(); + } else { + this.token(operator); + } + this.print(node.argument); +} +function DoExpression(node) { + if (node.async) { + this.word("async", true); + this.space(); + } + this.word("do"); + this.space(); + this.print(node.body); +} +function ParenthesizedExpression(node) { + this.tokenChar(40); + this.print(node.expression); + this.rightParens(node); +} +function UpdateExpression(node) { + if (node.prefix) { + this.token(node.operator); + this.print(node.argument); + } else { + this.printTerminatorless(node.argument, true); + this.token(node.operator); + } +} +function ConditionalExpression(node) { + this.print(node.test); + this.space(); + this.tokenChar(63); + this.space(); + this.print(node.consequent); + this.space(); + this.tokenChar(58); + this.space(); + this.print(node.alternate); +} +function NewExpression(node, parent) { + this.word("new"); + this.space(); + this.print(node.callee); + if (this.format.minified && node.arguments.length === 0 && !node.optional && !isCallExpression(parent, { + callee: node + }) && !isMemberExpression(parent) && !isNewExpression(parent)) { + return; + } + this.print(node.typeArguments); + this.print(node.typeParameters); + if (node.optional) { + this.token("?."); + } + this.tokenChar(40); + const exit = this.enterForStatementInit(false); + this.printList(node.arguments); + exit(); + this.rightParens(node); +} +function SequenceExpression(node) { + this.printList(node.expressions); +} +function ThisExpression() { + this.word("this"); +} +function Super() { + this.word("super"); +} +function _shouldPrintDecoratorsBeforeExport(node) { + if (typeof this.format.decoratorsBeforeExport === "boolean") { + return this.format.decoratorsBeforeExport; + } + return typeof node.start === "number" && node.start === node.declaration.start; +} +function Decorator(node) { + this.tokenChar(64); + this.print(node.expression); + this.newline(); +} +function OptionalMemberExpression(node) { + let { + computed + } = node; + const { + optional, + property + } = node; + this.print(node.object); + if (!computed && isMemberExpression(property)) { + throw new TypeError("Got a MemberExpression for MemberExpression property"); + } + if (isLiteral(property) && typeof property.value === "number") { + computed = true; + } + if (optional) { + this.token("?."); + } + if (computed) { + this.tokenChar(91); + this.print(property); + this.tokenChar(93); + } else { + if (!optional) { + this.tokenChar(46); + } + this.print(property); + } +} +function OptionalCallExpression(node) { + this.print(node.callee); + this.print(node.typeParameters); + if (node.optional) { + this.token("?."); + } + this.print(node.typeArguments); + this.tokenChar(40); + const exit = this.enterForStatementInit(false); + this.printList(node.arguments); + exit(); + this.rightParens(node); +} +function CallExpression(node) { + this.print(node.callee); + this.print(node.typeArguments); + this.print(node.typeParameters); + this.tokenChar(40); + const exit = this.enterForStatementInit(false); + this.printList(node.arguments); + exit(); + this.rightParens(node); +} +function Import() { + this.word("import"); +} +function AwaitExpression(node) { + this.word("await"); + if (node.argument) { + this.space(); + this.printTerminatorless(node.argument, false); + } +} +function YieldExpression(node) { + this.word("yield", true); + if (node.delegate) { + this.tokenChar(42); + if (node.argument) { + this.space(); + this.print(node.argument); + } + } else { + if (node.argument) { + this.space(); + this.printTerminatorless(node.argument, false); + } + } +} +function EmptyStatement() { + this.semicolon(true); +} +function ExpressionStatement(node) { + this.tokenContext |= _index.TokenContext.expressionStatement; + this.print(node.expression); + this.semicolon(); +} +function AssignmentPattern(node) { + this.print(node.left); + if (node.left.type === "Identifier") { + if (node.left.optional) this.tokenChar(63); + this.print(node.left.typeAnnotation); + } + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.right); +} +function AssignmentExpression(node) { + this.print(node.left); + this.space(); + if (node.operator === "in" || node.operator === "instanceof") { + this.word(node.operator); + } else { + this.token(node.operator); + this._endsWithDiv = node.operator === "/"; + } + this.space(); + this.print(node.right); +} +function BindExpression(node) { + this.print(node.object); + this.token("::"); + this.print(node.callee); +} +function MemberExpression(node) { + this.print(node.object); + if (!node.computed && isMemberExpression(node.property)) { + throw new TypeError("Got a MemberExpression for MemberExpression property"); + } + let computed = node.computed; + if (isLiteral(node.property) && typeof node.property.value === "number") { + computed = true; + } + if (computed) { + const exit = this.enterForStatementInit(false); + this.tokenChar(91); + this.print(node.property); + this.tokenChar(93); + exit(); + } else { + this.tokenChar(46); + this.print(node.property); + } +} +function MetaProperty(node) { + this.print(node.meta); + this.tokenChar(46); + this.print(node.property); +} +function PrivateName(node) { + this.tokenChar(35); + this.print(node.id); +} +function V8IntrinsicIdentifier(node) { + this.tokenChar(37); + this.word(node.name); +} +function ModuleExpression(node) { + this.word("module", true); + this.space(); + this.tokenChar(123); + this.indent(); + const { + body + } = node; + if (body.body.length || body.directives.length) { + this.newline(); + } + this.print(body); + this.dedent(); + this.rightBrace(node); +} + +//# sourceMappingURL=expressions.js.map diff --git a/node_modules/@babel/generator/lib/generators/expressions.js.map b/node_modules/@babel/generator/lib/generators/expressions.js.map new file mode 100644 index 0000000..962a086 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/expressions.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_t","require","_index","isCallExpression","isLiteral","isMemberExpression","isNewExpression","UnaryExpression","node","operator","word","space","token","print","argument","DoExpression","async","body","ParenthesizedExpression","expression","rightParens","UpdateExpression","prefix","printTerminatorless","ConditionalExpression","test","consequent","alternate","NewExpression","parent","callee","format","minified","arguments","length","optional","typeArguments","typeParameters","exit","enterForStatementInit","printList","SequenceExpression","expressions","ThisExpression","Super","_shouldPrintDecoratorsBeforeExport","decoratorsBeforeExport","start","declaration","Decorator","newline","OptionalMemberExpression","computed","property","object","TypeError","value","OptionalCallExpression","CallExpression","Import","AwaitExpression","YieldExpression","delegate","EmptyStatement","semicolon","ExpressionStatement","tokenContext","TokenContext","expressionStatement","AssignmentPattern","left","type","typeAnnotation","right","AssignmentExpression","_endsWithDiv","BindExpression","MemberExpression","MetaProperty","meta","PrivateName","id","V8IntrinsicIdentifier","name","ModuleExpression","indent","directives","dedent","rightBrace"],"sources":["../../src/generators/expressions.ts"],"sourcesContent":["import type Printer from \"../printer.ts\";\nimport {\n isCallExpression,\n isLiteral,\n isMemberExpression,\n isNewExpression,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport { TokenContext } from \"../node/index.ts\";\n\nexport function UnaryExpression(this: Printer, node: t.UnaryExpression) {\n const { operator } = node;\n if (\n operator === \"void\" ||\n operator === \"delete\" ||\n operator === \"typeof\" ||\n // throwExpressions\n operator === \"throw\"\n ) {\n this.word(operator);\n this.space();\n } else {\n this.token(operator);\n }\n\n this.print(node.argument);\n}\n\nexport function DoExpression(this: Printer, node: t.DoExpression) {\n if (node.async) {\n this.word(\"async\", true);\n this.space();\n }\n this.word(\"do\");\n this.space();\n this.print(node.body);\n}\n\nexport function ParenthesizedExpression(\n this: Printer,\n node: t.ParenthesizedExpression,\n) {\n this.token(\"(\");\n this.print(node.expression);\n this.rightParens(node);\n}\n\nexport function UpdateExpression(this: Printer, node: t.UpdateExpression) {\n if (node.prefix) {\n this.token(node.operator);\n this.print(node.argument);\n } else {\n this.printTerminatorless(node.argument, true);\n this.token(node.operator);\n }\n}\n\nexport function ConditionalExpression(\n this: Printer,\n node: t.ConditionalExpression,\n) {\n this.print(node.test);\n this.space();\n this.token(\"?\");\n this.space();\n this.print(node.consequent);\n this.space();\n this.token(\":\");\n this.space();\n this.print(node.alternate);\n}\n\nexport function NewExpression(\n this: Printer,\n node: t.NewExpression,\n parent: t.Node,\n) {\n this.word(\"new\");\n this.space();\n this.print(node.callee);\n if (\n this.format.minified &&\n node.arguments.length === 0 &&\n !node.optional &&\n !isCallExpression(parent, { callee: node }) &&\n !isMemberExpression(parent) &&\n !isNewExpression(parent)\n ) {\n return;\n }\n\n this.print(node.typeArguments); // Flow\n this.print(node.typeParameters); // TS\n\n if (node.optional) {\n // TODO: This can never happen\n this.token(\"?.\");\n }\n this.token(\"(\");\n const exit = this.enterForStatementInit(false);\n this.printList(node.arguments);\n exit();\n this.rightParens(node);\n}\n\nexport function SequenceExpression(this: Printer, node: t.SequenceExpression) {\n this.printList(node.expressions);\n}\n\nexport function ThisExpression(this: Printer) {\n this.word(\"this\");\n}\n\nexport function Super(this: Printer) {\n this.word(\"super\");\n}\n\nexport function _shouldPrintDecoratorsBeforeExport(\n this: Printer,\n node: t.ExportDeclaration & { declaration: t.ClassDeclaration },\n) {\n if (typeof this.format.decoratorsBeforeExport === \"boolean\") {\n return this.format.decoratorsBeforeExport;\n }\n return (\n typeof node.start === \"number\" && node.start === node.declaration.start\n );\n}\n\nexport function Decorator(this: Printer, node: t.Decorator) {\n this.token(\"@\");\n this.print(node.expression);\n this.newline();\n}\n\nexport function OptionalMemberExpression(\n this: Printer,\n node: t.OptionalMemberExpression,\n) {\n let { computed } = node;\n const { optional, property } = node;\n\n this.print(node.object);\n\n if (!computed && isMemberExpression(property)) {\n throw new TypeError(\"Got a MemberExpression for MemberExpression property\");\n }\n\n // @ts-expect-error todo(flow->ts) maybe instead of typeof check specific literal types?\n if (isLiteral(property) && typeof property.value === \"number\") {\n computed = true;\n }\n if (optional) {\n this.token(\"?.\");\n }\n\n if (computed) {\n this.token(\"[\");\n this.print(property);\n this.token(\"]\");\n } else {\n if (!optional) {\n this.token(\".\");\n }\n this.print(property);\n }\n}\n\nexport function OptionalCallExpression(\n this: Printer,\n node: t.OptionalCallExpression,\n) {\n this.print(node.callee);\n\n this.print(node.typeParameters); // TS\n\n if (node.optional) {\n this.token(\"?.\");\n }\n\n this.print(node.typeArguments); // Flow\n\n this.token(\"(\");\n const exit = this.enterForStatementInit(false);\n this.printList(node.arguments);\n exit();\n this.rightParens(node);\n}\n\nexport function CallExpression(this: Printer, node: t.CallExpression) {\n this.print(node.callee);\n\n this.print(node.typeArguments); // Flow\n this.print(node.typeParameters); // TS\n this.token(\"(\");\n const exit = this.enterForStatementInit(false);\n this.printList(node.arguments);\n exit();\n this.rightParens(node);\n}\n\nexport function Import(this: Printer) {\n this.word(\"import\");\n}\n\nexport function AwaitExpression(this: Printer, node: t.AwaitExpression) {\n this.word(\"await\");\n\n if (node.argument) {\n this.space();\n this.printTerminatorless(node.argument, false);\n }\n}\n\nexport function YieldExpression(this: Printer, node: t.YieldExpression) {\n this.word(\"yield\", true);\n\n if (node.delegate) {\n this.token(\"*\");\n if (node.argument) {\n this.space();\n // line terminators are allowed after yield*\n this.print(node.argument);\n }\n } else {\n if (node.argument) {\n this.space();\n this.printTerminatorless(node.argument, false);\n }\n }\n}\n\nexport function EmptyStatement(this: Printer) {\n this.semicolon(true /* force */);\n}\n\nexport function ExpressionStatement(\n this: Printer,\n node: t.ExpressionStatement,\n) {\n this.tokenContext |= TokenContext.expressionStatement;\n this.print(node.expression);\n this.semicolon();\n}\n\nexport function AssignmentPattern(this: Printer, node: t.AssignmentPattern) {\n this.print(node.left);\n if (node.left.type === \"Identifier\") {\n if (node.left.optional) this.token(\"?\");\n this.print(node.left.typeAnnotation);\n }\n this.space();\n this.token(\"=\");\n this.space();\n this.print(node.right);\n}\n\nexport function AssignmentExpression(\n this: Printer,\n node: t.AssignmentExpression,\n) {\n this.print(node.left);\n\n this.space();\n if (node.operator === \"in\" || node.operator === \"instanceof\") {\n this.word(node.operator);\n } else {\n this.token(node.operator);\n this._endsWithDiv = node.operator === \"/\";\n }\n this.space();\n\n this.print(node.right);\n}\n\nexport function BindExpression(this: Printer, node: t.BindExpression) {\n this.print(node.object);\n this.token(\"::\");\n this.print(node.callee);\n}\n\nexport {\n AssignmentExpression as BinaryExpression,\n AssignmentExpression as LogicalExpression,\n};\n\nexport function MemberExpression(this: Printer, node: t.MemberExpression) {\n this.print(node.object);\n\n if (!node.computed && isMemberExpression(node.property)) {\n throw new TypeError(\"Got a MemberExpression for MemberExpression property\");\n }\n\n let computed = node.computed;\n // @ts-expect-error todo(flow->ts) maybe use specific literal types\n if (isLiteral(node.property) && typeof node.property.value === \"number\") {\n computed = true;\n }\n\n if (computed) {\n const exit = this.enterForStatementInit(false);\n this.token(\"[\");\n this.print(node.property);\n this.token(\"]\");\n exit();\n } else {\n this.token(\".\");\n this.print(node.property);\n }\n}\n\nexport function MetaProperty(this: Printer, node: t.MetaProperty) {\n this.print(node.meta);\n this.token(\".\");\n this.print(node.property);\n}\n\nexport function PrivateName(this: Printer, node: t.PrivateName) {\n this.token(\"#\");\n this.print(node.id);\n}\n\nexport function V8IntrinsicIdentifier(\n this: Printer,\n node: t.V8IntrinsicIdentifier,\n) {\n this.token(\"%\");\n this.word(node.name);\n}\n\nexport function ModuleExpression(this: Printer, node: t.ModuleExpression) {\n this.word(\"module\", true);\n this.space();\n this.token(\"{\");\n this.indent();\n const { body } = node;\n if (body.body.length || body.directives.length) {\n this.newline();\n }\n this.print(body);\n this.dedent();\n this.rightBrace(node);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,IAAAA,EAAA,GAAAC,OAAA;AAOA,IAAAC,MAAA,GAAAD,OAAA;AAAgD;EAN9CE,gBAAgB;EAChBC,SAAS;EACTC,kBAAkB;EAClBC;AAAe,IAAAN,EAAA;AAKV,SAASO,eAAeA,CAAgBC,IAAuB,EAAE;EACtE,MAAM;IAAEC;EAAS,CAAC,GAAGD,IAAI;EACzB,IACEC,QAAQ,KAAK,MAAM,IACnBA,QAAQ,KAAK,QAA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,GAAI,CAAC;EACf,IAAI,CAACF,IAAI,CAACF,IAAI,CAAC2E,IAAI,CAAC;AACtB;AAEO,SAASC,gBAAgBA,CAAgB5E,IAAwB,EAAE;EACxE,IAAI,CAACE,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC;EACzB,IAAI,CAACC,KAAK,CAAC,CAAC;EACZ,IAAI,CAACC,SAAK,IAAI,CAAC;EACf,IAAI,CAACyE,MAAM,CAAC,CAAC;EACb,MAAM;IAAEpE;EAAK,CAAC,GAAGT,IAAI;EACrB,IAAIS,IAAI,CAACA,IAAI,CAACiB,MAAM,IAAIjB,IAAI,CAACqE,UAAU,CAACpD,MAAM,EAAE;IAC9C,IAAI,CAACgB,OAAO,CAAC,CAAC;EAChB;EACA,IAAI,CAACrC,KAAK,CAACI,IAAI,CAAC;EAChB,IAAI,CAACsE,MAAM,CAAC,CAAC;EACb,IAAI,CAACC,UAAU,CAAChF,IAAI,CAAC;AACvB","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/flow.js b/node_modules/@babel/generator/lib/generators/flow.js new file mode 100644 index 0000000..4913531 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/flow.js @@ -0,0 +1,669 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AnyTypeAnnotation = AnyTypeAnnotation; +exports.ArrayTypeAnnotation = ArrayTypeAnnotation; +exports.BooleanLiteralTypeAnnotation = BooleanLiteralTypeAnnotation; +exports.BooleanTypeAnnotation = BooleanTypeAnnotation; +exports.DeclareClass = DeclareClass; +exports.DeclareExportAllDeclaration = DeclareExportAllDeclaration; +exports.DeclareExportDeclaration = DeclareExportDeclaration; +exports.DeclareFunction = DeclareFunction; +exports.DeclareInterface = DeclareInterface; +exports.DeclareModule = DeclareModule; +exports.DeclareModuleExports = DeclareModuleExports; +exports.DeclareOpaqueType = DeclareOpaqueType; +exports.DeclareTypeAlias = DeclareTypeAlias; +exports.DeclareVariable = DeclareVariable; +exports.DeclaredPredicate = DeclaredPredicate; +exports.EmptyTypeAnnotation = EmptyTypeAnnotation; +exports.EnumBooleanBody = EnumBooleanBody; +exports.EnumBooleanMember = EnumBooleanMember; +exports.EnumDeclaration = EnumDeclaration; +exports.EnumDefaultedMember = EnumDefaultedMember; +exports.EnumNumberBody = EnumNumberBody; +exports.EnumNumberMember = EnumNumberMember; +exports.EnumStringBody = EnumStringBody; +exports.EnumStringMember = EnumStringMember; +exports.EnumSymbolBody = EnumSymbolBody; +exports.ExistsTypeAnnotation = ExistsTypeAnnotation; +exports.FunctionTypeAnnotation = FunctionTypeAnnotation; +exports.FunctionTypeParam = FunctionTypeParam; +exports.IndexedAccessType = IndexedAccessType; +exports.InferredPredicate = InferredPredicate; +exports.InterfaceDeclaration = InterfaceDeclaration; +exports.GenericTypeAnnotation = exports.ClassImplements = exports.InterfaceExtends = InterfaceExtends; +exports.InterfaceTypeAnnotation = InterfaceTypeAnnotation; +exports.IntersectionTypeAnnotation = IntersectionTypeAnnotation; +exports.MixedTypeAnnotation = MixedTypeAnnotation; +exports.NullLiteralTypeAnnotation = NullLiteralTypeAnnotation; +exports.NullableTypeAnnotation = NullableTypeAnnotation; +Object.defineProperty(exports, "NumberLiteralTypeAnnotation", { + enumerable: true, + get: function () { + return _types2.NumericLiteral; + } +}); +exports.NumberTypeAnnotation = NumberTypeAnnotation; +exports.ObjectTypeAnnotation = ObjectTypeAnnotation; +exports.ObjectTypeCallProperty = ObjectTypeCallProperty; +exports.ObjectTypeIndexer = ObjectTypeIndexer; +exports.ObjectTypeInternalSlot = ObjectTypeInternalSlot; +exports.ObjectTypeProperty = ObjectTypeProperty; +exports.ObjectTypeSpreadProperty = ObjectTypeSpreadProperty; +exports.OpaqueType = OpaqueType; +exports.OptionalIndexedAccessType = OptionalIndexedAccessType; +exports.QualifiedTypeIdentifier = QualifiedTypeIdentifier; +Object.defineProperty(exports, "StringLiteralTypeAnnotation", { + enumerable: true, + get: function () { + return _types2.StringLiteral; + } +}); +exports.StringTypeAnnotation = StringTypeAnnotation; +exports.SymbolTypeAnnotation = SymbolTypeAnnotation; +exports.ThisTypeAnnotation = ThisTypeAnnotation; +exports.TupleTypeAnnotation = TupleTypeAnnotation; +exports.TypeAlias = TypeAlias; +exports.TypeAnnotation = TypeAnnotation; +exports.TypeCastExpression = TypeCastExpression; +exports.TypeParameter = TypeParameter; +exports.TypeParameterDeclaration = exports.TypeParameterInstantiation = TypeParameterInstantiation; +exports.TypeofTypeAnnotation = TypeofTypeAnnotation; +exports.UnionTypeAnnotation = UnionTypeAnnotation; +exports.Variance = Variance; +exports.VoidTypeAnnotation = VoidTypeAnnotation; +exports._interfaceish = _interfaceish; +exports._variance = _variance; +var _t = require("@babel/types"); +var _modules = require("./modules.js"); +var _index = require("../node/index.js"); +var _types2 = require("./types.js"); +const { + isDeclareExportDeclaration, + isStatement +} = _t; +function AnyTypeAnnotation() { + this.word("any"); +} +function ArrayTypeAnnotation(node) { + this.print(node.elementType, true); + this.tokenChar(91); + this.tokenChar(93); +} +function BooleanTypeAnnotation() { + this.word("boolean"); +} +function BooleanLiteralTypeAnnotation(node) { + this.word(node.value ? "true" : "false"); +} +function NullLiteralTypeAnnotation() { + this.word("null"); +} +function DeclareClass(node, parent) { + if (!isDeclareExportDeclaration(parent)) { + this.word("declare"); + this.space(); + } + this.word("class"); + this.space(); + this._interfaceish(node); +} +function DeclareFunction(node, parent) { + if (!isDeclareExportDeclaration(parent)) { + this.word("declare"); + this.space(); + } + this.word("function"); + this.space(); + this.print(node.id); + this.print(node.id.typeAnnotation.typeAnnotation); + if (node.predicate) { + this.space(); + this.print(node.predicate); + } + this.semicolon(); +} +function InferredPredicate() { + this.tokenChar(37); + this.word("checks"); +} +function DeclaredPredicate(node) { + this.tokenChar(37); + this.word("checks"); + this.tokenChar(40); + this.print(node.value); + this.tokenChar(41); +} +function DeclareInterface(node) { + this.word("declare"); + this.space(); + this.InterfaceDeclaration(node); +} +function DeclareModule(node) { + this.word("declare"); + this.space(); + this.word("module"); + this.space(); + this.print(node.id); + this.space(); + this.print(node.body); +} +function DeclareModuleExports(node) { + this.word("declare"); + this.space(); + this.word("module"); + this.tokenChar(46); + this.word("exports"); + this.print(node.typeAnnotation); +} +function DeclareTypeAlias(node) { + this.word("declare"); + this.space(); + this.TypeAlias(node); +} +function DeclareOpaqueType(node, parent) { + if (!isDeclareExportDeclaration(parent)) { + this.word("declare"); + this.space(); + } + this.OpaqueType(node); +} +function DeclareVariable(node, parent) { + if (!isDeclareExportDeclaration(parent)) { + this.word("declare"); + this.space(); + } + this.word("var"); + this.space(); + this.print(node.id); + this.print(node.id.typeAnnotation); + this.semicolon(); +} +function DeclareExportDeclaration(node) { + this.word("declare"); + this.space(); + this.word("export"); + this.space(); + if (node.default) { + this.word("default"); + this.space(); + } + FlowExportDeclaration.call(this, node); +} +function DeclareExportAllDeclaration(node) { + this.word("declare"); + this.space(); + _modules.ExportAllDeclaration.call(this, node); +} +function EnumDeclaration(node) { + const { + id, + body + } = node; + this.word("enum"); + this.space(); + this.print(id); + this.print(body); +} +function enumExplicitType(context, name, hasExplicitType) { + if (hasExplicitType) { + context.space(); + context.word("of"); + context.space(); + context.word(name); + } + context.space(); +} +function enumBody(context, node) { + const { + members + } = node; + context.token("{"); + context.indent(); + context.newline(); + for (const member of members) { + context.print(member); + context.newline(); + } + if (node.hasUnknownMembers) { + context.token("..."); + context.newline(); + } + context.dedent(); + context.token("}"); +} +function EnumBooleanBody(node) { + const { + explicitType + } = node; + enumExplicitType(this, "boolean", explicitType); + enumBody(this, node); +} +function EnumNumberBody(node) { + const { + explicitType + } = node; + enumExplicitType(this, "number", explicitType); + enumBody(this, node); +} +function EnumStringBody(node) { + const { + explicitType + } = node; + enumExplicitType(this, "string", explicitType); + enumBody(this, node); +} +function EnumSymbolBody(node) { + enumExplicitType(this, "symbol", true); + enumBody(this, node); +} +function EnumDefaultedMember(node) { + const { + id + } = node; + this.print(id); + this.tokenChar(44); +} +function enumInitializedMember(context, node) { + context.print(node.id); + context.space(); + context.token("="); + context.space(); + context.print(node.init); + context.token(","); +} +function EnumBooleanMember(node) { + enumInitializedMember(this, node); +} +function EnumNumberMember(node) { + enumInitializedMember(this, node); +} +function EnumStringMember(node) { + enumInitializedMember(this, node); +} +function FlowExportDeclaration(node) { + if (node.declaration) { + const declar = node.declaration; + this.print(declar); + if (!isStatement(declar)) this.semicolon(); + } else { + this.tokenChar(123); + if (node.specifiers.length) { + this.space(); + this.printList(node.specifiers); + this.space(); + } + this.tokenChar(125); + if (node.source) { + this.space(); + this.word("from"); + this.space(); + this.print(node.source); + } + this.semicolon(); + } +} +function ExistsTypeAnnotation() { + this.tokenChar(42); +} +function FunctionTypeAnnotation(node, parent) { + this.print(node.typeParameters); + this.tokenChar(40); + if (node.this) { + this.word("this"); + this.tokenChar(58); + this.space(); + this.print(node.this.typeAnnotation); + if (node.params.length || node.rest) { + this.tokenChar(44); + this.space(); + } + } + this.printList(node.params); + if (node.rest) { + if (node.params.length) { + this.tokenChar(44); + this.space(); + } + this.token("..."); + this.print(node.rest); + } + this.tokenChar(41); + const type = parent == null ? void 0 : parent.type; + if (type != null && (type === "ObjectTypeCallProperty" || type === "ObjectTypeInternalSlot" || type === "DeclareFunction" || type === "ObjectTypeProperty" && parent.method)) { + this.tokenChar(58); + } else { + this.space(); + this.token("=>"); + } + this.space(); + this.print(node.returnType); +} +function FunctionTypeParam(node) { + this.print(node.name); + if (node.optional) this.tokenChar(63); + if (node.name) { + this.tokenChar(58); + this.space(); + } + this.print(node.typeAnnotation); +} +function InterfaceExtends(node) { + this.print(node.id); + this.print(node.typeParameters, true); +} +function _interfaceish(node) { + var _node$extends; + this.print(node.id); + this.print(node.typeParameters); + if ((_node$extends = node.extends) != null && _node$extends.length) { + this.space(); + this.word("extends"); + this.space(); + this.printList(node.extends); + } + if (node.type === "DeclareClass") { + var _node$mixins, _node$implements; + if ((_node$mixins = node.mixins) != null && _node$mixins.length) { + this.space(); + this.word("mixins"); + this.space(); + this.printList(node.mixins); + } + if ((_node$implements = node.implements) != null && _node$implements.length) { + this.space(); + this.word("implements"); + this.space(); + this.printList(node.implements); + } + } + this.space(); + this.print(node.body); +} +function _variance(node) { + var _node$variance; + const kind = (_node$variance = node.variance) == null ? void 0 : _node$variance.kind; + if (kind != null) { + if (kind === "plus") { + this.tokenChar(43); + } else if (kind === "minus") { + this.tokenChar(45); + } + } +} +function InterfaceDeclaration(node) { + this.word("interface"); + this.space(); + this._interfaceish(node); +} +function andSeparator() { + this.space(); + this.tokenChar(38); + this.space(); +} +function InterfaceTypeAnnotation(node) { + var _node$extends2; + this.word("interface"); + if ((_node$extends2 = node.extends) != null && _node$extends2.length) { + this.space(); + this.word("extends"); + this.space(); + this.printList(node.extends); + } + this.space(); + this.print(node.body); +} +function IntersectionTypeAnnotation(node) { + this.printJoin(node.types, { + separator: andSeparator + }); +} +function MixedTypeAnnotation() { + this.word("mixed"); +} +function EmptyTypeAnnotation() { + this.word("empty"); +} +function NullableTypeAnnotation(node) { + this.tokenChar(63); + this.print(node.typeAnnotation); +} +function NumberTypeAnnotation() { + this.word("number"); +} +function StringTypeAnnotation() { + this.word("string"); +} +function ThisTypeAnnotation() { + this.word("this"); +} +function TupleTypeAnnotation(node) { + this.tokenChar(91); + this.printList(node.types); + this.tokenChar(93); +} +function TypeofTypeAnnotation(node) { + this.word("typeof"); + this.space(); + this.print(node.argument); +} +function TypeAlias(node) { + this.word("type"); + this.space(); + this.print(node.id); + this.print(node.typeParameters); + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.right); + this.semicolon(); +} +function TypeAnnotation(node, parent) { + this.tokenChar(58); + this.space(); + if (parent.type === "ArrowFunctionExpression") { + this.tokenContext |= _index.TokenContext.arrowFlowReturnType; + } else if (node.optional) { + this.tokenChar(63); + } + this.print(node.typeAnnotation); +} +function TypeParameterInstantiation(node) { + this.tokenChar(60); + this.printList(node.params, {}); + this.tokenChar(62); +} +function TypeParameter(node) { + this._variance(node); + this.word(node.name); + if (node.bound) { + this.print(node.bound); + } + if (node.default) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.default); + } +} +function OpaqueType(node) { + this.word("opaque"); + this.space(); + this.word("type"); + this.space(); + this.print(node.id); + this.print(node.typeParameters); + if (node.supertype) { + this.tokenChar(58); + this.space(); + this.print(node.supertype); + } + if (node.impltype) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.impltype); + } + this.semicolon(); +} +function ObjectTypeAnnotation(node) { + if (node.exact) { + this.token("{|"); + } else { + this.tokenChar(123); + } + const props = [...node.properties, ...(node.callProperties || []), ...(node.indexers || []), ...(node.internalSlots || [])]; + if (props.length) { + this.newline(); + this.space(); + this.printJoin(props, { + addNewlines(leading) { + if (leading && !props[0]) return 1; + }, + indent: true, + statement: true, + iterator: () => { + if (props.length !== 1 || node.inexact) { + this.tokenChar(44); + this.space(); + } + } + }); + this.space(); + } + if (node.inexact) { + this.indent(); + this.token("..."); + if (props.length) { + this.newline(); + } + this.dedent(); + } + if (node.exact) { + this.token("|}"); + } else { + this.tokenChar(125); + } +} +function ObjectTypeInternalSlot(node) { + if (node.static) { + this.word("static"); + this.space(); + } + this.tokenChar(91); + this.tokenChar(91); + this.print(node.id); + this.tokenChar(93); + this.tokenChar(93); + if (node.optional) this.tokenChar(63); + if (!node.method) { + this.tokenChar(58); + this.space(); + } + this.print(node.value); +} +function ObjectTypeCallProperty(node) { + if (node.static) { + this.word("static"); + this.space(); + } + this.print(node.value); +} +function ObjectTypeIndexer(node) { + if (node.static) { + this.word("static"); + this.space(); + } + this._variance(node); + this.tokenChar(91); + if (node.id) { + this.print(node.id); + this.tokenChar(58); + this.space(); + } + this.print(node.key); + this.tokenChar(93); + this.tokenChar(58); + this.space(); + this.print(node.value); +} +function ObjectTypeProperty(node) { + if (node.proto) { + this.word("proto"); + this.space(); + } + if (node.static) { + this.word("static"); + this.space(); + } + if (node.kind === "get" || node.kind === "set") { + this.word(node.kind); + this.space(); + } + this._variance(node); + this.print(node.key); + if (node.optional) this.tokenChar(63); + if (!node.method) { + this.tokenChar(58); + this.space(); + } + this.print(node.value); +} +function ObjectTypeSpreadProperty(node) { + this.token("..."); + this.print(node.argument); +} +function QualifiedTypeIdentifier(node) { + this.print(node.qualification); + this.tokenChar(46); + this.print(node.id); +} +function SymbolTypeAnnotation() { + this.word("symbol"); +} +function orSeparator() { + this.space(); + this.tokenChar(124); + this.space(); +} +function UnionTypeAnnotation(node) { + this.printJoin(node.types, { + separator: orSeparator + }); +} +function TypeCastExpression(node) { + this.tokenChar(40); + this.print(node.expression); + this.print(node.typeAnnotation); + this.tokenChar(41); +} +function Variance(node) { + if (node.kind === "plus") { + this.tokenChar(43); + } else { + this.tokenChar(45); + } +} +function VoidTypeAnnotation() { + this.word("void"); +} +function IndexedAccessType(node) { + this.print(node.objectType, true); + this.tokenChar(91); + this.print(node.indexType); + this.tokenChar(93); +} +function OptionalIndexedAccessType(node) { + this.print(node.objectType); + if (node.optional) { + this.token("?."); + } + this.tokenChar(91); + this.print(node.indexType); + this.tokenChar(93); +} + +//# sourceMappingURL=flow.js.map diff --git a/node_modules/@babel/generator/lib/generators/flow.js.map b/node_modules/@babel/generator/lib/generators/flow.js.map new file mode 100644 index 0000000..d5c6e2e --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/flow.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_t","require","_modules","_index","_types2","isDeclareExportDeclaration","isStatement","AnyTypeAnnotation","word","ArrayTypeAnnotation","node","print","elementType","token","BooleanTypeAnnotation","BooleanLiteralTypeAnnotation","value","NullLiteralTypeAnnotation","DeclareClass","parent","space","_interfaceish","DeclareFunction","id","typeAnnotation","predicate","semicolon","InferredPredicate","DeclaredPredicate","DeclareInterface","InterfaceDeclaration","DeclareModule","body","DeclareModuleExports","DeclareTypeAlias","TypeAlias","DeclareOpaqueType","OpaqueType","DeclareVariable","DeclareExportDeclaration","default","FlowExportDeclaration","call","DeclareExportAllDeclaration","ExportAllDeclaration","EnumDeclaration","enumExplicitType","context","name","hasExplicitType","enumBody","members","indent","newline","member","hasUnknownMembers","dedent","EnumBooleanBody","explicitType","EnumNumberBody","EnumStringBody","EnumSymbolBody","EnumDefaultedMember","enumInitializedMember","init","EnumBooleanMember","EnumNumberMember","EnumStringMember","declaration","declar","specifiers","length","printList","source","ExistsTypeAnnotation","FunctionTypeAnnotation","typeParameters","this","params","rest","type","method","returnType","FunctionTypeParam","optional","InterfaceExtends","_node$extends","extends","_node$mixins","_node$implements","mixins","implements","_variance","_node$variance","kind","variance","andSeparator","InterfaceTypeAnnotation","_node$extends2","IntersectionTypeAnnotation","printJoin","types","separator","MixedTypeAnnotation","EmptyTypeAnnotation","NullableTypeAnnotation","NumberTypeAnnotation","StringTypeAnnotation","ThisTypeAnnotation","TupleTypeAnnotation","TypeofTypeAnnotation","argument","right","TypeAnnotation","tokenContext","TokenContext","arrowFlowReturnType","TypeParameterInstantiation","TypeParameter","bound","supertype","impltype","ObjectTypeAnnotation","exact","props","properties","callProperties","indexers","internalSlots","addNewlines","leading","statement","iterator","inexact","ObjectTypeInternalSlot","static","ObjectTypeCallProperty","ObjectTypeIndexer","key","ObjectTypeProperty","proto","ObjectTypeSpreadProperty","QualifiedTypeIdentifier","qualification","SymbolTypeAnnotation","orSeparator","UnionTypeAnnotation","TypeCastExpression","expression","Variance","VoidTypeAnnotation","IndexedAccessType","objectType","indexType","OptionalIndexedAccessType"],"sources":["../../src/generators/flow.ts"],"sourcesContent":["import type Printer from \"../printer.ts\";\nimport { isDeclareExportDeclaration, isStatement } from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport { ExportAllDeclaration } from \"./modules.ts\";\nimport { TokenContext } from \"../node/index.ts\";\n\nexport function AnyTypeAnnotation(this: Printer) {\n this.word(\"any\");\n}\n\nexport function ArrayTypeAnnotation(\n this: Printer,\n node: t.ArrayTypeAnnotation,\n) {\n this.print(node.elementType, true);\n this.token(\"[\");\n this.token(\"]\");\n}\n\nexport function BooleanTypeAnnotation(this: Printer) {\n this.word(\"boolean\");\n}\n\nexport function BooleanLiteralTypeAnnotation(\n this: Printer,\n node: t.BooleanLiteralTypeAnnotation,\n) {\n this.word(node.value ? \"true\" : \"false\");\n}\n\nexport function NullLiteralTypeAnnotation(this: Printer) {\n this.word(\"null\");\n}\n\nexport function DeclareClass(\n this: Printer,\n node: t.DeclareClass,\n parent: t.Node,\n) {\n if (!isDeclareExportDeclaration(parent)) {\n this.word(\"declare\");\n this.space();\n }\n this.word(\"class\");\n this.space();\n this._interfaceish(node);\n}\n\nexport function DeclareFunction(\n this: Printer,\n node: t.DeclareFunction,\n parent: t.Node,\n) {\n if (!isDeclareExportDeclaration(parent)) {\n this.word(\"declare\");\n this.space();\n }\n this.word(\"function\");\n this.space();\n this.print(node.id);\n // @ts-ignore(Babel 7 vs Babel 8) TODO(Babel 8) Remove this comment, since we'll remove the Noop node\n this.print(node.id.typeAnnotation.typeAnnotation);\n\n if (node.predicate) {\n this.space();\n this.print(node.predicate);\n }\n\n this.semicolon();\n}\n\nexport function InferredPredicate(this: Printer) {\n this.token(\"%\");\n this.word(\"checks\");\n}\n\nexport function DeclaredPredicate(this: Printer, node: t.DeclaredPredicate) {\n this.token(\"%\");\n this.word(\"checks\");\n this.token(\"(\");\n this.print(node.value);\n this.token(\")\");\n}\n\nexport function DeclareInterface(this: Printer, node: t.DeclareInterface) {\n this.word(\"declare\");\n this.space();\n this.InterfaceDeclaration(node);\n}\n\nexport function DeclareModule(this: Printer, node: t.DeclareModule) {\n this.word(\"declare\");\n this.space();\n this.word(\"module\");\n this.space();\n this.print(node.id);\n this.space();\n this.print(node.body);\n}\n\nexport function DeclareModuleExports(\n this: Printer,\n node: t.DeclareModuleExports,\n) {\n this.word(\"declare\");\n this.space();\n this.word(\"module\");\n this.token(\".\");\n this.word(\"exports\");\n this.print(node.typeAnnotation);\n}\n\nexport function DeclareTypeAlias(this: Printer, node: t.DeclareTypeAlias) {\n this.word(\"declare\");\n this.space();\n this.TypeAlias(node);\n}\n\nexport function DeclareOpaqueType(\n this: Printer,\n node: t.DeclareOpaqueType,\n parent: t.Node,\n) {\n if (!isDeclareExportDeclaration(parent)) {\n this.word(\"declare\");\n this.space();\n }\n this.OpaqueType(node);\n}\n\nexport function DeclareVariable(\n this: Printer,\n node: t.DeclareVariable,\n parent: t.Node,\n) {\n if (!isDeclareExportDeclaration(parent)) {\n this.word(\"declare\");\n this.space();\n }\n this.word(\"var\");\n this.space();\n this.print(node.id);\n this.print(node.id.typeAnnotation);\n this.semicolon();\n}\n\nexport function DeclareExportDeclaration(\n this: Printer,\n node: t.DeclareExportDeclaration,\n) {\n this.word(\"declare\");\n this.space();\n this.word(\"export\");\n this.space();\n if (node.default) {\n this.word(\"default\");\n this.space();\n }\n\n FlowExportDeclaration.call(this, node);\n}\n\nexport function DeclareExportAllDeclaration(\n this: Printer,\n node: t.DeclareExportAllDeclaration,\n) {\n this.word(\"declare\");\n this.space();\n ExportAllDeclaration.call(this, node);\n}\n\nexport function EnumDeclaration(this: Printer, node: t.EnumDeclaration) {\n const { id, body } = node;\n this.word(\"enum\");\n this.space();\n this.print(id);\n this.print(body);\n}\n\nfunction enumExplicitType(\n context: Printer,\n name: string,\n hasExplicitType: boolean,\n) {\n if (hasExplicitType) {\n context.space();\n context.word(\"of\");\n context.space();\n context.word(name);\n }\n context.space();\n}\n\nfunction enumBody(context: Printer, node: t.EnumBody) {\n const { members } = node;\n context.token(\"{\");\n context.indent();\n context.newline();\n for (const member of members) {\n context.print(member);\n context.newline();\n }\n if (node.hasUnknownMembers) {\n context.token(\"...\");\n context.newline();\n }\n context.dedent();\n context.token(\"}\");\n}\n\nexport function EnumBooleanBody(this: Printer, node: t.EnumBooleanBody) {\n const { explicitType } = node;\n enumExplicitType(this, \"boolean\", explicitType);\n enumBody(this, node);\n}\n\nexport function EnumNumberBody(this: Printer, node: t.EnumNumberBody) {\n const { explicitType } = node;\n enumExplicitType(this, \"number\", explicitType);\n enumBody(this, node);\n}\n\nexport function EnumStringBody(this: Printer, node: t.EnumStringBody) {\n const { explicitType } = node;\n enumExplicitType(this, \"string\", explicitType);\n enumBody(this, node);\n}\n\nexport function EnumSymbolBody(this: Printer, node: t.EnumSymbolBody) {\n enumExplicitType(this, \"symbol\", true);\n enumBody(this, node);\n}\n\nexport function EnumDefaultedMember(\n this: Printer,\n node: t.EnumDefaultedMember,\n) {\n const { id } = node;\n this.print(id);\n this.token(\",\");\n}\n\nfunction enumInitializedMember(\n context: Printer,\n node: t.EnumBooleanMember | t.EnumNumberMember | t.EnumStringMember,\n) {\n context.print(node.id);\n context.space();\n context.token(\"=\");\n context.space();\n context.print(node.init);\n context.token(\",\");\n}\n\nexport function EnumBooleanMember(this: Printer, node: t.EnumBooleanMember) {\n enumInitializedMember(this, node);\n}\n\nexport function EnumNumberMember(this: Printer, node: t.EnumNumberMember) {\n enumInitializedMember(this, node);\n}\n\nexport function EnumStringMember(this: Printer, node: t.EnumStringMember) {\n enumInitializedMember(this, node);\n}\n\nfunction FlowExportDeclaration(\n this: Printer,\n node: t.DeclareExportDeclaration,\n) {\n if (node.declaration) {\n const declar = node.declaration;\n this.print(declar);\n if (!isStatement(declar)) this.semicolon();\n } else {\n this.token(\"{\");\n if (node.specifiers.length) {\n this.space();\n this.printList(node.specifiers);\n this.space();\n }\n this.token(\"}\");\n\n if (node.source) {\n this.space();\n this.word(\"from\");\n this.space();\n this.print(node.source);\n }\n\n this.semicolon();\n }\n}\n\nexport function ExistsTypeAnnotation(this: Printer) {\n this.token(\"*\");\n}\n\nexport function FunctionTypeAnnotation(\n this: Printer,\n node: t.FunctionTypeAnnotation,\n parent?: t.Node,\n) {\n this.print(node.typeParameters);\n this.token(\"(\");\n\n if (node.this) {\n this.word(\"this\");\n this.token(\":\");\n this.space();\n this.print(node.this.typeAnnotation);\n if (node.params.length || node.rest) {\n this.token(\",\");\n this.space();\n }\n }\n\n this.printList(node.params);\n\n if (node.rest) {\n if (node.params.length) {\n this.token(\",\");\n this.space();\n }\n this.token(\"...\");\n this.print(node.rest);\n }\n\n this.token(\")\");\n\n // this node type is overloaded, not sure why but it makes it EXTREMELY annoying\n\n const type = parent?.type;\n if (\n type != null &&\n (type === \"ObjectTypeCallProperty\" ||\n type === \"ObjectTypeInternalSlot\" ||\n type === \"DeclareFunction\" ||\n (type === \"ObjectTypeProperty\" && parent.method))\n ) {\n this.token(\":\");\n } else {\n this.space();\n this.token(\"=>\");\n }\n\n this.space();\n this.print(node.returnType);\n}\n\nexport function FunctionTypeParam(this: Printer, node: t.FunctionTypeParam) {\n this.print(node.name);\n if (node.optional) this.token(\"?\");\n if (node.name) {\n this.token(\":\");\n this.space();\n }\n this.print(node.typeAnnotation);\n}\n\nexport function InterfaceExtends(this: Printer, node: t.InterfaceExtends) {\n this.print(node.id);\n this.print(node.typeParameters, true);\n}\n\nexport {\n InterfaceExtends as ClassImplements,\n InterfaceExtends as GenericTypeAnnotation,\n};\n\nexport function _interfaceish(\n this: Printer,\n node: t.InterfaceDeclaration | t.DeclareInterface | t.DeclareClass,\n) {\n this.print(node.id);\n this.print(node.typeParameters);\n if (node.extends?.length) {\n this.space();\n this.word(\"extends\");\n this.space();\n this.printList(node.extends);\n }\n if (node.type === \"DeclareClass\") {\n if (node.mixins?.length) {\n this.space();\n this.word(\"mixins\");\n this.space();\n this.printList(node.mixins);\n }\n if (node.implements?.length) {\n this.space();\n this.word(\"implements\");\n this.space();\n this.printList(node.implements);\n }\n }\n this.space();\n this.print(node.body);\n}\n\nexport function _variance(\n this: Printer,\n node:\n | t.TypeParameter\n | t.ObjectTypeIndexer\n | t.ObjectTypeProperty\n | t.ClassProperty\n | t.ClassPrivateProperty\n | t.ClassAccessorProperty,\n) {\n const kind = node.variance?.kind;\n if (kind != null) {\n if (kind === \"plus\") {\n this.token(\"+\");\n } else if (kind === \"minus\") {\n this.token(\"-\");\n }\n }\n}\n\nexport function InterfaceDeclaration(\n this: Printer,\n node: t.InterfaceDeclaration | t.DeclareInterface,\n) {\n this.word(\"interface\");\n this.space();\n this._interfaceish(node);\n}\n\nfunction andSeparator(this: Printer) {\n this.space();\n this.token(\"&\");\n this.space();\n}\n\nexport function InterfaceTypeAnnotation(\n this: Printer,\n node: t.InterfaceTypeAnnotation,\n) {\n this.word(\"interface\");\n if (node.extends?.length) {\n this.space();\n this.word(\"extends\");\n this.space();\n this.printList(node.extends);\n }\n this.space();\n this.print(node.body);\n}\n\nexport function IntersectionTypeAnnotation(\n this: Printer,\n node: t.IntersectionTypeAnnotation,\n) {\n this.printJoin(node.types, { separator: andSeparator });\n}\n\nexport function MixedTypeAnnotation(this: Printer) {\n this.word(\"mixed\");\n}\n\nexport function EmptyTypeAnnotation(this: Printer) {\n this.word(\"empty\");\n}\n\nexport function NullableTypeAnnotation(\n this: Printer,\n node: t.NullableTypeAnnotation,\n) {\n this.token(\"?\");\n this.print(node.typeAnnotation);\n}\n\nexport {\n NumericLiteral as NumberLiteralTypeAnnotation,\n StringLiteral as StringLiteralTypeAnnotation,\n} from \"./types.ts\";\n\nexport function NumberTypeAnnotation(this: Printer) {\n this.word(\"number\");\n}\n\nexport function StringTypeAnnotation(this: Printer) {\n this.word(\"string\");\n}\n\nexport function ThisTypeAnnotation(this: Printer) {\n this.word(\"this\");\n}\n\nexport function TupleTypeAnnotation(\n this: Printer,\n node: t.TupleTypeAnnotation,\n) {\n this.token(\"[\");\n this.printList(node.types);\n this.token(\"]\");\n}\n\nexport function TypeofTypeAnnotation(\n this: Printer,\n node: t.TypeofTypeAnnotation,\n) {\n this.word(\"typeof\");\n this.space();\n this.print(node.argument);\n}\n\nexport function TypeAlias(\n this: Printer,\n node: t.TypeAlias | t.DeclareTypeAlias,\n) {\n this.word(\"type\");\n this.space();\n this.print(node.id);\n this.print(node.typeParameters);\n this.space();\n this.token(\"=\");\n this.space();\n this.print(node.right);\n this.semicolon();\n}\n\nexport function TypeAnnotation(\n this: Printer,\n node: t.TypeAnnotation,\n parent: t.Node,\n) {\n this.token(\":\");\n this.space();\n if (parent.type === \"ArrowFunctionExpression\") {\n this.tokenContext |= TokenContext.arrowFlowReturnType;\n } else if (\n // @ts-expect-error todo(flow->ts) can this be removed? `.optional` looks to be not existing property\n node.optional\n ) {\n this.token(\"?\");\n }\n this.print(node.typeAnnotation);\n}\n\nexport function TypeParameterInstantiation(\n this: Printer,\n node: t.TypeParameterInstantiation,\n): void {\n this.token(\"<\");\n this.printList(node.params, {});\n this.token(\">\");\n}\n\nexport { TypeParameterInstantiation as TypeParameterDeclaration };\n\nexport function TypeParameter(this: Printer, node: t.TypeParameter) {\n this._variance(node);\n\n this.word(node.name);\n\n if (node.bound) {\n this.print(node.bound);\n }\n\n if (node.default) {\n this.space();\n this.token(\"=\");\n this.space();\n this.print(node.default);\n }\n}\n\nexport function OpaqueType(\n this: Printer,\n node: t.OpaqueType | t.DeclareOpaqueType,\n) {\n this.word(\"opaque\");\n this.space();\n this.word(\"type\");\n this.space();\n this.print(node.id);\n this.print(node.typeParameters);\n if (node.supertype) {\n this.token(\":\");\n this.space();\n this.print(node.supertype);\n }\n\n if (node.impltype) {\n this.space();\n this.token(\"=\");\n this.space();\n this.print(node.impltype);\n }\n this.semicolon();\n}\n\nexport function ObjectTypeAnnotation(\n this: Printer,\n node: t.ObjectTypeAnnotation,\n) {\n if (node.exact) {\n this.token(\"{|\");\n } else {\n this.token(\"{\");\n }\n\n // TODO: remove the array fallbacks and instead enforce the types to require an array\n const props = [\n ...node.properties,\n ...(node.callProperties || []),\n ...(node.indexers || []),\n ...(node.internalSlots || []),\n ];\n\n if (props.length) {\n this.newline();\n\n this.space();\n\n this.printJoin(props, {\n addNewlines(leading) {\n if (leading && !props[0]) return 1;\n },\n indent: true,\n statement: true,\n iterator: () => {\n if (props.length !== 1 || node.inexact) {\n this.token(\",\");\n this.space();\n }\n },\n });\n\n this.space();\n }\n\n if (node.inexact) {\n this.indent();\n this.token(\"...\");\n if (props.length) {\n this.newline();\n }\n this.dedent();\n }\n\n if (node.exact) {\n this.token(\"|}\");\n } else {\n this.token(\"}\");\n }\n}\n\nexport function ObjectTypeInternalSlot(\n this: Printer,\n node: t.ObjectTypeInternalSlot,\n) {\n if (node.static) {\n this.word(\"static\");\n this.space();\n }\n this.token(\"[\");\n this.token(\"[\");\n this.print(node.id);\n this.token(\"]\");\n this.token(\"]\");\n if (node.optional) this.token(\"?\");\n if (!node.method) {\n this.token(\":\");\n this.space();\n }\n this.print(node.value);\n}\n\nexport function ObjectTypeCallProperty(\n this: Printer,\n node: t.ObjectTypeCallProperty,\n) {\n if (node.static) {\n this.word(\"static\");\n this.space();\n }\n this.print(node.value);\n}\n\nexport function ObjectTypeIndexer(this: Printer, node: t.ObjectTypeIndexer) {\n if (node.static) {\n this.word(\"static\");\n this.space();\n }\n this._variance(node);\n this.token(\"[\");\n if (node.id) {\n this.print(node.id);\n this.token(\":\");\n this.space();\n }\n this.print(node.key);\n this.token(\"]\");\n this.token(\":\");\n this.space();\n this.print(node.value);\n}\n\nexport function ObjectTypeProperty(this: Printer, node: t.ObjectTypeProperty) {\n if (node.proto) {\n this.word(\"proto\");\n this.space();\n }\n if (node.static) {\n this.word(\"static\");\n this.space();\n }\n if (node.kind === \"get\" || node.kind === \"set\") {\n this.word(node.kind);\n this.space();\n }\n this._variance(node);\n this.print(node.key);\n if (node.optional) this.token(\"?\");\n if (!node.method) {\n this.token(\":\");\n this.space();\n }\n this.print(node.value);\n}\n\nexport function ObjectTypeSpreadProperty(\n this: Printer,\n node: t.ObjectTypeSpreadProperty,\n) {\n this.token(\"...\");\n this.print(node.argument);\n}\n\nexport function QualifiedTypeIdentifier(\n this: Printer,\n node: t.QualifiedTypeIdentifier,\n) {\n this.print(node.qualification);\n this.token(\".\");\n this.print(node.id);\n}\n\nexport function SymbolTypeAnnotation(this: Printer) {\n this.word(\"symbol\");\n}\n\nfunction orSeparator(this: Printer) {\n this.space();\n this.token(\"|\");\n this.space();\n}\n\nexport function UnionTypeAnnotation(\n this: Printer,\n node: t.UnionTypeAnnotation,\n) {\n this.printJoin(node.types, { separator: orSeparator });\n}\n\nexport function TypeCastExpression(this: Printer, node: t.TypeCastExpression) {\n this.token(\"(\");\n this.print(node.expression);\n this.print(node.typeAnnotation);\n this.token(\")\");\n}\n\nexport function Variance(this: Printer, node: t.Variance) {\n if (node.kind === \"plus\") {\n this.token(\"+\");\n } else {\n this.token(\"-\");\n }\n}\n\nexport function VoidTypeAnnotation(this: Printer) {\n this.word(\"void\");\n}\n\nexport function IndexedAccessType(this: Printer, node: t.IndexedAccessType) {\n this.print(node.objectType, true);\n this.token(\"[\");\n this.print(node.indexType);\n this.token(\"]\");\n}\n\nexport function OptionalIndexedAccessType(\n this: Printer,\n node: t.OptionalIndexedAccessType,\n) {\n this.print(node.objectType);\n if (node.optional) {\n this.token(\"?.\");\n }\n this.token(\"[\");\n this.print(node.indexType);\n this.token(\"]\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,IAAAA,EAAA,GAAAC,OAAA;AAEA,IAAAC,QAAA,GAAAD,OAAA;AACA,IAAAE,MAAA,GAAAF,OAAA;AAqdA,IAAAG,OAAA,GAAAH,OAAA;AAGoB;EA3dXI,0BAA0B;EAAEC;AAAW,IAAAN,EAAA;AAKzC,SAASO,iBAAiBA,CAAA,EAAgB;EAC/C,IAAI,CAACC,IAAI,CAAC,KAAK,CAAC;AAClB;AAEO,SAASC,mBAAmBA,CAEjCC,IAA2B,EAC3B;EACA,IAAI,CAACC,KAAK,CAACD,IAAI,CAACE,WAAW,EAAE,IAAI,CAAC;EAClC,IAAI,CAACC,SAAK,GAAI,CAAC;EACf,IAAI,CAACA,SAAK,GAAI,CAAC;AACjB;AAEO,SAASC,qBAAqBA,CAAA,EAAgB;EACnD,IAAI,CAACN,IAAI,CAAC,SAAS,CAAC;AACtB;AAEO,SAASO,4BAA4BA,CAE1CL,IAAoC,EACpC;EACA,IAAI,CAACF,IAAI,CAACE,IAAI,CAACM,KAAK,GAAG,MAAM,GAAG,OAAO,CAAC;A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I,kBAAkBA,CAAA,EAAgB;EAChD,IAAI,CAAC9I,IAAI,CAAC,MAAM,CAAC;AACnB;AAEO,SAAS+I,iBAAiBA,CAAgB7I,IAAyB,EAAE;EAC1E,IAAI,CAACC,KAAK,CAACD,IAAI,CAAC8I,UAAU,EAAE,IAAI,CAAC;EACjC,IAAI,CAAC3I,SAAK,GAAI,CAAC;EACf,IAAI,CAACF,KAAK,CAACD,IAAI,CAAC+I,SAAS,CAAC;EAC1B,IAAI,CAAC5I,SAAK,GAAI,CAAC;AACjB;AAEO,SAAS6I,yBAAyBA,CAEvChJ,IAAiC,EACjC;EACA,IAAI,CAACC,KAAK,CAACD,IAAI,CAAC8I,UAAU,CAAC;EAC3B,IAAI9I,IAAI,CAAC0E,QAAQ,EAAE;IACjB,IAAI,CAACvE,KAAK,CAAC,IAAI,CAAC;EAClB;EACA,IAAI,CAACA,SAAK,GAAI,CAAC;EACf,IAAI,CAACF,KAAK,CAACD,IAAI,CAAC+I,SAAS,CAAC;EAC1B,IAAI,CAAC5I,SAAK,GAAI,CAAC;AACjB","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/index.js b/node_modules/@babel/generator/lib/generators/index.js new file mode 100644 index 0000000..331c73f --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/index.js @@ -0,0 +1,128 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _templateLiterals = require("./template-literals.js"); +Object.keys(_templateLiterals).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _templateLiterals[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _templateLiterals[key]; + } + }); +}); +var _expressions = require("./expressions.js"); +Object.keys(_expressions).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _expressions[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _expressions[key]; + } + }); +}); +var _statements = require("./statements.js"); +Object.keys(_statements).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _statements[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _statements[key]; + } + }); +}); +var _classes = require("./classes.js"); +Object.keys(_classes).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _classes[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _classes[key]; + } + }); +}); +var _methods = require("./methods.js"); +Object.keys(_methods).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _methods[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _methods[key]; + } + }); +}); +var _modules = require("./modules.js"); +Object.keys(_modules).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _modules[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _modules[key]; + } + }); +}); +var _types = require("./types.js"); +Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _types[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _types[key]; + } + }); +}); +var _flow = require("./flow.js"); +Object.keys(_flow).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _flow[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _flow[key]; + } + }); +}); +var _base = require("./base.js"); +Object.keys(_base).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _base[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _base[key]; + } + }); +}); +var _jsx = require("./jsx.js"); +Object.keys(_jsx).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _jsx[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _jsx[key]; + } + }); +}); +var _typescript = require("./typescript.js"); +Object.keys(_typescript).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _typescript[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _typescript[key]; + } + }); +}); + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/generator/lib/generators/index.js.map b/node_modules/@babel/generator/lib/generators/index.js.map new file mode 100644 index 0000000..e8b0341 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_templateLiterals","require","Object","keys","forEach","key","exports","defineProperty","enumerable","get","_expressions","_statements","_classes","_methods","_modules","_types","_flow","_base","_jsx","_typescript"],"sources":["../../src/generators/index.ts"],"sourcesContent":["export * from \"./template-literals.ts\";\nexport * from \"./expressions.ts\";\nexport * from \"./statements.ts\";\nexport * from \"./classes.ts\";\nexport * from \"./methods.ts\";\nexport * from \"./modules.ts\";\nexport * from \"./types.ts\";\nexport * from \"./flow.ts\";\nexport * from \"./base.ts\";\nexport * from \"./jsx.ts\";\nexport * from \"./typescript.ts\";\n"],"mappings":";;;;;AAAA,IAAAA,iBAAA,GAAAC,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAH,iBAAA,EAAAI,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAL,iBAAA,CAAAK,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA;IAAAG,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAT,iBAAA,CAAAK,GAAA;IAAA;EAAA;AAAA;AACA,IAAAK,YAAA,GAAAT,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAO,YAAA,EAAAN,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAK,YAAA,CAAAL,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAA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AAY,KAAA,CAAAZ,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA;IAAAG,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAQ,KAAA,CAAAZ,GAAA;IAAA;EAAA;AAAA;AACA,IAAAa,IAAA,GAAAjB,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAe,IAAA,EAAAd,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAa,IAAA,CAAAb,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA;IAAAG,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAS,IAAA,CAAAb,GAAA;IAAA;EAAA;AAAA;AACA,IAAAc,WAAA,GAAAlB,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAgB,WAAA,EAAAf,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAc,WAAA,CAAAd,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA;IAAAG,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAU,WAAA,CAAAd,GAAA;IAAA;EAAA;AAAA","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/jsx.js b/node_modules/@babel/generator/lib/generators/jsx.js new file mode 100644 index 0000000..90b52fb --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/jsx.js @@ -0,0 +1,123 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.JSXAttribute = JSXAttribute; +exports.JSXClosingElement = JSXClosingElement; +exports.JSXClosingFragment = JSXClosingFragment; +exports.JSXElement = JSXElement; +exports.JSXEmptyExpression = JSXEmptyExpression; +exports.JSXExpressionContainer = JSXExpressionContainer; +exports.JSXFragment = JSXFragment; +exports.JSXIdentifier = JSXIdentifier; +exports.JSXMemberExpression = JSXMemberExpression; +exports.JSXNamespacedName = JSXNamespacedName; +exports.JSXOpeningElement = JSXOpeningElement; +exports.JSXOpeningFragment = JSXOpeningFragment; +exports.JSXSpreadAttribute = JSXSpreadAttribute; +exports.JSXSpreadChild = JSXSpreadChild; +exports.JSXText = JSXText; +function JSXAttribute(node) { + this.print(node.name); + if (node.value) { + this.tokenChar(61); + this.print(node.value); + } +} +function JSXIdentifier(node) { + this.word(node.name); +} +function JSXNamespacedName(node) { + this.print(node.namespace); + this.tokenChar(58); + this.print(node.name); +} +function JSXMemberExpression(node) { + this.print(node.object); + this.tokenChar(46); + this.print(node.property); +} +function JSXSpreadAttribute(node) { + this.tokenChar(123); + this.token("..."); + this.print(node.argument); + this.rightBrace(node); +} +function JSXExpressionContainer(node) { + this.tokenChar(123); + this.print(node.expression); + this.rightBrace(node); +} +function JSXSpreadChild(node) { + this.tokenChar(123); + this.token("..."); + this.print(node.expression); + this.rightBrace(node); +} +function JSXText(node) { + const raw = this.getPossibleRaw(node); + if (raw !== undefined) { + this.token(raw, true); + } else { + this.token(node.value, true); + } +} +function JSXElement(node) { + const open = node.openingElement; + this.print(open); + if (open.selfClosing) return; + this.indent(); + for (const child of node.children) { + this.print(child); + } + this.dedent(); + this.print(node.closingElement); +} +function spaceSeparator() { + this.space(); +} +function JSXOpeningElement(node) { + this.tokenChar(60); + this.print(node.name); + this.print(node.typeParameters); + if (node.attributes.length > 0) { + this.space(); + this.printJoin(node.attributes, { + separator: spaceSeparator + }); + } + if (node.selfClosing) { + this.space(); + this.token("/>"); + } else { + this.tokenChar(62); + } +} +function JSXClosingElement(node) { + this.token(" 0) {\n this.space();\n this.printJoin(node.attributes, { separator: spaceSeparator });\n }\n if (node.selfClosing) {\n this.space();\n this.token(\"/>\");\n } else {\n this.token(\">\");\n }\n}\n\nexport function JSXClosingElement(this: Printer, node: t.JSXClosingElement) {\n this.token(\"\");\n}\n\nexport function JSXEmptyExpression(this: Printer) {\n // This node is empty, so forcefully print its inner comments.\n this.printInnerComments();\n}\n\nexport function JSXFragment(this: Printer, node: t.JSXFragment) {\n this.print(node.openingFragment);\n\n this.indent();\n for (const child of node.children) {\n this.print(child);\n }\n this.dedent();\n\n this.print(node.closingFragment);\n}\n\nexport function JSXOpeningFragment(this: Printer) {\n this.token(\"<\");\n this.token(\">\");\n}\n\nexport function JSXClosingFragment(this: Printer) {\n this.token(\"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAGO,SAASA,YAAYA,CAAgBC,IAAoB,EAAE;EAChE,IAAI,CAACC,KAAK,CAACD,IAAI,CAACE,IAAI,CAAC;EACrB,IAAIF,IAAI,CAACG,KAAK,EAAE;IACd,IAAI,CAACC,SAAK,GAAI,CAAC;IACf,IAAI,CAACH,KAAK,CAACD,IAAI,CAACG,KAAK,CAAC;EACxB;AACF;AAEO,SAASE,aAAaA,CAAgBL,IAAqB,EAAE;EAClE,IAAI,CAACM,IAAI,CAACN,IAAI,CAACE,IAAI,CAAC;AACtB;AAEO,SAASK,iBAAiBA,CAAgBP,IAAyB,EAAE;EAC1E,IAAI,CAACC,KAAK,CAACD,IAAI,CAACQ,SAAS,CAAC;EAC1B,IAAI,CAACJ,SAAK,GAAI,CAAC;EACf,IAAI,CAACH,KAAK,CAACD,IAAI,CAACE,IAAI,CAAC;AACvB;AAEO,SAASO,mBAAmBA,CAEjCT,IAA2B,EAC3B;EACA,IAAI,CAACC,KAAK,CAACD,IAAI,CAACU,MAAM,CAAC;EACvB,IAAI,CAACN,SAAK,GAAI,CAAC;EACf,IAAI,CAACH,KAAK,CAACD,IAAI,CAACW,QAAQ,CAAC;AAC3B;AAEO,SAASC,kBAAkBA,CAAgBZ,IAA0B,EAAE;EAC5E,IAAI,CAACI,SAAK,IAAI,CAAC;EACf,IAAI,CAACA,KAAK,CAAC,KAAK,CAAC;EACjB,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IAAI,CAAC4C,eAAe,CAAC;AAClC;AAEO,SAASC,kBAAkBA,CAAA,EAAgB;EAChD,IAAI,CAACzC,SAAK,GAAI,CAAC;EACf,IAAI,CAACA,SAAK,GAAI,CAAC;AACjB;AAEO,SAAS0C,kBAAkBA,CAAA,EAAgB;EAChD,IAAI,CAAC1C,KAAK,CAAC,IAAI,CAAC;EAChB,IAAI,CAACA,SAAK,GAAI,CAAC;AACjB","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/methods.js b/node_modules/@babel/generator/lib/generators/methods.js new file mode 100644 index 0000000..5155d3e --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/methods.js @@ -0,0 +1,177 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ArrowFunctionExpression = ArrowFunctionExpression; +exports.FunctionDeclaration = exports.FunctionExpression = FunctionExpression; +exports._functionHead = _functionHead; +exports._methodHead = _methodHead; +exports._param = _param; +exports._parameters = _parameters; +exports._params = _params; +exports._predicate = _predicate; +var _t = require("@babel/types"); +var _index = require("../node/index.js"); +const { + isIdentifier +} = _t; +function _params(node, idNode, parentNode) { + this.print(node.typeParameters); + const nameInfo = _getFuncIdName.call(this, idNode, parentNode); + if (nameInfo) { + this.sourceIdentifierName(nameInfo.name, nameInfo.pos); + } + this.tokenChar(40); + this._parameters(node.params); + this.tokenChar(41); + const noLineTerminator = node.type === "ArrowFunctionExpression"; + this.print(node.returnType, noLineTerminator); + this._noLineTerminator = noLineTerminator; +} +function _parameters(parameters) { + const exit = this.enterForStatementInit(false); + const paramLength = parameters.length; + for (let i = 0; i < paramLength; i++) { + this._param(parameters[i]); + if (i < parameters.length - 1) { + this.tokenChar(44); + this.space(); + } + } + exit(); +} +function _param(parameter) { + this.printJoin(parameter.decorators); + this.print(parameter); + if (parameter.optional) { + this.tokenChar(63); + } + this.print(parameter.typeAnnotation); +} +function _methodHead(node) { + const kind = node.kind; + const key = node.key; + if (kind === "get" || kind === "set") { + this.word(kind); + this.space(); + } + if (node.async) { + this.word("async", true); + this.space(); + } + if (kind === "method" || kind === "init") { + if (node.generator) { + this.tokenChar(42); + } + } + if (node.computed) { + this.tokenChar(91); + this.print(key); + this.tokenChar(93); + } else { + this.print(key); + } + if (node.optional) { + this.tokenChar(63); + } + this._params(node, node.computed && node.key.type !== "StringLiteral" ? undefined : node.key, undefined); +} +function _predicate(node, noLineTerminatorAfter) { + if (node.predicate) { + if (!node.returnType) { + this.tokenChar(58); + } + this.space(); + this.print(node.predicate, noLineTerminatorAfter); + } +} +function _functionHead(node, parent) { + if (node.async) { + this.word("async"); + this._endsWithInnerRaw = false; + this.space(); + } + this.word("function"); + if (node.generator) { + this._endsWithInnerRaw = false; + this.tokenChar(42); + } + this.space(); + if (node.id) { + this.print(node.id); + } + this._params(node, node.id, parent); + if (node.type !== "TSDeclareFunction") { + this._predicate(node); + } +} +function FunctionExpression(node, parent) { + this._functionHead(node, parent); + this.space(); + this.print(node.body); +} +function ArrowFunctionExpression(node, parent) { + if (node.async) { + this.word("async", true); + this.space(); + } + let firstParam; + if (!this.format.retainLines && node.params.length === 1 && isIdentifier(firstParam = node.params[0]) && !hasTypesOrComments(node, firstParam)) { + this.print(firstParam, true); + } else { + this._params(node, undefined, parent); + } + this._predicate(node, true); + this.space(); + this.printInnerComments(); + this.token("=>"); + this.space(); + this.tokenContext |= _index.TokenContext.arrowBody; + this.print(node.body); +} +function hasTypesOrComments(node, param) { + var _param$leadingComment, _param$trailingCommen; + return !!(node.typeParameters || node.returnType || node.predicate || param.typeAnnotation || param.optional || (_param$leadingComment = param.leadingComments) != null && _param$leadingComment.length || (_param$trailingCommen = param.trailingComments) != null && _param$trailingCommen.length); +} +function _getFuncIdName(idNode, parent) { + let id = idNode; + if (!id && parent) { + const parentType = parent.type; + if (parentType === "VariableDeclarator") { + id = parent.id; + } else if (parentType === "AssignmentExpression" || parentType === "AssignmentPattern") { + id = parent.left; + } else if (parentType === "ObjectProperty" || parentType === "ClassProperty") { + if (!parent.computed || parent.key.type === "StringLiteral") { + id = parent.key; + } + } else if (parentType === "ClassPrivateProperty" || parentType === "ClassAccessorProperty") { + id = parent.key; + } + } + if (!id) return; + let nameInfo; + if (id.type === "Identifier") { + var _id$loc, _id$loc2; + nameInfo = { + pos: (_id$loc = id.loc) == null ? void 0 : _id$loc.start, + name: ((_id$loc2 = id.loc) == null ? void 0 : _id$loc2.identifierName) || id.name + }; + } else if (id.type === "PrivateName") { + var _id$loc3; + nameInfo = { + pos: (_id$loc3 = id.loc) == null ? void 0 : _id$loc3.start, + name: "#" + id.id.name + }; + } else if (id.type === "StringLiteral") { + var _id$loc4; + nameInfo = { + pos: (_id$loc4 = id.loc) == null ? void 0 : _id$loc4.start, + name: id.value + }; + } + return nameInfo; +} + +//# sourceMappingURL=methods.js.map diff --git a/node_modules/@babel/generator/lib/generators/methods.js.map b/node_modules/@babel/generator/lib/generators/methods.js.map new file mode 100644 index 0000000..d231672 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/methods.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_t","require","_index","isIdentifier","_params","node","idNode","parentNode","print","typeParameters","nameInfo","_getFuncIdName","call","sourceIdentifierName","name","pos","token","_parameters","params","noLineTerminator","type","returnType","_noLineTerminator","parameters","exit","enterForStatementInit","paramLength","length","i","_param","space","parameter","printJoin","decorators","optional","typeAnnotation","_methodHead","kind","key","word","async","generator","computed","undefined","_predicate","noLineTerminatorAfter","predicate","_functionHead","parent","_endsWithInnerRaw","id","FunctionExpression","body","ArrowFunctionExpression","firstParam","format","retainLines","hasTypesOrComments","printInnerComments","tokenContext","TokenContext","arrowBody","param","_param$leadingComment","_param$trailingCommen","leadingComments","trailingComments","parentType","left","_id$loc","_id$loc2","loc","start","identifierName","_id$loc3","_id$loc4","value"],"sources":["../../src/generators/methods.ts"],"sourcesContent":["import type Printer from \"../printer.ts\";\nimport type * as t from \"@babel/types\";\nimport { isIdentifier, type ParentMaps } from \"@babel/types\";\nimport { TokenContext } from \"../node/index.ts\";\n\ntype ParentsOf = ParentMaps[T[\"type\"]];\n\nexport function _params(\n this: Printer,\n node: t.Function | t.TSDeclareMethod | t.TSDeclareFunction,\n idNode: t.Expression | t.PrivateName,\n parentNode: ParentsOf,\n) {\n this.print(node.typeParameters);\n\n const nameInfo = _getFuncIdName.call(this, idNode, parentNode);\n if (nameInfo) {\n this.sourceIdentifierName(nameInfo.name, nameInfo.pos);\n }\n\n this.token(\"(\");\n this._parameters(node.params);\n this.token(\")\");\n\n const noLineTerminator = node.type === \"ArrowFunctionExpression\";\n this.print(node.returnType, noLineTerminator);\n\n this._noLineTerminator = noLineTerminator;\n}\n\nexport function _parameters(this: Printer, parameters: t.Function[\"params\"]) {\n const exit = this.enterForStatementInit(false);\n\n const paramLength = parameters.length;\n for (let i = 0; i < paramLength; i++) {\n this._param(parameters[i]);\n\n if (i < parameters.length - 1) {\n this.token(\",\");\n this.space();\n }\n }\n\n exit();\n}\n\nexport function _param(\n this: Printer,\n parameter: t.Identifier | t.RestElement | t.Pattern | t.TSParameterProperty,\n) {\n this.printJoin(parameter.decorators);\n this.print(parameter);\n if (\n // @ts-expect-error optional is not in TSParameterProperty\n parameter.optional\n ) {\n this.token(\"?\"); // TS / flow\n }\n\n this.print(\n // @ts-expect-error typeAnnotation is not in TSParameterProperty\n parameter.typeAnnotation,\n ); // TS / flow\n}\n\nexport function _methodHead(this: Printer, node: t.Method | t.TSDeclareMethod) {\n const kind = node.kind;\n const key = node.key;\n\n if (kind === \"get\" || kind === \"set\") {\n this.word(kind);\n this.space();\n }\n\n if (node.async) {\n this.word(\"async\", true);\n this.space();\n }\n\n if (\n kind === \"method\" ||\n // @ts-expect-error Fixme: kind: \"init\" is not defined\n kind === \"init\"\n ) {\n if (node.generator) {\n this.token(\"*\");\n }\n }\n\n if (node.computed) {\n this.token(\"[\");\n this.print(key);\n this.token(\"]\");\n } else {\n this.print(key);\n }\n\n if (\n // @ts-expect-error optional is not in ObjectMethod\n node.optional\n ) {\n // TS\n this.token(\"?\");\n }\n\n this._params(\n node,\n node.computed && node.key.type !== \"StringLiteral\" ? undefined : node.key,\n undefined,\n );\n}\n\nexport function _predicate(\n this: Printer,\n node:\n | t.FunctionDeclaration\n | t.FunctionExpression\n | t.ArrowFunctionExpression,\n noLineTerminatorAfter?: boolean,\n) {\n if (node.predicate) {\n if (!node.returnType) {\n this.token(\":\");\n }\n this.space();\n this.print(node.predicate, noLineTerminatorAfter);\n }\n}\n\nexport function _functionHead(\n this: Printer,\n node: t.FunctionDeclaration | t.FunctionExpression | t.TSDeclareFunction,\n parent: ParentsOf,\n) {\n if (node.async) {\n this.word(\"async\");\n // We prevent inner comments from being printed here,\n // so that they are always consistently printed in the\n // same place regardless of the function type.\n this._endsWithInnerRaw = false;\n this.space();\n }\n this.word(\"function\");\n if (node.generator) {\n // We prevent inner comments from being printed here,\n // so that they are always consistently printed in the\n // same place regardless of the function type.\n this._endsWithInnerRaw = false;\n this.token(\"*\");\n }\n\n this.space();\n if (node.id) {\n this.print(node.id);\n }\n\n this._params(node, node.id, parent);\n if (node.type !== \"TSDeclareFunction\") {\n this._predicate(node);\n }\n}\n\nexport function FunctionExpression(\n this: Printer,\n node: t.FunctionExpression,\n parent: ParentsOf,\n) {\n this._functionHead(node, parent);\n this.space();\n this.print(node.body);\n}\n\nexport { FunctionExpression as FunctionDeclaration };\n\nexport function ArrowFunctionExpression(\n this: Printer,\n node: t.ArrowFunctionExpression,\n parent: ParentsOf,\n) {\n if (node.async) {\n this.word(\"async\", true);\n this.space();\n }\n\n // Try to avoid printing parens in simple cases, but only if we're pretty\n // sure that they aren't needed by type annotations or potential newlines.\n let firstParam;\n if (\n !this.format.retainLines &&\n node.params.length === 1 &&\n isIdentifier((firstParam = node.params[0])) &&\n !hasTypesOrComments(node, firstParam)\n ) {\n this.print(firstParam, true);\n } else {\n this._params(node, undefined, parent);\n }\n\n this._predicate(node, true);\n this.space();\n // When printing (x)/*1*/=>{}, we remove the parentheses\n // and thus there aren't two contiguous inner tokens.\n // We forcefully print inner comments here.\n this.printInnerComments();\n this.token(\"=>\");\n\n this.space();\n\n this.tokenContext |= TokenContext.arrowBody;\n this.print(node.body);\n}\n\nfunction hasTypesOrComments(\n node: t.ArrowFunctionExpression,\n param: t.Identifier,\n): boolean {\n return !!(\n node.typeParameters ||\n node.returnType ||\n node.predicate ||\n param.typeAnnotation ||\n param.optional ||\n // Flow does not support `foo /*: string*/ => {};`\n param.leadingComments?.length ||\n param.trailingComments?.length\n );\n}\n\nfunction _getFuncIdName(\n this: Printer,\n idNode: t.Expression | t.PrivateName,\n parent: ParentsOf,\n) {\n let id: t.Expression | t.PrivateName | t.LVal = idNode;\n\n if (!id && parent) {\n const parentType = parent.type;\n\n if (parentType === \"VariableDeclarator\") {\n id = parent.id;\n } else if (\n parentType === \"AssignmentExpression\" ||\n parentType === \"AssignmentPattern\"\n ) {\n id = parent.left;\n } else if (\n parentType === \"ObjectProperty\" ||\n parentType === \"ClassProperty\"\n ) {\n if (!parent.computed || parent.key.type === \"StringLiteral\") {\n id = parent.key;\n }\n } else if (\n parentType === \"ClassPrivateProperty\" ||\n parentType === \"ClassAccessorProperty\"\n ) {\n id = parent.key;\n }\n }\n\n if (!id) return;\n\n let nameInfo;\n\n if (id.type === \"Identifier\") {\n nameInfo = {\n pos: id.loc?.start,\n name: id.loc?.identifierName || id.name,\n };\n } else if (id.type === \"PrivateName\") {\n nameInfo = {\n pos: id.loc?.start,\n name: \"#\" + id.id.name,\n };\n } else if (id.type === \"StringLiteral\") {\n nameInfo = {\n pos: id.loc?.start,\n name: id.value,\n };\n }\n\n return nameInfo;\n}\n"],"mappings":";;;;;;;;;;;;;AAEA,IAAAA,EAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AAAgD;EADvCE;AAAY,IAAAH,EAAA;AAKd,SAASI,OAAOA,CAErBC,IAA0D,EAC1DC,MAAoC,EACpCC,UAAkC,EAClC;EACA,IAAI,CAACC,KAAK,CAACH,IAAI,C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G,GAAA2D,QAAA,GAAExB,EAAE,CAACqB,GAAG,qBAANG,QAAA,CAAQF,KAAK;MAClB1D,IAAI,EAAE,GAAG,GAAGoC,EAAE,CAACA,EAAE,CAACpC;IACpB,CAAC;EACH,CAAC,MAAM,IAAIoC,EAAE,CAAC9B,IAAI,KAAK,eAAe,EAAE;IAAA,IAAAuD,QAAA;IACtCjE,QAAQ,GAAG;MACTK,GAAG,GAAA4D,QAAA,GAAEzB,EAAE,CAACqB,GAAG,qBAANI,QAAA,CAAQH,KAAK;MAClB1D,IAAI,EAAEoC,EAAE,CAAC0B;IACX,CAAC;EACH;EAEA,OAAOlE,QAAQ;AACjB","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/modules.js b/node_modules/@babel/generator/lib/generators/modules.js new file mode 100644 index 0000000..bb7a72b --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/modules.js @@ -0,0 +1,276 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ExportAllDeclaration = ExportAllDeclaration; +exports.ExportDefaultDeclaration = ExportDefaultDeclaration; +exports.ExportDefaultSpecifier = ExportDefaultSpecifier; +exports.ExportNamedDeclaration = ExportNamedDeclaration; +exports.ExportNamespaceSpecifier = ExportNamespaceSpecifier; +exports.ExportSpecifier = ExportSpecifier; +exports.ImportAttribute = ImportAttribute; +exports.ImportDeclaration = ImportDeclaration; +exports.ImportDefaultSpecifier = ImportDefaultSpecifier; +exports.ImportExpression = ImportExpression; +exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; +exports.ImportSpecifier = ImportSpecifier; +exports._printAttributes = _printAttributes; +var _t = require("@babel/types"); +var _index = require("../node/index.js"); +const { + isClassDeclaration, + isExportDefaultSpecifier, + isExportNamespaceSpecifier, + isImportDefaultSpecifier, + isImportNamespaceSpecifier, + isStatement +} = _t; +function ImportSpecifier(node) { + if (node.importKind === "type" || node.importKind === "typeof") { + this.word(node.importKind); + this.space(); + } + this.print(node.imported); + if (node.local && node.local.name !== node.imported.name) { + this.space(); + this.word("as"); + this.space(); + this.print(node.local); + } +} +function ImportDefaultSpecifier(node) { + this.print(node.local); +} +function ExportDefaultSpecifier(node) { + this.print(node.exported); +} +function ExportSpecifier(node) { + if (node.exportKind === "type") { + this.word("type"); + this.space(); + } + this.print(node.local); + if (node.exported && node.local.name !== node.exported.name) { + this.space(); + this.word("as"); + this.space(); + this.print(node.exported); + } +} +function ExportNamespaceSpecifier(node) { + this.tokenChar(42); + this.space(); + this.word("as"); + this.space(); + this.print(node.exported); +} +let warningShown = false; +function _printAttributes(node) { + const { + importAttributesKeyword + } = this.format; + const { + attributes, + assertions + } = node; + if (attributes && !importAttributesKeyword && !warningShown) { + warningShown = true; + console.warn(`\ +You are using import attributes, without specifying the desired output syntax. +Please specify the "importAttributesKeyword" generator option, whose value can be one of: + - "with" : \`import { a } from "b" with { type: "json" };\` + - "assert" : \`import { a } from "b" assert { type: "json" };\` + - "with-legacy" : \`import { a } from "b" with type: "json";\` +`); + } + const useAssertKeyword = importAttributesKeyword === "assert" || !importAttributesKeyword && assertions; + this.word(useAssertKeyword ? "assert" : "with"); + this.space(); + if (!useAssertKeyword && importAttributesKeyword !== "with") { + this.printList(attributes || assertions); + return; + } + this.tokenChar(123); + this.space(); + this.printList(attributes || assertions); + this.space(); + this.tokenChar(125); +} +function ExportAllDeclaration(node) { + var _node$attributes, _node$assertions; + this.word("export"); + this.space(); + if (node.exportKind === "type") { + this.word("type"); + this.space(); + } + this.tokenChar(42); + this.space(); + this.word("from"); + this.space(); + if ((_node$attributes = node.attributes) != null && _node$attributes.length || (_node$assertions = node.assertions) != null && _node$assertions.length) { + this.print(node.source, true); + this.space(); + this._printAttributes(node); + } else { + this.print(node.source); + } + this.semicolon(); +} +function maybePrintDecoratorsBeforeExport(printer, node) { + if (isClassDeclaration(node.declaration) && printer._shouldPrintDecoratorsBeforeExport(node)) { + printer.printJoin(node.declaration.decorators); + } +} +function ExportNamedDeclaration(node) { + maybePrintDecoratorsBeforeExport(this, node); + this.word("export"); + this.space(); + if (node.declaration) { + const declar = node.declaration; + this.print(declar); + if (!isStatement(declar)) this.semicolon(); + } else { + if (node.exportKind === "type") { + this.word("type"); + this.space(); + } + const specifiers = node.specifiers.slice(0); + let hasSpecial = false; + for (;;) { + const first = specifiers[0]; + if (isExportDefaultSpecifier(first) || isExportNamespaceSpecifier(first)) { + hasSpecial = true; + this.print(specifiers.shift()); + if (specifiers.length) { + this.tokenChar(44); + this.space(); + } + } else { + break; + } + } + if (specifiers.length || !specifiers.length && !hasSpecial) { + this.tokenChar(123); + if (specifiers.length) { + this.space(); + this.printList(specifiers); + this.space(); + } + this.tokenChar(125); + } + if (node.source) { + var _node$attributes2, _node$assertions2; + this.space(); + this.word("from"); + this.space(); + if ((_node$attributes2 = node.attributes) != null && _node$attributes2.length || (_node$assertions2 = node.assertions) != null && _node$assertions2.length) { + this.print(node.source, true); + this.space(); + this._printAttributes(node); + } else { + this.print(node.source); + } + } + this.semicolon(); + } +} +function ExportDefaultDeclaration(node) { + maybePrintDecoratorsBeforeExport(this, node); + this.word("export"); + this.noIndentInnerCommentsHere(); + this.space(); + this.word("default"); + this.space(); + this.tokenContext |= _index.TokenContext.exportDefault; + const declar = node.declaration; + this.print(declar); + if (!isStatement(declar)) this.semicolon(); +} +function ImportDeclaration(node) { + var _node$attributes3, _node$assertions3; + this.word("import"); + this.space(); + const isTypeKind = node.importKind === "type" || node.importKind === "typeof"; + if (isTypeKind) { + this.noIndentInnerCommentsHere(); + this.word(node.importKind); + this.space(); + } else if (node.module) { + this.noIndentInnerCommentsHere(); + this.word("module"); + this.space(); + } else if (node.phase) { + this.noIndentInnerCommentsHere(); + this.word(node.phase); + this.space(); + } + const specifiers = node.specifiers.slice(0); + const hasSpecifiers = !!specifiers.length; + while (hasSpecifiers) { + const first = specifiers[0]; + if (isImportDefaultSpecifier(first) || isImportNamespaceSpecifier(first)) { + this.print(specifiers.shift()); + if (specifiers.length) { + this.tokenChar(44); + this.space(); + } + } else { + break; + } + } + if (specifiers.length) { + this.tokenChar(123); + this.space(); + this.printList(specifiers); + this.space(); + this.tokenChar(125); + } else if (isTypeKind && !hasSpecifiers) { + this.tokenChar(123); + this.tokenChar(125); + } + if (hasSpecifiers || isTypeKind) { + this.space(); + this.word("from"); + this.space(); + } + if ((_node$attributes3 = node.attributes) != null && _node$attributes3.length || (_node$assertions3 = node.assertions) != null && _node$assertions3.length) { + this.print(node.source, true); + this.space(); + this._printAttributes(node); + } else { + this.print(node.source); + } + this.semicolon(); +} +function ImportAttribute(node) { + this.print(node.key); + this.tokenChar(58); + this.space(); + this.print(node.value); +} +function ImportNamespaceSpecifier(node) { + this.tokenChar(42); + this.space(); + this.word("as"); + this.space(); + this.print(node.local); +} +function ImportExpression(node) { + this.word("import"); + if (node.phase) { + this.tokenChar(46); + this.word(node.phase); + } + this.tokenChar(40); + this.print(node.source); + if (node.options != null) { + this.tokenChar(44); + this.space(); + this.print(node.options); + } + this.tokenChar(41); +} + +//# sourceMappingURL=modules.js.map diff --git a/node_modules/@babel/generator/lib/generators/modules.js.map b/node_modules/@babel/generator/lib/generators/modules.js.map new file mode 100644 index 0000000..7aed326 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/modules.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_t","require","_index","isClassDeclaration","isExportDefaultSpecifier","isExportNamespaceSpecifier","isImportDefaultSpecifier","isImportNamespaceSpecifier","isStatement","ImportSpecifier","node","importKind","word","space","print","imported","local","name","ImportDefaultSpecifier","ExportDefaultSpecifier","exported","ExportSpecifier","exportKind","ExportNamespaceSpecifier","token","warningShown","_printAttributes","importAttributesKeyword","format","attributes","assertions","console","warn","useAssertKeyword","printList","ExportAllDeclaration","_node$attributes","_node$assertions","length","source","semicolon","maybePrintDecoratorsBeforeExport","printer","declaration","_shouldPrintDecoratorsBeforeExport","printJoin","decorators","ExportNamedDeclaration","declar","specifiers","slice","hasSpecial","first","shift","_node$attributes2","_node$assertions2","ExportDefaultDeclaration","noIndentInnerCommentsHere","tokenContext","TokenContext","exportDefault","ImportDeclaration","_node$attributes3","_node$assertions3","isTypeKind","module","phase","hasSpecifiers","ImportAttribute","key","value","ImportNamespaceSpecifier","ImportExpression","options"],"sources":["../../src/generators/modules.ts"],"sourcesContent":["import type Printer from \"../printer.ts\";\nimport {\n isClassDeclaration,\n isExportDefaultSpecifier,\n isExportNamespaceSpecifier,\n isImportDefaultSpecifier,\n isImportNamespaceSpecifier,\n isStatement,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport { TokenContext } from \"../node/index.ts\";\n\nexport function ImportSpecifier(this: Printer, node: t.ImportSpecifier) {\n if (node.importKind === \"type\" || node.importKind === \"typeof\") {\n this.word(node.importKind);\n this.space();\n }\n\n this.print(node.imported);\n // @ts-expect-error todo(flow-ts) maybe check node type instead of relying on name to be undefined on t.StringLiteral\n if (node.local && node.local.name !== node.imported.name) {\n this.space();\n this.word(\"as\");\n this.space();\n this.print(node.local);\n }\n}\n\nexport function ImportDefaultSpecifier(\n this: Printer,\n node: t.ImportDefaultSpecifier,\n) {\n this.print(node.local);\n}\n\nexport function ExportDefaultSpecifier(\n this: Printer,\n node: t.ExportDefaultSpecifier,\n) {\n this.print(node.exported);\n}\n\nexport function ExportSpecifier(this: Printer, node: t.ExportSpecifier) {\n if (node.exportKind === \"type\") {\n this.word(\"type\");\n this.space();\n }\n\n this.print(node.local);\n // @ts-expect-error todo(flow-ts) maybe check node type instead of relying on name to be undefined on t.StringLiteral\n if (node.exported && node.local.name !== node.exported.name) {\n this.space();\n this.word(\"as\");\n this.space();\n this.print(node.exported);\n }\n}\n\nexport function ExportNamespaceSpecifier(\n this: Printer,\n node: t.ExportNamespaceSpecifier,\n) {\n this.token(\"*\");\n this.space();\n this.word(\"as\");\n this.space();\n this.print(node.exported);\n}\n\nlet warningShown = false;\n\nexport function _printAttributes(\n this: Printer,\n node: Extract,\n) {\n const { importAttributesKeyword } = this.format;\n const { attributes, assertions } = node;\n\n if (\n attributes &&\n !importAttributesKeyword &&\n // In the production build only show the warning once.\n // We want to show it per-usage locally for tests.\n (!process.env.IS_PUBLISH || !warningShown)\n ) {\n warningShown = true;\n console.warn(`\\\nYou are using import attributes, without specifying the desired output syntax.\nPlease specify the \"importAttributesKeyword\" generator option, whose value can be one of:\n - \"with\" : \\`import { a } from \"b\" with { type: \"json\" };\\`\n - \"assert\" : \\`import { a } from \"b\" assert { type: \"json\" };\\`\n - \"with-legacy\" : \\`import { a } from \"b\" with type: \"json\";\\`\n`);\n }\n\n const useAssertKeyword =\n importAttributesKeyword === \"assert\" ||\n (!importAttributesKeyword && assertions);\n\n this.word(useAssertKeyword ? \"assert\" : \"with\");\n this.space();\n\n if (!useAssertKeyword && importAttributesKeyword !== \"with\") {\n // with-legacy\n this.printList(attributes || assertions);\n return;\n }\n\n this.token(\"{\");\n this.space();\n this.printList(attributes || assertions);\n this.space();\n this.token(\"}\");\n}\n\nexport function ExportAllDeclaration(\n this: Printer,\n node: t.ExportAllDeclaration | t.DeclareExportAllDeclaration,\n) {\n this.word(\"export\");\n this.space();\n if (node.exportKind === \"type\") {\n this.word(\"type\");\n this.space();\n }\n this.token(\"*\");\n this.space();\n this.word(\"from\");\n this.space();\n // @ts-expect-error Fixme: attributes is not defined in DeclareExportAllDeclaration\n if (node.attributes?.length || node.assertions?.length) {\n this.print(node.source, true);\n this.space();\n // @ts-expect-error Fixme: attributes is not defined in DeclareExportAllDeclaration\n this._printAttributes(node);\n } else {\n this.print(node.source);\n }\n\n this.semicolon();\n}\n\nfunction maybePrintDecoratorsBeforeExport(\n printer: Printer,\n node: t.ExportNamedDeclaration | t.ExportDefaultDeclaration,\n) {\n if (\n isClassDeclaration(node.declaration) &&\n printer._shouldPrintDecoratorsBeforeExport(\n node as t.ExportNamedDeclaration & { declaration: t.ClassDeclaration },\n )\n ) {\n printer.printJoin(node.declaration.decorators);\n }\n}\n\nexport function ExportNamedDeclaration(\n this: Printer,\n node: t.ExportNamedDeclaration,\n) {\n maybePrintDecoratorsBeforeExport(this, node);\n\n this.word(\"export\");\n this.space();\n if (node.declaration) {\n const declar = node.declaration;\n this.print(declar);\n if (!isStatement(declar)) this.semicolon();\n } else {\n if (node.exportKind === \"type\") {\n this.word(\"type\");\n this.space();\n }\n\n const specifiers = node.specifiers.slice(0);\n\n // print \"special\" specifiers first\n let hasSpecial = false;\n for (;;) {\n const first = specifiers[0];\n if (\n isExportDefaultSpecifier(first) ||\n isExportNamespaceSpecifier(first)\n ) {\n hasSpecial = true;\n this.print(specifiers.shift());\n if (specifiers.length) {\n this.token(\",\");\n this.space();\n }\n } else {\n break;\n }\n }\n\n if (specifiers.length || (!specifiers.length && !hasSpecial)) {\n this.token(\"{\");\n if (specifiers.length) {\n this.space();\n this.printList(specifiers);\n this.space();\n }\n this.token(\"}\");\n }\n\n if (node.source) {\n this.space();\n this.word(\"from\");\n this.space();\n if (node.attributes?.length || node.assertions?.length) {\n this.print(node.source, true);\n this.space();\n this._printAttributes(node);\n } else {\n this.print(node.source);\n }\n }\n\n this.semicolon();\n }\n}\n\nexport function ExportDefaultDeclaration(\n this: Printer,\n node: t.ExportDefaultDeclaration,\n) {\n maybePrintDecoratorsBeforeExport(this, node);\n\n this.word(\"export\");\n this.noIndentInnerCommentsHere();\n this.space();\n this.word(\"default\");\n this.space();\n this.tokenContext |= TokenContext.exportDefault;\n const declar = node.declaration;\n this.print(declar);\n if (!isStatement(declar)) this.semicolon();\n}\n\nexport function ImportDeclaration(this: Printer, node: t.ImportDeclaration) {\n this.word(\"import\");\n this.space();\n\n const isTypeKind = node.importKind === \"type\" || node.importKind === \"typeof\";\n if (isTypeKind) {\n this.noIndentInnerCommentsHere();\n this.word(node.importKind);\n this.space();\n } else if (node.module) {\n this.noIndentInnerCommentsHere();\n this.word(\"module\");\n this.space();\n } else if (node.phase) {\n this.noIndentInnerCommentsHere();\n this.word(node.phase);\n this.space();\n }\n\n const specifiers = node.specifiers.slice(0);\n const hasSpecifiers = !!specifiers.length;\n // print \"special\" specifiers first. The loop condition is constant,\n // but there is a \"break\" in the body.\n while (hasSpecifiers) {\n const first = specifiers[0];\n if (isImportDefaultSpecifier(first) || isImportNamespaceSpecifier(first)) {\n this.print(specifiers.shift());\n if (specifiers.length) {\n this.token(\",\");\n this.space();\n }\n } else {\n break;\n }\n }\n\n if (specifiers.length) {\n this.token(\"{\");\n this.space();\n this.printList(specifiers);\n this.space();\n this.token(\"}\");\n } else if (isTypeKind && !hasSpecifiers) {\n this.token(\"{\");\n this.token(\"}\");\n }\n\n if (hasSpecifiers || isTypeKind) {\n this.space();\n this.word(\"from\");\n this.space();\n }\n\n if (node.attributes?.length || node.assertions?.length) {\n this.print(node.source, true);\n this.space();\n this._printAttributes(node);\n } else {\n this.print(node.source);\n }\n\n this.semicolon();\n}\n\nexport function ImportAttribute(this: Printer, node: t.ImportAttribute) {\n this.print(node.key);\n this.token(\":\");\n this.space();\n this.print(node.value);\n}\n\nexport function ImportNamespaceSpecifier(\n this: Printer,\n node: t.ImportNamespaceSpecifier,\n) {\n this.token(\"*\");\n this.space();\n this.word(\"as\");\n this.space();\n this.print(node.local);\n}\n\nexport function ImportExpression(this: Printer, node: t.ImportExpression) {\n this.word(\"import\");\n if (node.phase) {\n this.token(\".\");\n this.word(node.phase);\n }\n this.token(\"(\");\n this.print(node.source);\n if (node.options != null) {\n this.token(\",\");\n this.space();\n this.print(node.options);\n }\n this.token(\")\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AACA,IAAAA,EAAA,GAAAC,OAAA;AASA,IAAAC,MAAA,GAAAD,OAAA;AAAgD;EAR9CE,kBAAkB;EAClBC,wBAAwB;EACxBC,0BAA0B;EAC1BC,wBAAwB;EACxBC,0BAA0B;EAC1BC;AAAW,IAAAR,EAAA;AAKN,SAASS,eAAeA,CAAgBC,IAAuB,EAAE;EACtE,IAAIA,IAAI,CAACC,UAAU,KAAK,MAAM,IAAID,IAAI,CAACC,UAAU,KAAK,QAAQ,EAAE;IAC9D,IAAI,CA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I,CAACD,IAAI,CAAC,IAAI,CAAC;EACf,IAAI,CAACC,KAAK,CAAC,CAAC;EACZ,IAAI,CAACC,KAAK,CAACJ,IAAI,CAACM,KAAK,CAAC;AACxB;AAEO,SAASwD,gBAAgBA,CAAgB9D,IAAwB,EAAE;EACxE,IAAI,CAACE,IAAI,CAAC,QAAQ,CAAC;EACnB,IAAIF,IAAI,CAACwD,KAAK,EAAE;IACd,IAAI,CAAC1C,SAAK,GAAI,CAAC;IACf,IAAI,CAACZ,IAAI,CAACF,IAAI,CAACwD,KAAK,CAAC;EACvB;EACA,IAAI,CAAC1C,SAAK,GAAI,CAAC;EACf,IAAI,CAACV,KAAK,CAACJ,IAAI,CAAC6B,MAAM,CAAC;EACvB,IAAI7B,IAAI,CAAC+D,OAAO,IAAI,IAAI,EAAE;IACxB,IAAI,CAACjD,SAAK,GAAI,CAAC;IACf,IAAI,CAACX,KAAK,CAAC,CAAC;IACZ,IAAI,CAACC,KAAK,CAACJ,IAAI,CAAC+D,OAAO,CAAC;EAC1B;EACA,IAAI,CAACjD,SAAK,GAAI,CAAC;AACjB","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/statements.js b/node_modules/@babel/generator/lib/generators/statements.js new file mode 100644 index 0000000..0dab117 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/statements.js @@ -0,0 +1,290 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.BreakStatement = BreakStatement; +exports.CatchClause = CatchClause; +exports.ContinueStatement = ContinueStatement; +exports.DebuggerStatement = DebuggerStatement; +exports.DoWhileStatement = DoWhileStatement; +exports.ForOfStatement = exports.ForInStatement = void 0; +exports.ForStatement = ForStatement; +exports.IfStatement = IfStatement; +exports.LabeledStatement = LabeledStatement; +exports.ReturnStatement = ReturnStatement; +exports.SwitchCase = SwitchCase; +exports.SwitchStatement = SwitchStatement; +exports.ThrowStatement = ThrowStatement; +exports.TryStatement = TryStatement; +exports.VariableDeclaration = VariableDeclaration; +exports.VariableDeclarator = VariableDeclarator; +exports.WhileStatement = WhileStatement; +exports.WithStatement = WithStatement; +var _t = require("@babel/types"); +var _index = require("../node/index.js"); +const { + isFor, + isForStatement, + isIfStatement, + isStatement +} = _t; +function WithStatement(node) { + this.word("with"); + this.space(); + this.tokenChar(40); + this.print(node.object); + this.tokenChar(41); + this.printBlock(node); +} +function IfStatement(node) { + this.word("if"); + this.space(); + this.tokenChar(40); + this.print(node.test); + this.tokenChar(41); + this.space(); + const needsBlock = node.alternate && isIfStatement(getLastStatement(node.consequent)); + if (needsBlock) { + this.tokenChar(123); + this.newline(); + this.indent(); + } + this.printAndIndentOnComments(node.consequent); + if (needsBlock) { + this.dedent(); + this.newline(); + this.tokenChar(125); + } + if (node.alternate) { + if (this.endsWith(125)) this.space(); + this.word("else"); + this.space(); + this.printAndIndentOnComments(node.alternate); + } +} +function getLastStatement(statement) { + const { + body + } = statement; + if (isStatement(body) === false) { + return statement; + } + return getLastStatement(body); +} +function ForStatement(node) { + this.word("for"); + this.space(); + this.tokenChar(40); + { + const exit = this.enterForStatementInit(true); + this.tokenContext |= _index.TokenContext.forHead; + this.print(node.init); + exit(); + } + this.tokenChar(59); + if (node.test) { + this.space(); + this.print(node.test); + } + this.tokenChar(59); + if (node.update) { + this.space(); + this.print(node.update); + } + this.tokenChar(41); + this.printBlock(node); +} +function WhileStatement(node) { + this.word("while"); + this.space(); + this.tokenChar(40); + this.print(node.test); + this.tokenChar(41); + this.printBlock(node); +} +function ForXStatement(node) { + this.word("for"); + this.space(); + const isForOf = node.type === "ForOfStatement"; + if (isForOf && node.await) { + this.word("await"); + this.space(); + } + this.noIndentInnerCommentsHere(); + this.tokenChar(40); + { + const exit = isForOf ? null : this.enterForStatementInit(true); + this.tokenContext |= isForOf ? _index.TokenContext.forOfHead : _index.TokenContext.forInHead; + this.print(node.left); + exit == null || exit(); + } + this.space(); + this.word(isForOf ? "of" : "in"); + this.space(); + this.print(node.right); + this.tokenChar(41); + this.printBlock(node); +} +const ForInStatement = exports.ForInStatement = ForXStatement; +const ForOfStatement = exports.ForOfStatement = ForXStatement; +function DoWhileStatement(node) { + this.word("do"); + this.space(); + this.print(node.body); + this.space(); + this.word("while"); + this.space(); + this.tokenChar(40); + this.print(node.test); + this.tokenChar(41); + this.semicolon(); +} +function printStatementAfterKeyword(printer, node, isLabel) { + if (node) { + printer.space(); + printer.printTerminatorless(node, isLabel); + } + printer.semicolon(); +} +function BreakStatement(node) { + this.word("break"); + printStatementAfterKeyword(this, node.label, true); +} +function ContinueStatement(node) { + this.word("continue"); + printStatementAfterKeyword(this, node.label, true); +} +function ReturnStatement(node) { + this.word("return"); + printStatementAfterKeyword(this, node.argument, false); +} +function ThrowStatement(node) { + this.word("throw"); + printStatementAfterKeyword(this, node.argument, false); +} +function LabeledStatement(node) { + this.print(node.label); + this.tokenChar(58); + this.space(); + this.print(node.body); +} +function TryStatement(node) { + this.word("try"); + this.space(); + this.print(node.block); + this.space(); + if (node.handlers) { + this.print(node.handlers[0]); + } else { + this.print(node.handler); + } + if (node.finalizer) { + this.space(); + this.word("finally"); + this.space(); + this.print(node.finalizer); + } +} +function CatchClause(node) { + this.word("catch"); + this.space(); + if (node.param) { + this.tokenChar(40); + this.print(node.param); + this.print(node.param.typeAnnotation); + this.tokenChar(41); + this.space(); + } + this.print(node.body); +} +function SwitchStatement(node) { + this.word("switch"); + this.space(); + this.tokenChar(40); + this.print(node.discriminant); + this.tokenChar(41); + this.space(); + this.tokenChar(123); + this.printSequence(node.cases, { + indent: true, + addNewlines(leading, cas) { + if (!leading && node.cases[node.cases.length - 1] === cas) return -1; + } + }); + this.rightBrace(node); +} +function SwitchCase(node) { + if (node.test) { + this.word("case"); + this.space(); + this.print(node.test); + this.tokenChar(58); + } else { + this.word("default"); + this.tokenChar(58); + } + if (node.consequent.length) { + this.newline(); + this.printSequence(node.consequent, { + indent: true + }); + } +} +function DebuggerStatement() { + this.word("debugger"); + this.semicolon(); +} +function VariableDeclaration(node, parent) { + if (node.declare) { + this.word("declare"); + this.space(); + } + const { + kind + } = node; + if (kind === "await using") { + this.word("await"); + this.space(); + this.word("using", true); + } else { + this.word(kind, kind === "using"); + } + this.space(); + let hasInits = false; + if (!isFor(parent)) { + for (const declar of node.declarations) { + if (declar.init) { + hasInits = true; + } + } + } + this.printList(node.declarations, { + separator: hasInits ? function () { + this.tokenChar(44); + this.newline(); + } : undefined, + indent: node.declarations.length > 1 ? true : false + }); + if (isFor(parent)) { + if (isForStatement(parent)) { + if (parent.init === node) return; + } else { + if (parent.left === node) return; + } + } + this.semicolon(); +} +function VariableDeclarator(node) { + this.print(node.id); + if (node.definite) this.tokenChar(33); + this.print(node.id.typeAnnotation); + if (node.init) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.init); + } +} + +//# sourceMappingURL=statements.js.map diff --git a/node_modules/@babel/generator/lib/generators/statements.js.map b/node_modules/@babel/generator/lib/generators/statements.js.map new file mode 100644 index 0000000..e9518b3 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/statements.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_t","require","_index","isFor","isForStatement","isIfStatement","isStatement","WithStatement","node","word","space","token","print","object","printBlock","IfStatement","test","needsBlock","alternate","getLastStatement","consequent","newline","indent","printAndIndentOnComments","dedent","endsWith","statement","body","ForStatement","exit","enterForStatementInit","tokenContext","TokenContext","forHead","init","update","WhileStatement","ForXStatement","isForOf","type","await","noIndentInnerCommentsHere","forOfHead","forInHead","left","right","ForInStatement","exports","ForOfStatement","DoWhileStatement","semicolon","printStatementAfterKeyword","printer","isLabel","printTerminatorless","BreakStatement","label","ContinueStatement","ReturnStatement","argument","ThrowStatement","LabeledStatement","TryStatement","block","handlers","handler","finalizer","CatchClause","param","typeAnnotation","SwitchStatement","discriminant","printSequence","cases","addNewlines","leading","cas","length","rightBrace","SwitchCase","DebuggerStatement","VariableDeclaration","parent","declare","kind","hasInits","declar","declarations","printList","separator","undefined","VariableDeclarator","id","definite"],"sources":["../../src/generators/statements.ts"],"sourcesContent":["import type Printer from \"../printer.ts\";\nimport {\n isFor,\n isForStatement,\n isIfStatement,\n isStatement,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\n\n// We inline this package\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport * as charCodes from \"charcodes\";\nimport { TokenContext } from \"../node/index.ts\";\n\nexport function WithStatement(this: Printer, node: t.WithStatement) {\n this.word(\"with\");\n this.space();\n this.token(\"(\");\n this.print(node.object);\n this.token(\")\");\n this.printBlock(node);\n}\n\nexport function IfStatement(this: Printer, node: t.IfStatement) {\n this.word(\"if\");\n this.space();\n this.token(\"(\");\n this.print(node.test);\n this.token(\")\");\n this.space();\n\n const needsBlock =\n node.alternate && isIfStatement(getLastStatement(node.consequent));\n if (needsBlock) {\n this.token(\"{\");\n this.newline();\n this.indent();\n }\n\n this.printAndIndentOnComments(node.consequent);\n\n if (needsBlock) {\n this.dedent();\n this.newline();\n this.token(\"}\");\n }\n\n if (node.alternate) {\n if (this.endsWith(charCodes.rightCurlyBrace)) this.space();\n this.word(\"else\");\n this.space();\n this.printAndIndentOnComments(node.alternate);\n }\n}\n\n// Recursively get the last statement.\nfunction getLastStatement(statement: t.Statement): t.Statement {\n // @ts-expect-error: If statement.body is empty or not a Node, isStatement will return false\n const { body } = statement;\n if (isStatement(body) === false) {\n return statement;\n }\n\n return getLastStatement(body);\n}\n\nexport function ForStatement(this: Printer, node: t.ForStatement) {\n this.word(\"for\");\n this.space();\n this.token(\"(\");\n\n {\n const exit = this.enterForStatementInit(true);\n this.tokenContext |= TokenContext.forHead;\n this.print(node.init);\n exit();\n }\n\n this.token(\";\");\n\n if (node.test) {\n this.space();\n this.print(node.test);\n }\n this.token(\";\");\n\n if (node.update) {\n this.space();\n this.print(node.update);\n }\n\n this.token(\")\");\n this.printBlock(node);\n}\n\nexport function WhileStatement(this: Printer, node: t.WhileStatement) {\n this.word(\"while\");\n this.space();\n this.token(\"(\");\n this.print(node.test);\n this.token(\")\");\n this.printBlock(node);\n}\n\nfunction ForXStatement(this: Printer, node: t.ForXStatement) {\n this.word(\"for\");\n this.space();\n const isForOf = node.type === \"ForOfStatement\";\n if (isForOf && node.await) {\n this.word(\"await\");\n this.space();\n }\n this.noIndentInnerCommentsHere();\n this.token(\"(\");\n {\n const exit = isForOf ? null : this.enterForStatementInit(true);\n this.tokenContext |= isForOf\n ? TokenContext.forOfHead\n : TokenContext.forInHead;\n this.print(node.left);\n exit?.();\n }\n this.space();\n this.word(isForOf ? \"of\" : \"in\");\n this.space();\n this.print(node.right);\n this.token(\")\");\n this.printBlock(node);\n}\n\nexport const ForInStatement = ForXStatement;\nexport const ForOfStatement = ForXStatement;\n\nexport function DoWhileStatement(this: Printer, node: t.DoWhileStatement) {\n this.word(\"do\");\n this.space();\n this.print(node.body);\n this.space();\n this.word(\"while\");\n this.space();\n this.token(\"(\");\n this.print(node.test);\n this.token(\")\");\n this.semicolon();\n}\n\nfunction printStatementAfterKeyword(\n printer: Printer,\n node: t.Node,\n isLabel: boolean,\n) {\n if (node) {\n printer.space();\n printer.printTerminatorless(node, isLabel);\n }\n\n printer.semicolon();\n}\n\nexport function BreakStatement(this: Printer, node: t.ContinueStatement) {\n this.word(\"break\");\n printStatementAfterKeyword(this, node.label, true);\n}\n\nexport function ContinueStatement(this: Printer, node: t.ContinueStatement) {\n this.word(\"continue\");\n printStatementAfterKeyword(this, node.label, true);\n}\n\nexport function ReturnStatement(this: Printer, node: t.ReturnStatement) {\n this.word(\"return\");\n printStatementAfterKeyword(this, node.argument, false);\n}\n\nexport function ThrowStatement(this: Printer, node: t.ThrowStatement) {\n this.word(\"throw\");\n printStatementAfterKeyword(this, node.argument, false);\n}\n\nexport function LabeledStatement(this: Printer, node: t.LabeledStatement) {\n this.print(node.label);\n this.token(\":\");\n this.space();\n this.print(node.body);\n}\n\nexport function TryStatement(this: Printer, node: t.TryStatement) {\n this.word(\"try\");\n this.space();\n this.print(node.block);\n this.space();\n\n // Esprima bug puts the catch clause in a `handlers` array.\n // see https://code.google.com/p/esprima/issues/detail?id=433\n // We run into this from regenerator generated ast.\n // @ts-expect-error todo(flow->ts) should ast node type be updated to support this?\n if (node.handlers) {\n // @ts-expect-error todo(flow->ts) should ast node type be updated to support this?\n this.print(node.handlers[0]);\n } else {\n this.print(node.handler);\n }\n\n if (node.finalizer) {\n this.space();\n this.word(\"finally\");\n this.space();\n this.print(node.finalizer);\n }\n}\n\nexport function CatchClause(this: Printer, node: t.CatchClause) {\n this.word(\"catch\");\n this.space();\n if (node.param) {\n this.token(\"(\");\n this.print(node.param);\n this.print(node.param.typeAnnotation);\n this.token(\")\");\n this.space();\n }\n this.print(node.body);\n}\n\nexport function SwitchStatement(this: Printer, node: t.SwitchStatement) {\n this.word(\"switch\");\n this.space();\n this.token(\"(\");\n this.print(node.discriminant);\n this.token(\")\");\n this.space();\n this.token(\"{\");\n\n this.printSequence(node.cases, {\n indent: true,\n addNewlines(leading, cas) {\n if (!leading && node.cases[node.cases.length - 1] === cas) return -1;\n },\n });\n\n this.rightBrace(node);\n}\n\nexport function SwitchCase(this: Printer, node: t.SwitchCase) {\n if (node.test) {\n this.word(\"case\");\n this.space();\n this.print(node.test);\n this.token(\":\");\n } else {\n this.word(\"default\");\n this.token(\":\");\n }\n\n if (node.consequent.length) {\n this.newline();\n this.printSequence(node.consequent, { indent: true });\n }\n}\n\nexport function DebuggerStatement(this: Printer) {\n this.word(\"debugger\");\n this.semicolon();\n}\n\nexport function VariableDeclaration(\n this: Printer,\n node: t.VariableDeclaration,\n parent: t.Node,\n) {\n if (node.declare) {\n // TS\n this.word(\"declare\");\n this.space();\n }\n\n const { kind } = node;\n if (kind === \"await using\") {\n this.word(\"await\");\n this.space();\n this.word(\"using\", true);\n } else {\n this.word(kind, kind === \"using\");\n }\n this.space();\n\n let hasInits = false;\n // don't add whitespace to loop heads\n if (!isFor(parent)) {\n for (const declar of node.declarations) {\n if (declar.init) {\n // has an init so let's split it up over multiple lines\n hasInits = true;\n }\n }\n }\n\n //\n // use a pretty separator when we aren't in compact mode, have initializers and don't have retainLines on\n // this will format declarations like:\n //\n // let foo = \"bar\", bar = \"foo\";\n //\n // into\n //\n // let foo = \"bar\",\n // bar = \"foo\";\n //\n\n this.printList(node.declarations, {\n separator: hasInits\n ? function (this: Printer) {\n this.token(\",\");\n this.newline();\n }\n : undefined,\n indent: node.declarations.length > 1 ? true : false,\n });\n\n if (isFor(parent)) {\n // don't give semicolons to these nodes since they'll be inserted in the parent generator\n if (isForStatement(parent)) {\n if (parent.init === node) return;\n } else {\n if (parent.left === node) return;\n }\n }\n\n this.semicolon();\n}\n\nexport function VariableDeclarator(this: Printer, node: t.VariableDeclarator) {\n this.print(node.id);\n if (node.definite) this.token(\"!\"); // TS\n // @ts-expect-error todo(flow-ts) Property 'typeAnnotation' does not exist on type 'MemberExpression'.\n this.print(node.id.typeAnnotation);\n if (node.init) {\n this.space();\n this.token(\"=\");\n this.space();\n this.print(node.init);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AACA,IAAAA,EAAA,GAAAC,OAAA;AAWA,IAAAC,MAAA,GAAAD,OAAA;AAAgD;EAV9CE,KAAK;EACLC,cAAc;EACdC,aAAa;EACbC;AAAW,IAAAN,EAAA;AASN,SAASO,aAAaA,CAAgBC,IAAqB,EAAE;EAClE,IAAI,CAACC,IAAI,CAAC,MAAM,CAAC;EACjB,IAAI,CAACC,KAAK,CAAC,CAAC;EACZ,IAAI,CAACC,SAAK,GAAI,CAAC;EACf,IAAI,CAACC,KAAK,CAACJ,IAAI,CAACK,MAAM,CAAC;EACvB,IAAI,CAACF,SAAK,GAAI,CAAC;EACf,IAAI,CAACG,UAAU,CAACN,IAAI,CAAC;AACvB;AAEO,SAASO,WAAWA,CAAgBP,IAAmB,EAAE;EAC9D,IAAI,CAACC,IAAI,CAAC,IAAI,CAAC;EACf,IAAI,CAACC,KAAK,CAAC,CAAC;EACZ,IAAI,CAACC,SAAK,GAAI,CAAC;EACf,IAAI,CAACC,KAA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AC,CAAC;AAClB;AAEO,SAASyC,kBAAkBA,CAAgBnF,IAA0B,EAAE;EAC5E,IAAI,CAACI,KAAK,CAACJ,IAAI,CAACoF,EAAE,CAAC;EACnB,IAAIpF,IAAI,CAACqF,QAAQ,EAAE,IAAI,CAAClF,SAAK,GAAI,CAAC;EAElC,IAAI,CAACC,KAAK,CAACJ,IAAI,CAACoF,EAAE,CAACvB,cAAc,CAAC;EAClC,IAAI7D,IAAI,CAAC0B,IAAI,EAAE;IACb,IAAI,CAACxB,KAAK,CAAC,CAAC;IACZ,IAAI,CAACC,SAAK,GAAI,CAAC;IACf,IAAI,CAACD,KAAK,CAAC,CAAC;IACZ,IAAI,CAACE,KAAK,CAACJ,IAAI,CAAC0B,IAAI,CAAC;EACvB;AACF","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/template-literals.js b/node_modules/@babel/generator/lib/generators/template-literals.js new file mode 100644 index 0000000..a975057 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/template-literals.js @@ -0,0 +1,31 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TaggedTemplateExpression = TaggedTemplateExpression; +exports.TemplateElement = TemplateElement; +exports.TemplateLiteral = TemplateLiteral; +function TaggedTemplateExpression(node) { + this.print(node.tag); + this.print(node.typeParameters); + this.print(node.quasi); +} +function TemplateElement() { + throw new Error("TemplateElement printing is handled in TemplateLiteral"); +} +function TemplateLiteral(node) { + const quasis = node.quasis; + let partRaw = "`"; + for (let i = 0; i < quasis.length; i++) { + partRaw += quasis[i].value.raw; + if (i + 1 < quasis.length) { + this.token(partRaw + "${", true); + this.print(node.expressions[i]); + partRaw = "}"; + } + } + this.token(partRaw + "`", true); +} + +//# sourceMappingURL=template-literals.js.map diff --git a/node_modules/@babel/generator/lib/generators/template-literals.js.map b/node_modules/@babel/generator/lib/generators/template-literals.js.map new file mode 100644 index 0000000..bbda4fd --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/template-literals.js.map @@ -0,0 +1 @@ +{"version":3,"names":["TaggedTemplateExpression","node","print","tag","typeParameters","quasi","TemplateElement","Error","TemplateLiteral","quasis","partRaw","i","length","value","raw","token","expressions"],"sources":["../../src/generators/template-literals.ts"],"sourcesContent":["import type Printer from \"../printer.ts\";\nimport type * as t from \"@babel/types\";\n\nexport function TaggedTemplateExpression(\n this: Printer,\n node: t.TaggedTemplateExpression,\n) {\n this.print(node.tag);\n this.print(node.typeParameters); // TS\n this.print(node.quasi);\n}\n\nexport function TemplateElement(this: Printer) {\n throw new Error(\"TemplateElement printing is handled in TemplateLiteral\");\n}\n\nexport function TemplateLiteral(this: Printer, node: t.TemplateLiteral) {\n const quasis = node.quasis;\n\n let partRaw = \"`\";\n\n for (let i = 0; i < quasis.length; i++) {\n partRaw += quasis[i].value.raw;\n\n if (i + 1 < quasis.length) {\n this.token(partRaw + \"${\", true);\n this.print(node.expressions[i]);\n partRaw = \"}\";\n }\n }\n\n this.token(partRaw + \"`\", true);\n}\n"],"mappings":";;;;;;;;AAGO,SAASA,wBAAwBA,CAEtCC,IAAgC,EAChC;EACA,IAAI,CAACC,KAAK,CAACD,IAAI,CAACE,GAAG,CAAC;EACpB,IAAI,CAACD,KAAK,CAACD,IAAI,CAACG,cAAc,CAAC;EAC/B,IAAI,CAACF,KAAK,CAACD,IAAI,CAACI,KAAK,CAAC;AACxB;AAEO,SAASC,eAAeA,CAAA,EAAgB;EAC7C,MAAM,IAAIC,KAAK,CAAC,wDAAwD,CAAC;AAC3E;AAEO,SAASC,eAAeA,CAAgBP,IAAuB,EAAE;EACtE,MAAMQ,MAAM,GAAGR,IAAI,CAACQ,MAAM;EAE1B,IAAIC,OAAO,GAAG,GAAG;EAEjB,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGF,MAAM,CAACG,MAAM,EAAED,CAAC,EAAE,EAAE;IACtCD,OAAO,IAAID,MAAM,CAACE,CAAC,CAAC,CAACE,KAAK,CAACC,GAAG;IAE9B,IAAIH,CAAC,GAAG,CAAC,GAAGF,MAAM,CAACG,MAAM,EAAE;MACzB,IAAI,CAACG,KAAK,CAACL,OAAO,GAAG,IAAI,EAAE,IAAI,CAAC;MAChC,IAAI,CAACR,KAAK,CAACD,IAAI,CAACe,WAAW,CAACL,CAAC,CAAC,CAAC;MAC/BD,OAAO,GAAG,GAAG;IACf;EACF;EAEA,IAAI,CAACK,KAAK,CAACL,OAAO,GAAG,GAAG,EAAE,IAAI,CAAC;AACjC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/types.js b/node_modules/@babel/generator/lib/generators/types.js new file mode 100644 index 0000000..dce19a4 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/types.js @@ -0,0 +1,229 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ArgumentPlaceholder = ArgumentPlaceholder; +exports.ArrayPattern = exports.ArrayExpression = ArrayExpression; +exports.BigIntLiteral = BigIntLiteral; +exports.BooleanLiteral = BooleanLiteral; +exports.DecimalLiteral = DecimalLiteral; +exports.Identifier = Identifier; +exports.NullLiteral = NullLiteral; +exports.NumericLiteral = NumericLiteral; +exports.ObjectPattern = exports.ObjectExpression = ObjectExpression; +exports.ObjectMethod = ObjectMethod; +exports.ObjectProperty = ObjectProperty; +exports.PipelineBareFunction = PipelineBareFunction; +exports.PipelinePrimaryTopicReference = PipelinePrimaryTopicReference; +exports.PipelineTopicExpression = PipelineTopicExpression; +exports.RecordExpression = RecordExpression; +exports.RegExpLiteral = RegExpLiteral; +exports.SpreadElement = exports.RestElement = RestElement; +exports.StringLiteral = StringLiteral; +exports.TopicReference = TopicReference; +exports.TupleExpression = TupleExpression; +var _t = require("@babel/types"); +var _jsesc = require("jsesc"); +const { + isAssignmentPattern, + isIdentifier +} = _t; +function Identifier(node) { + var _node$loc; + this.sourceIdentifierName(((_node$loc = node.loc) == null ? void 0 : _node$loc.identifierName) || node.name); + this.word(node.name); +} +function ArgumentPlaceholder() { + this.tokenChar(63); +} +function RestElement(node) { + this.token("..."); + this.print(node.argument); +} +function ObjectExpression(node) { + const props = node.properties; + this.tokenChar(123); + if (props.length) { + const exit = this.enterForStatementInit(false); + this.space(); + this.printList(props, { + indent: true, + statement: true + }); + this.space(); + exit(); + } + this.sourceWithOffset("end", node.loc, -1); + this.tokenChar(125); +} +function ObjectMethod(node) { + this.printJoin(node.decorators); + this._methodHead(node); + this.space(); + this.print(node.body); +} +function ObjectProperty(node) { + this.printJoin(node.decorators); + if (node.computed) { + this.tokenChar(91); + this.print(node.key); + this.tokenChar(93); + } else { + if (isAssignmentPattern(node.value) && isIdentifier(node.key) && node.key.name === node.value.left.name) { + this.print(node.value); + return; + } + this.print(node.key); + if (node.shorthand && isIdentifier(node.key) && isIdentifier(node.value) && node.key.name === node.value.name) { + return; + } + } + this.tokenChar(58); + this.space(); + this.print(node.value); +} +function ArrayExpression(node) { + const elems = node.elements; + const len = elems.length; + this.tokenChar(91); + const exit = this.enterForStatementInit(false); + for (let i = 0; i < elems.length; i++) { + const elem = elems[i]; + if (elem) { + if (i > 0) this.space(); + this.print(elem); + if (i < len - 1) this.tokenChar(44); + } else { + this.tokenChar(44); + } + } + exit(); + this.tokenChar(93); +} +function RecordExpression(node) { + const props = node.properties; + let startToken; + let endToken; + { + if (this.format.recordAndTupleSyntaxType === "bar") { + startToken = "{|"; + endToken = "|}"; + } else if (this.format.recordAndTupleSyntaxType !== "hash" && this.format.recordAndTupleSyntaxType != null) { + throw new Error(`The "recordAndTupleSyntaxType" generator option must be "bar" or "hash" (${JSON.stringify(this.format.recordAndTupleSyntaxType)} received).`); + } else { + startToken = "#{"; + endToken = "}"; + } + } + this.token(startToken); + if (props.length) { + this.space(); + this.printList(props, { + indent: true, + statement: true + }); + this.space(); + } + this.token(endToken); +} +function TupleExpression(node) { + const elems = node.elements; + const len = elems.length; + let startToken; + let endToken; + { + if (this.format.recordAndTupleSyntaxType === "bar") { + startToken = "[|"; + endToken = "|]"; + } else if (this.format.recordAndTupleSyntaxType === "hash") { + startToken = "#["; + endToken = "]"; + } else { + throw new Error(`${this.format.recordAndTupleSyntaxType} is not a valid recordAndTuple syntax type`); + } + } + this.token(startToken); + for (let i = 0; i < elems.length; i++) { + const elem = elems[i]; + if (elem) { + if (i > 0) this.space(); + this.print(elem); + if (i < len - 1) this.tokenChar(44); + } + } + this.token(endToken); +} +function RegExpLiteral(node) { + this.word(`/${node.pattern}/${node.flags}`); +} +function BooleanLiteral(node) { + this.word(node.value ? "true" : "false"); +} +function NullLiteral() { + this.word("null"); +} +function NumericLiteral(node) { + const raw = this.getPossibleRaw(node); + const opts = this.format.jsescOption; + const value = node.value; + const str = value + ""; + if (opts.numbers) { + this.number(_jsesc(value, opts), value); + } else if (raw == null) { + this.number(str, value); + } else if (this.format.minified) { + this.number(raw.length < str.length ? raw : str, value); + } else { + this.number(raw, value); + } +} +function StringLiteral(node) { + const raw = this.getPossibleRaw(node); + if (!this.format.minified && raw !== undefined) { + this.token(raw); + return; + } + const val = _jsesc(node.value, this.format.jsescOption); + this.token(val); +} +function BigIntLiteral(node) { + const raw = this.getPossibleRaw(node); + if (!this.format.minified && raw !== undefined) { + this.word(raw); + return; + } + this.word(node.value + "n"); +} +function DecimalLiteral(node) { + const raw = this.getPossibleRaw(node); + if (!this.format.minified && raw !== undefined) { + this.word(raw); + return; + } + this.word(node.value + "m"); +} +const validTopicTokenSet = new Set(["^^", "@@", "^", "%", "#"]); +function TopicReference() { + const { + topicToken + } = this.format; + if (validTopicTokenSet.has(topicToken)) { + this.token(topicToken); + } else { + const givenTopicTokenJSON = JSON.stringify(topicToken); + const validTopics = Array.from(validTopicTokenSet, v => JSON.stringify(v)); + throw new Error(`The "topicToken" generator option must be one of ` + `${validTopics.join(", ")} (${givenTopicTokenJSON} received instead).`); + } +} +function PipelineTopicExpression(node) { + this.print(node.expression); +} +function PipelineBareFunction(node) { + this.print(node.callee); +} +function PipelinePrimaryTopicReference() { + this.tokenChar(35); +} + +//# sourceMappingURL=types.js.map diff --git a/node_modules/@babel/generator/lib/generators/types.js.map b/node_modules/@babel/generator/lib/generators/types.js.map new file mode 100644 index 0000000..523c9ef --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/types.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_t","require","_jsesc","isAssignmentPattern","isIdentifier","Identifier","node","_node$loc","sourceIdentifierName","loc","identifierName","name","word","ArgumentPlaceholder","token","RestElement","print","argument","ObjectExpression","props","properties","length","exit","enterForStatementInit","space","printList","indent","statement","sourceWithOffset","ObjectMethod","printJoin","decorators","_methodHead","body","ObjectProperty","computed","key","value","left","shorthand","ArrayExpression","elems","elements","len","i","elem","RecordExpression","startToken","endToken","format","recordAndTupleSyntaxType","Error","JSON","stringify","TupleExpression","RegExpLiteral","pattern","flags","BooleanLiteral","NullLiteral","NumericLiteral","raw","getPossibleRaw","opts","jsescOption","str","numbers","number","jsesc","minified","StringLiteral","undefined","val","BigIntLiteral","DecimalLiteral","validTopicTokenSet","Set","TopicReference","topicToken","has","givenTopicTokenJSON","validTopics","Array","from","v","join","PipelineTopicExpression","expression","PipelineBareFunction","callee","PipelinePrimaryTopicReference"],"sources":["../../src/generators/types.ts"],"sourcesContent":["import type Printer from \"../printer.ts\";\nimport { isAssignmentPattern, isIdentifier } from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport jsesc from \"jsesc\";\n\nexport function Identifier(this: Printer, node: t.Identifier) {\n this.sourceIdentifierName(node.loc?.identifierName || node.name);\n this.word(node.name);\n}\n\nexport function ArgumentPlaceholder(this: Printer) {\n this.token(\"?\");\n}\n\nexport function RestElement(this: Printer, node: t.RestElement) {\n this.token(\"...\");\n this.print(node.argument);\n}\n\nexport { RestElement as SpreadElement };\n\nexport function ObjectExpression(this: Printer, node: t.ObjectExpression) {\n const props = node.properties;\n\n this.token(\"{\");\n\n if (props.length) {\n const exit = this.enterForStatementInit(false);\n this.space();\n this.printList(props, { indent: true, statement: true });\n this.space();\n exit();\n }\n\n this.sourceWithOffset(\"end\", node.loc, -1);\n\n this.token(\"}\");\n}\n\nexport { ObjectExpression as ObjectPattern };\n\nexport function ObjectMethod(this: Printer, node: t.ObjectMethod) {\n this.printJoin(node.decorators);\n this._methodHead(node);\n this.space();\n this.print(node.body);\n}\n\nexport function ObjectProperty(this: Printer, node: t.ObjectProperty) {\n this.printJoin(node.decorators);\n\n if (node.computed) {\n this.token(\"[\");\n this.print(node.key);\n this.token(\"]\");\n } else {\n // print `({ foo: foo = 5 } = {})` as `({ foo = 5 } = {});`\n if (\n isAssignmentPattern(node.value) &&\n isIdentifier(node.key) &&\n // @ts-expect-error todo(flow->ts) `.name` does not exist on some types in union\n node.key.name === node.value.left.name\n ) {\n this.print(node.value);\n return;\n }\n\n this.print(node.key);\n\n // shorthand!\n if (\n node.shorthand &&\n isIdentifier(node.key) &&\n isIdentifier(node.value) &&\n node.key.name === node.value.name\n ) {\n return;\n }\n }\n\n this.token(\":\");\n this.space();\n this.print(node.value);\n}\n\nexport function ArrayExpression(this: Printer, node: t.ArrayExpression) {\n const elems = node.elements;\n const len = elems.length;\n\n this.token(\"[\");\n\n const exit = this.enterForStatementInit(false);\n\n for (let i = 0; i < elems.length; i++) {\n const elem = elems[i];\n if (elem) {\n if (i > 0) this.space();\n this.print(elem);\n if (i < len - 1) this.token(\",\");\n } else {\n // If the array expression ends with a hole, that hole\n // will be ignored by the interpreter, but if it ends with\n // two (or more) holes, we need to write out two (or more)\n // commas so that the resulting code is interpreted with\n // both (all) of the holes.\n this.token(\",\");\n }\n }\n\n exit();\n\n this.token(\"]\");\n}\n\nexport { ArrayExpression as ArrayPattern };\n\nexport function RecordExpression(this: Printer, node: t.RecordExpression) {\n const props = node.properties;\n\n let startToken;\n let endToken;\n if (process.env.BABEL_8_BREAKING) {\n startToken = \"#{\";\n endToken = \"}\";\n } else {\n if (this.format.recordAndTupleSyntaxType === \"bar\") {\n startToken = \"{|\";\n endToken = \"|}\";\n } else if (\n this.format.recordAndTupleSyntaxType !== \"hash\" &&\n this.format.recordAndTupleSyntaxType != null\n ) {\n throw new Error(\n `The \"recordAndTupleSyntaxType\" generator option must be \"bar\" or \"hash\" (${JSON.stringify(\n this.format.recordAndTupleSyntaxType,\n )} received).`,\n );\n } else {\n startToken = \"#{\";\n endToken = \"}\";\n }\n }\n\n this.token(startToken);\n\n if (props.length) {\n this.space();\n this.printList(props, { indent: true, statement: true });\n this.space();\n }\n this.token(endToken);\n}\n\nexport function TupleExpression(this: Printer, node: t.TupleExpression) {\n const elems = node.elements;\n const len = elems.length;\n\n let startToken;\n let endToken;\n if (process.env.BABEL_8_BREAKING) {\n startToken = \"#[\";\n endToken = \"]\";\n } else {\n if (this.format.recordAndTupleSyntaxType === \"bar\") {\n startToken = \"[|\";\n endToken = \"|]\";\n } else if (this.format.recordAndTupleSyntaxType === \"hash\") {\n startToken = \"#[\";\n endToken = \"]\";\n } else {\n throw new Error(\n `${this.format.recordAndTupleSyntaxType} is not a valid recordAndTuple syntax type`,\n );\n }\n }\n\n this.token(startToken);\n\n for (let i = 0; i < elems.length; i++) {\n const elem = elems[i];\n if (elem) {\n if (i > 0) this.space();\n this.print(elem);\n if (i < len - 1) this.token(\",\");\n }\n }\n\n this.token(endToken);\n}\n\nexport function RegExpLiteral(this: Printer, node: t.RegExpLiteral) {\n this.word(`/${node.pattern}/${node.flags}`);\n}\n\nexport function BooleanLiteral(this: Printer, node: t.BooleanLiteral) {\n this.word(node.value ? \"true\" : \"false\");\n}\n\nexport function NullLiteral(this: Printer) {\n this.word(\"null\");\n}\n\nexport function NumericLiteral(this: Printer, node: t.NumericLiteral) {\n const raw = this.getPossibleRaw(node);\n const opts = this.format.jsescOption;\n const value = node.value;\n const str = value + \"\";\n if (opts.numbers) {\n this.number(jsesc(value, opts), value);\n } else if (raw == null) {\n this.number(str, value); // normalize\n } else if (this.format.minified) {\n this.number(raw.length < str.length ? raw : str, value);\n } else {\n this.number(raw, value);\n }\n}\n\nexport function StringLiteral(this: Printer, node: t.StringLiteral) {\n const raw = this.getPossibleRaw(node);\n if (!this.format.minified && raw !== undefined) {\n this.token(raw);\n return;\n }\n\n const val = jsesc(node.value, this.format.jsescOption);\n\n this.token(val);\n}\n\nexport function BigIntLiteral(this: Printer, node: t.BigIntLiteral) {\n const raw = this.getPossibleRaw(node);\n if (!this.format.minified && raw !== undefined) {\n this.word(raw);\n return;\n }\n this.word(node.value + \"n\");\n}\n\nexport function DecimalLiteral(this: Printer, node: t.DecimalLiteral) {\n const raw = this.getPossibleRaw(node);\n if (!this.format.minified && raw !== undefined) {\n this.word(raw);\n return;\n }\n this.word(node.value + \"m\");\n}\n\n// Hack pipe operator\nconst validTopicTokenSet = new Set([\"^^\", \"@@\", \"^\", \"%\", \"#\"]);\nexport function TopicReference(this: Printer) {\n const { topicToken } = this.format;\n\n if (validTopicTokenSet.has(topicToken)) {\n this.token(topicToken);\n } else {\n const givenTopicTokenJSON = JSON.stringify(topicToken);\n const validTopics = Array.from(validTopicTokenSet, v => JSON.stringify(v));\n throw new Error(\n `The \"topicToken\" generator option must be one of ` +\n `${validTopics.join(\", \")} (${givenTopicTokenJSON} received instead).`,\n );\n }\n}\n\n// Smart-mix pipe operator\nexport function PipelineTopicExpression(\n this: Printer,\n node: t.PipelineTopicExpression,\n) {\n this.print(node.expression);\n}\n\nexport function PipelineBareFunction(\n this: Printer,\n node: t.PipelineBareFunction,\n) {\n this.print(node.callee);\n}\n\nexport function PipelinePrimaryTopicReference(this: Printer) {\n this.token(\"#\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AACA,IAAAA,EAAA,GAAAC,OAAA;AAEA,IAAAC,MAAA,GAAAD,OAAA;AAA0B;EAFjBE,mBAAmB;EAAEC;AAAY,IAAAJ,EAAA;AAInC,SAASK,UAAUA,CAAgBC,IAAkB,EAAE;EAAA,IAAAC,SAAA;EAC5D,IAAI,CAACC,oBAAoB,CAAC,EAAAD,SAAA,GAAAD,IAAI,CAACG,GAAG,qBAARF,SAAA,CAAUG,cAAc,KAAI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B,EAAES,CAAC,IAAIhC,IAAI,CAACC,SAAS,CAAC+B,CAAC,CAAC,CAAC;IAC1E,MAAM,IAAIjC,KAAK,CACb,mDAAmD,GACjD,GAAG8B,WAAW,CAACI,IAAI,CAAC,IAAI,CAAC,KAAKL,mBAAmB,qBACrD,CAAC;EACH;AACF;AAGO,SAASM,uBAAuBA,CAErChF,IAA+B,EAC/B;EACA,IAAI,CAACU,KAAK,CAACV,IAAI,CAACiF,UAAU,CAAC;AAC7B;AAEO,SAASC,oBAAoBA,CAElClF,IAA4B,EAC5B;EACA,IAAI,CAACU,KAAK,CAACV,IAAI,CAACmF,MAAM,CAAC;AACzB;AAEO,SAASC,6BAA6BA,CAAA,EAAgB;EAC3D,IAAI,CAAC5E,SAAK,GAAI,CAAC;AACjB","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/typescript.js b/node_modules/@babel/generator/lib/generators/typescript.js new file mode 100644 index 0000000..499da0c --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/typescript.js @@ -0,0 +1,695 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TSAnyKeyword = TSAnyKeyword; +exports.TSArrayType = TSArrayType; +exports.TSSatisfiesExpression = exports.TSAsExpression = TSTypeExpression; +exports.TSBigIntKeyword = TSBigIntKeyword; +exports.TSBooleanKeyword = TSBooleanKeyword; +exports.TSCallSignatureDeclaration = TSCallSignatureDeclaration; +exports.TSConditionalType = TSConditionalType; +exports.TSConstructSignatureDeclaration = TSConstructSignatureDeclaration; +exports.TSConstructorType = TSConstructorType; +exports.TSDeclareFunction = TSDeclareFunction; +exports.TSDeclareMethod = TSDeclareMethod; +exports.TSEnumDeclaration = TSEnumDeclaration; +exports.TSEnumMember = TSEnumMember; +exports.TSExportAssignment = TSExportAssignment; +exports.TSExpressionWithTypeArguments = TSExpressionWithTypeArguments; +exports.TSExternalModuleReference = TSExternalModuleReference; +exports.TSFunctionType = TSFunctionType; +exports.TSImportEqualsDeclaration = TSImportEqualsDeclaration; +exports.TSImportType = TSImportType; +exports.TSIndexSignature = TSIndexSignature; +exports.TSIndexedAccessType = TSIndexedAccessType; +exports.TSInferType = TSInferType; +exports.TSInstantiationExpression = TSInstantiationExpression; +exports.TSInterfaceBody = TSInterfaceBody; +exports.TSInterfaceDeclaration = TSInterfaceDeclaration; +exports.TSIntersectionType = TSIntersectionType; +exports.TSIntrinsicKeyword = TSIntrinsicKeyword; +exports.TSLiteralType = TSLiteralType; +exports.TSMappedType = TSMappedType; +exports.TSMethodSignature = TSMethodSignature; +exports.TSModuleBlock = TSModuleBlock; +exports.TSModuleDeclaration = TSModuleDeclaration; +exports.TSNamedTupleMember = TSNamedTupleMember; +exports.TSNamespaceExportDeclaration = TSNamespaceExportDeclaration; +exports.TSNeverKeyword = TSNeverKeyword; +exports.TSNonNullExpression = TSNonNullExpression; +exports.TSNullKeyword = TSNullKeyword; +exports.TSNumberKeyword = TSNumberKeyword; +exports.TSObjectKeyword = TSObjectKeyword; +exports.TSOptionalType = TSOptionalType; +exports.TSParameterProperty = TSParameterProperty; +exports.TSParenthesizedType = TSParenthesizedType; +exports.TSPropertySignature = TSPropertySignature; +exports.TSQualifiedName = TSQualifiedName; +exports.TSRestType = TSRestType; +exports.TSStringKeyword = TSStringKeyword; +exports.TSSymbolKeyword = TSSymbolKeyword; +exports.TSThisType = TSThisType; +exports.TSTupleType = TSTupleType; +exports.TSTypeAliasDeclaration = TSTypeAliasDeclaration; +exports.TSTypeAnnotation = TSTypeAnnotation; +exports.TSTypeAssertion = TSTypeAssertion; +exports.TSTypeLiteral = TSTypeLiteral; +exports.TSTypeOperator = TSTypeOperator; +exports.TSTypeParameter = TSTypeParameter; +exports.TSTypeParameterDeclaration = exports.TSTypeParameterInstantiation = TSTypeParameterInstantiation; +exports.TSTypePredicate = TSTypePredicate; +exports.TSTypeQuery = TSTypeQuery; +exports.TSTypeReference = TSTypeReference; +exports.TSUndefinedKeyword = TSUndefinedKeyword; +exports.TSUnionType = TSUnionType; +exports.TSUnknownKeyword = TSUnknownKeyword; +exports.TSVoidKeyword = TSVoidKeyword; +exports.tsPrintClassMemberModifiers = tsPrintClassMemberModifiers; +exports.tsPrintFunctionOrConstructorType = tsPrintFunctionOrConstructorType; +exports.tsPrintPropertyOrMethodName = tsPrintPropertyOrMethodName; +exports.tsPrintSignatureDeclarationBase = tsPrintSignatureDeclarationBase; +exports.tsPrintTypeLiteralOrInterfaceBody = tsPrintTypeLiteralOrInterfaceBody; +function TSTypeAnnotation(node) { + this.tokenChar(58); + this.space(); + if (node.optional) this.tokenChar(63); + this.print(node.typeAnnotation); +} +function TSTypeParameterInstantiation(node, parent) { + this.tokenChar(60); + this.printList(node.params, {}); + if (parent.type === "ArrowFunctionExpression" && node.params.length === 1) { + this.tokenChar(44); + } + this.tokenChar(62); +} +function TSTypeParameter(node) { + if (node.in) { + this.word("in"); + this.space(); + } + if (node.out) { + this.word("out"); + this.space(); + } + this.word(node.name); + if (node.constraint) { + this.space(); + this.word("extends"); + this.space(); + this.print(node.constraint); + } + if (node.default) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.default); + } +} +function TSParameterProperty(node) { + if (node.accessibility) { + this.word(node.accessibility); + this.space(); + } + if (node.readonly) { + this.word("readonly"); + this.space(); + } + this._param(node.parameter); +} +function TSDeclareFunction(node, parent) { + if (node.declare) { + this.word("declare"); + this.space(); + } + this._functionHead(node, parent); + this.semicolon(); +} +function TSDeclareMethod(node) { + this._classMethodHead(node); + this.semicolon(); +} +function TSQualifiedName(node) { + this.print(node.left); + this.tokenChar(46); + this.print(node.right); +} +function TSCallSignatureDeclaration(node) { + this.tsPrintSignatureDeclarationBase(node); + this.semicolon(); +} +function TSConstructSignatureDeclaration(node) { + this.word("new"); + this.space(); + this.tsPrintSignatureDeclarationBase(node); + this.semicolon(); +} +function TSPropertySignature(node) { + const { + readonly + } = node; + if (readonly) { + this.word("readonly"); + this.space(); + } + this.tsPrintPropertyOrMethodName(node); + this.print(node.typeAnnotation); + this.semicolon(); +} +function tsPrintPropertyOrMethodName(node) { + if (node.computed) { + this.tokenChar(91); + } + this.print(node.key); + if (node.computed) { + this.tokenChar(93); + } + if (node.optional) { + this.tokenChar(63); + } +} +function TSMethodSignature(node) { + const { + kind + } = node; + if (kind === "set" || kind === "get") { + this.word(kind); + this.space(); + } + this.tsPrintPropertyOrMethodName(node); + this.tsPrintSignatureDeclarationBase(node); + this.semicolon(); +} +function TSIndexSignature(node) { + const { + readonly, + static: isStatic + } = node; + if (isStatic) { + this.word("static"); + this.space(); + } + if (readonly) { + this.word("readonly"); + this.space(); + } + this.tokenChar(91); + this._parameters(node.parameters); + this.tokenChar(93); + this.print(node.typeAnnotation); + this.semicolon(); +} +function TSAnyKeyword() { + this.word("any"); +} +function TSBigIntKeyword() { + this.word("bigint"); +} +function TSUnknownKeyword() { + this.word("unknown"); +} +function TSNumberKeyword() { + this.word("number"); +} +function TSObjectKeyword() { + this.word("object"); +} +function TSBooleanKeyword() { + this.word("boolean"); +} +function TSStringKeyword() { + this.word("string"); +} +function TSSymbolKeyword() { + this.word("symbol"); +} +function TSVoidKeyword() { + this.word("void"); +} +function TSUndefinedKeyword() { + this.word("undefined"); +} +function TSNullKeyword() { + this.word("null"); +} +function TSNeverKeyword() { + this.word("never"); +} +function TSIntrinsicKeyword() { + this.word("intrinsic"); +} +function TSThisType() { + this.word("this"); +} +function TSFunctionType(node) { + this.tsPrintFunctionOrConstructorType(node); +} +function TSConstructorType(node) { + if (node.abstract) { + this.word("abstract"); + this.space(); + } + this.word("new"); + this.space(); + this.tsPrintFunctionOrConstructorType(node); +} +function tsPrintFunctionOrConstructorType(node) { + const { + typeParameters + } = node; + const parameters = node.parameters; + this.print(typeParameters); + this.tokenChar(40); + this._parameters(parameters); + this.tokenChar(41); + this.space(); + this.token("=>"); + this.space(); + const returnType = node.typeAnnotation; + this.print(returnType.typeAnnotation); +} +function TSTypeReference(node) { + this.print(node.typeName, true); + this.print(node.typeParameters, true); +} +function TSTypePredicate(node) { + if (node.asserts) { + this.word("asserts"); + this.space(); + } + this.print(node.parameterName); + if (node.typeAnnotation) { + this.space(); + this.word("is"); + this.space(); + this.print(node.typeAnnotation.typeAnnotation); + } +} +function TSTypeQuery(node) { + this.word("typeof"); + this.space(); + this.print(node.exprName); + if (node.typeParameters) { + this.print(node.typeParameters); + } +} +function TSTypeLiteral(node) { + this.tsPrintTypeLiteralOrInterfaceBody(node.members, node); +} +function tsPrintTypeLiteralOrInterfaceBody(members, node) { + tsPrintBraced(this, members, node); +} +function tsPrintBraced(printer, members, node) { + printer.token("{"); + if (members.length) { + printer.indent(); + printer.newline(); + for (const member of members) { + printer.print(member); + printer.newline(); + } + printer.dedent(); + } + printer.rightBrace(node); +} +function TSArrayType(node) { + this.print(node.elementType, true); + this.tokenChar(91); + this.tokenChar(93); +} +function TSTupleType(node) { + this.tokenChar(91); + this.printList(node.elementTypes); + this.tokenChar(93); +} +function TSOptionalType(node) { + this.print(node.typeAnnotation); + this.tokenChar(63); +} +function TSRestType(node) { + this.token("..."); + this.print(node.typeAnnotation); +} +function TSNamedTupleMember(node) { + this.print(node.label); + if (node.optional) this.tokenChar(63); + this.tokenChar(58); + this.space(); + this.print(node.elementType); +} +function TSUnionType(node) { + tsPrintUnionOrIntersectionType(this, node, "|"); +} +function TSIntersectionType(node) { + tsPrintUnionOrIntersectionType(this, node, "&"); +} +function tsPrintUnionOrIntersectionType(printer, node, sep) { + printer.printJoin(node.types, { + separator() { + this.space(); + this.token(sep); + this.space(); + } + }); +} +function TSConditionalType(node) { + this.print(node.checkType); + this.space(); + this.word("extends"); + this.space(); + this.print(node.extendsType); + this.space(); + this.tokenChar(63); + this.space(); + this.print(node.trueType); + this.space(); + this.tokenChar(58); + this.space(); + this.print(node.falseType); +} +function TSInferType(node) { + this.token("infer"); + this.space(); + this.print(node.typeParameter); +} +function TSParenthesizedType(node) { + this.tokenChar(40); + this.print(node.typeAnnotation); + this.tokenChar(41); +} +function TSTypeOperator(node) { + this.word(node.operator); + this.space(); + this.print(node.typeAnnotation); +} +function TSIndexedAccessType(node) { + this.print(node.objectType, true); + this.tokenChar(91); + this.print(node.indexType); + this.tokenChar(93); +} +function TSMappedType(node) { + const { + nameType, + optional, + readonly, + typeAnnotation + } = node; + this.tokenChar(123); + this.space(); + if (readonly) { + tokenIfPlusMinus(this, readonly); + this.word("readonly"); + this.space(); + } + this.tokenChar(91); + { + this.word(node.typeParameter.name); + } + this.space(); + this.word("in"); + this.space(); + { + this.print(node.typeParameter.constraint); + } + if (nameType) { + this.space(); + this.word("as"); + this.space(); + this.print(nameType); + } + this.tokenChar(93); + if (optional) { + tokenIfPlusMinus(this, optional); + this.tokenChar(63); + } + if (typeAnnotation) { + this.tokenChar(58); + this.space(); + this.print(typeAnnotation); + } + this.space(); + this.tokenChar(125); +} +function tokenIfPlusMinus(self, tok) { + if (tok !== true) { + self.token(tok); + } +} +function TSLiteralType(node) { + this.print(node.literal); +} +function TSExpressionWithTypeArguments(node) { + this.print(node.expression); + this.print(node.typeParameters); +} +function TSInterfaceDeclaration(node) { + const { + declare, + id, + typeParameters, + extends: extendz, + body + } = node; + if (declare) { + this.word("declare"); + this.space(); + } + this.word("interface"); + this.space(); + this.print(id); + this.print(typeParameters); + if (extendz != null && extendz.length) { + this.space(); + this.word("extends"); + this.space(); + this.printList(extendz); + } + this.space(); + this.print(body); +} +function TSInterfaceBody(node) { + this.tsPrintTypeLiteralOrInterfaceBody(node.body, node); +} +function TSTypeAliasDeclaration(node) { + const { + declare, + id, + typeParameters, + typeAnnotation + } = node; + if (declare) { + this.word("declare"); + this.space(); + } + this.word("type"); + this.space(); + this.print(id); + this.print(typeParameters); + this.space(); + this.tokenChar(61); + this.space(); + this.print(typeAnnotation); + this.semicolon(); +} +function TSTypeExpression(node) { + var _expression$trailingC; + const { + type, + expression, + typeAnnotation + } = node; + const forceParens = (_expression$trailingC = expression.trailingComments) == null ? void 0 : _expression$trailingC.some(c => c.type === "CommentLine" || /[\r\n\u2028\u2029]/.test(c.value)); + this.print(expression, true, undefined, forceParens); + this.space(); + this.word(type === "TSAsExpression" ? "as" : "satisfies"); + this.space(); + this.print(typeAnnotation); +} +function TSTypeAssertion(node) { + const { + typeAnnotation, + expression + } = node; + this.tokenChar(60); + this.print(typeAnnotation); + this.tokenChar(62); + this.space(); + this.print(expression); +} +function TSInstantiationExpression(node) { + this.print(node.expression); + this.print(node.typeParameters); +} +function TSEnumDeclaration(node) { + const { + declare, + const: isConst, + id, + members + } = node; + if (declare) { + this.word("declare"); + this.space(); + } + if (isConst) { + this.word("const"); + this.space(); + } + this.word("enum"); + this.space(); + this.print(id); + this.space(); + tsPrintBraced(this, members, node); +} +function TSEnumMember(node) { + const { + id, + initializer + } = node; + this.print(id); + if (initializer) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(initializer); + } + this.tokenChar(44); +} +function TSModuleDeclaration(node) { + const { + declare, + id + } = node; + if (declare) { + this.word("declare"); + this.space(); + } + if (!node.global) { + this.word(id.type === "Identifier" ? "namespace" : "module"); + this.space(); + } + this.print(id); + if (!node.body) { + this.semicolon(); + return; + } + let body = node.body; + while (body.type === "TSModuleDeclaration") { + this.tokenChar(46); + this.print(body.id); + body = body.body; + } + this.space(); + this.print(body); +} +function TSModuleBlock(node) { + tsPrintBraced(this, node.body, node); +} +function TSImportType(node) { + const { + argument, + qualifier, + typeParameters + } = node; + this.word("import"); + this.tokenChar(40); + this.print(argument); + this.tokenChar(41); + if (qualifier) { + this.tokenChar(46); + this.print(qualifier); + } + if (typeParameters) { + this.print(typeParameters); + } +} +function TSImportEqualsDeclaration(node) { + const { + isExport, + id, + moduleReference + } = node; + if (isExport) { + this.word("export"); + this.space(); + } + this.word("import"); + this.space(); + this.print(id); + this.space(); + this.tokenChar(61); + this.space(); + this.print(moduleReference); + this.semicolon(); +} +function TSExternalModuleReference(node) { + this.token("require("); + this.print(node.expression); + this.tokenChar(41); +} +function TSNonNullExpression(node) { + this.print(node.expression); + this.tokenChar(33); +} +function TSExportAssignment(node) { + this.word("export"); + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.expression); + this.semicolon(); +} +function TSNamespaceExportDeclaration(node) { + this.word("export"); + this.space(); + this.word("as"); + this.space(); + this.word("namespace"); + this.space(); + this.print(node.id); + this.semicolon(); +} +function tsPrintSignatureDeclarationBase(node) { + const { + typeParameters + } = node; + const parameters = node.parameters; + this.print(typeParameters); + this.tokenChar(40); + this._parameters(parameters); + this.tokenChar(41); + const returnType = node.typeAnnotation; + this.print(returnType); +} +function tsPrintClassMemberModifiers(node) { + const isField = node.type === "ClassAccessorProperty" || node.type === "ClassProperty"; + if (isField && node.declare) { + this.word("declare"); + this.space(); + } + if (node.accessibility) { + this.word(node.accessibility); + this.space(); + } + if (node.static) { + this.word("static"); + this.space(); + } + if (node.override) { + this.word("override"); + this.space(); + } + if (node.abstract) { + this.word("abstract"); + this.space(); + } + if (isField && node.readonly) { + this.word("readonly"); + this.space(); + } +} + +//# sourceMappingURL=typescript.js.map diff --git a/node_modules/@babel/generator/lib/generators/typescript.js.map b/node_modules/@babel/generator/lib/generators/typescript.js.map new file mode 100644 index 0000000..1ed2078 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/typescript.js.map @@ -0,0 +1 @@ +{"version":3,"names":["TSTypeAnnotation","node","token","space","optional","print","typeAnnotation","TSTypeParameterInstantiation","parent","printList","params","type","length","TSTypeParameter","in","word","out","name","constraint","default","TSParameterProperty","accessibility","readonly","_param","parameter","TSDeclareFunction","declare","_functionHead","semicolon","TSDeclareMethod","_classMethodHead","TSQualifiedName","left","right","TSCallSignatureDeclaration","tsPrintSignatureDeclarationBase","TSConstructSignatureDeclaration","TSPropertySignature","tsPrintPropertyOrMethodName","computed","key","TSMethodSignature","kind","TSIndexSignature","static","isStatic","_parameters","parameters","TSAnyKeyword","TSBigIntKeyword","TSUnknownKeyword","TSNumberKeyword","TSObjectKeyword","TSBooleanKeyword","TSStringKeyword","TSSymbolKeyword","TSVoidKeyword","TSUndefinedKeyword","TSNullKeyword","TSNeverKeyword","TSIntrinsicKeyword","TSThisType","TSFunctionType","tsPrintFunctionOrConstructorType","TSConstructorType","abstract","typeParameters","returnType","TSTypeReference","typeName","TSTypePredicate","asserts","parameterName","TSTypeQuery","exprName","TSTypeLiteral","tsPrintTypeLiteralOrInterfaceBody","members","tsPrintBraced","printer","indent","newline","member","dedent","rightBrace","TSArrayType","elementType","TSTupleType","elementTypes","TSOptionalType","TSRestType","TSNamedTupleMember","label","TSUnionType","tsPrintUnionOrIntersectionType","TSIntersectionType","sep","printJoin","types","separator","TSConditionalType","checkType","extendsType","trueType","falseType","TSInferType","typeParameter","TSParenthesizedType","TSTypeOperator","operator","TSIndexedAccessType","objectType","indexType","TSMappedType","nameType","tokenIfPlusMinus","self","tok","TSLiteralType","literal","TSExpressionWithTypeArguments","expression","TSInterfaceDeclaration","id","extends","extendz","body","TSInterfaceBody","TSTypeAliasDeclaration","TSTypeExpression","_expression$trailingC","forceParens","trailingComments","some","c","test","value","undefined","TSTypeAssertion","TSInstantiationExpression","TSEnumDeclaration","const","isConst","TSEnumMember","initializer","TSModuleDeclaration","global","TSModuleBlock","TSImportType","argument","qualifier","TSImportEqualsDeclaration","isExport","moduleReference","TSExternalModuleReference","TSNonNullExpression","TSExportAssignment","TSNamespaceExportDeclaration","tsPrintClassMemberModifiers","isField","override"],"sources":["../../src/generators/typescript.ts"],"sourcesContent":["import type Printer from \"../printer.ts\";\nimport type * as t from \"@babel/types\";\n\nexport function TSTypeAnnotation(this: Printer, node: t.TSTypeAnnotation) {\n this.token(\":\");\n this.space();\n // @ts-expect-error todo(flow->ts) can this be removed? `.optional` looks to be not existing property\n if (node.optional) this.token(\"?\");\n this.print(node.typeAnnotation);\n}\n\nexport function TSTypeParameterInstantiation(\n this: Printer,\n node: t.TSTypeParameterInstantiation,\n parent: t.Node,\n): void {\n this.token(\"<\");\n this.printList(node.params, {});\n if (parent.type === \"ArrowFunctionExpression\" && node.params.length === 1) {\n this.token(\",\");\n }\n this.token(\">\");\n}\n\nexport { TSTypeParameterInstantiation as TSTypeParameterDeclaration };\n\nexport function TSTypeParameter(this: Printer, node: t.TSTypeParameter) {\n if (node.in) {\n this.word(\"in\");\n this.space();\n }\n\n if (node.out) {\n this.word(\"out\");\n this.space();\n }\n\n this.word(\n !process.env.BABEL_8_BREAKING\n ? (node.name as unknown as string)\n : (node.name as unknown as t.Identifier).name,\n );\n\n if (node.constraint) {\n this.space();\n this.word(\"extends\");\n this.space();\n this.print(node.constraint);\n }\n\n if (node.default) {\n this.space();\n this.token(\"=\");\n this.space();\n this.print(node.default);\n }\n}\n\nexport function TSParameterProperty(\n this: Printer,\n node: t.TSParameterProperty,\n) {\n if (node.accessibility) {\n this.word(node.accessibility);\n this.space();\n }\n\n if (node.readonly) {\n this.word(\"readonly\");\n this.space();\n }\n\n this._param(node.parameter);\n}\n\nexport function TSDeclareFunction(\n this: Printer,\n node: t.TSDeclareFunction,\n parent: t.ParentMaps[\"TSDeclareFunction\"],\n) {\n if (node.declare) {\n this.word(\"declare\");\n this.space();\n }\n this._functionHead(node, parent);\n this.semicolon();\n}\n\nexport function TSDeclareMethod(this: Printer, node: t.TSDeclareMethod) {\n this._classMethodHead(node);\n this.semicolon();\n}\n\nexport function TSQualifiedName(this: Printer, node: t.TSQualifiedName) {\n this.print(node.left);\n this.token(\".\");\n this.print(node.right);\n}\n\nexport function TSCallSignatureDeclaration(\n this: Printer,\n node: t.TSCallSignatureDeclaration,\n) {\n this.tsPrintSignatureDeclarationBase(node);\n this.semicolon();\n}\n\nexport function TSConstructSignatureDeclaration(\n this: Printer,\n node: t.TSConstructSignatureDeclaration,\n) {\n this.word(\"new\");\n this.space();\n this.tsPrintSignatureDeclarationBase(node);\n this.semicolon();\n}\n\nexport function TSPropertySignature(\n this: Printer,\n node: t.TSPropertySignature,\n) {\n const { readonly } = node;\n if (readonly) {\n this.word(\"readonly\");\n this.space();\n }\n this.tsPrintPropertyOrMethodName(node);\n this.print(node.typeAnnotation);\n this.semicolon();\n}\n\nexport function tsPrintPropertyOrMethodName(\n this: Printer,\n node: t.TSPropertySignature | t.TSMethodSignature,\n) {\n if (node.computed) {\n this.token(\"[\");\n }\n this.print(node.key);\n if (node.computed) {\n this.token(\"]\");\n }\n if (node.optional) {\n this.token(\"?\");\n }\n}\n\nexport function TSMethodSignature(this: Printer, node: t.TSMethodSignature) {\n const { kind } = node;\n if (kind === \"set\" || kind === \"get\") {\n this.word(kind);\n this.space();\n }\n this.tsPrintPropertyOrMethodName(node);\n this.tsPrintSignatureDeclarationBase(node);\n this.semicolon();\n}\n\nexport function TSIndexSignature(this: Printer, node: t.TSIndexSignature) {\n const { readonly, static: isStatic } = node;\n if (isStatic) {\n this.word(\"static\");\n this.space();\n }\n if (readonly) {\n this.word(\"readonly\");\n this.space();\n }\n this.token(\"[\");\n this._parameters(node.parameters);\n this.token(\"]\");\n this.print(node.typeAnnotation);\n this.semicolon();\n}\n\nexport function TSAnyKeyword(this: Printer) {\n this.word(\"any\");\n}\nexport function TSBigIntKeyword(this: Printer) {\n this.word(\"bigint\");\n}\nexport function TSUnknownKeyword(this: Printer) {\n this.word(\"unknown\");\n}\nexport function TSNumberKeyword(this: Printer) {\n this.word(\"number\");\n}\nexport function TSObjectKeyword(this: Printer) {\n this.word(\"object\");\n}\nexport function TSBooleanKeyword(this: Printer) {\n this.word(\"boolean\");\n}\nexport function TSStringKeyword(this: Printer) {\n this.word(\"string\");\n}\nexport function TSSymbolKeyword(this: Printer) {\n this.word(\"symbol\");\n}\nexport function TSVoidKeyword(this: Printer) {\n this.word(\"void\");\n}\nexport function TSUndefinedKeyword(this: Printer) {\n this.word(\"undefined\");\n}\nexport function TSNullKeyword(this: Printer) {\n this.word(\"null\");\n}\nexport function TSNeverKeyword(this: Printer) {\n this.word(\"never\");\n}\nexport function TSIntrinsicKeyword(this: Printer) {\n this.word(\"intrinsic\");\n}\n\nexport function TSThisType(this: Printer) {\n this.word(\"this\");\n}\n\nexport function TSFunctionType(this: Printer, node: t.TSFunctionType) {\n this.tsPrintFunctionOrConstructorType(node);\n}\n\nexport function TSConstructorType(this: Printer, node: t.TSConstructorType) {\n if (node.abstract) {\n this.word(\"abstract\");\n this.space();\n }\n this.word(\"new\");\n this.space();\n this.tsPrintFunctionOrConstructorType(node);\n}\n\nexport function tsPrintFunctionOrConstructorType(\n this: Printer,\n node: t.TSFunctionType | t.TSConstructorType,\n) {\n const { typeParameters } = node;\n const parameters = process.env.BABEL_8_BREAKING\n ? // @ts-ignore(Babel 7 vs Babel 8) Babel 8 AST shape\n node.params\n : // @ts-ignore(Babel 7 vs Babel 8) Babel 7 AST shape\n node.parameters;\n this.print(typeParameters);\n this.token(\"(\");\n this._parameters(parameters);\n this.token(\")\");\n this.space();\n this.token(\"=>\");\n this.space();\n const returnType = process.env.BABEL_8_BREAKING\n ? // @ts-ignore(Babel 7 vs Babel 8) Babel 8 AST shape\n node.returnType\n : // @ts-ignore(Babel 7 vs Babel 8) Babel 7 AST shape\n node.typeAnnotation;\n this.print(returnType.typeAnnotation);\n}\n\nexport function TSTypeReference(this: Printer, node: t.TSTypeReference) {\n this.print(node.typeName, true);\n this.print(node.typeParameters, true);\n}\n\nexport function TSTypePredicate(this: Printer, node: t.TSTypePredicate) {\n if (node.asserts) {\n this.word(\"asserts\");\n this.space();\n }\n this.print(node.parameterName);\n if (node.typeAnnotation) {\n this.space();\n this.word(\"is\");\n this.space();\n this.print(node.typeAnnotation.typeAnnotation);\n }\n}\n\nexport function TSTypeQuery(this: Printer, node: t.TSTypeQuery) {\n this.word(\"typeof\");\n this.space();\n this.print(node.exprName);\n\n if (node.typeParameters) {\n this.print(node.typeParameters);\n }\n}\n\nexport function TSTypeLiteral(this: Printer, node: t.TSTypeLiteral) {\n this.tsPrintTypeLiteralOrInterfaceBody(node.members, node);\n}\n\nexport function tsPrintTypeLiteralOrInterfaceBody(\n this: Printer,\n members: t.TSTypeElement[],\n node: t.TSType | t.TSInterfaceBody,\n) {\n tsPrintBraced(this, members, node);\n}\n\nfunction tsPrintBraced(printer: Printer, members: t.Node[], node: t.Node) {\n printer.token(\"{\");\n if (members.length) {\n printer.indent();\n printer.newline();\n for (const member of members) {\n printer.print(member);\n //this.token(sep);\n printer.newline();\n }\n printer.dedent();\n }\n\n printer.rightBrace(node);\n}\n\nexport function TSArrayType(this: Printer, node: t.TSArrayType) {\n this.print(node.elementType, true);\n\n this.token(\"[\");\n this.token(\"]\");\n}\n\nexport function TSTupleType(this: Printer, node: t.TSTupleType) {\n this.token(\"[\");\n this.printList(node.elementTypes);\n this.token(\"]\");\n}\n\nexport function TSOptionalType(this: Printer, node: t.TSOptionalType) {\n this.print(node.typeAnnotation);\n this.token(\"?\");\n}\n\nexport function TSRestType(this: Printer, node: t.TSRestType) {\n this.token(\"...\");\n this.print(node.typeAnnotation);\n}\n\nexport function TSNamedTupleMember(this: Printer, node: t.TSNamedTupleMember) {\n this.print(node.label);\n if (node.optional) this.token(\"?\");\n this.token(\":\");\n this.space();\n this.print(node.elementType);\n}\n\nexport function TSUnionType(this: Printer, node: t.TSUnionType) {\n tsPrintUnionOrIntersectionType(this, node, \"|\");\n}\n\nexport function TSIntersectionType(this: Printer, node: t.TSIntersectionType) {\n tsPrintUnionOrIntersectionType(this, node, \"&\");\n}\n\nfunction tsPrintUnionOrIntersectionType(\n printer: Printer,\n node: t.TSUnionType | t.TSIntersectionType,\n sep: \"|\" | \"&\",\n) {\n printer.printJoin(node.types, {\n separator() {\n this.space();\n this.token(sep);\n this.space();\n },\n });\n}\n\nexport function TSConditionalType(this: Printer, node: t.TSConditionalType) {\n this.print(node.checkType);\n this.space();\n this.word(\"extends\");\n this.space();\n this.print(node.extendsType);\n this.space();\n this.token(\"?\");\n this.space();\n this.print(node.trueType);\n this.space();\n this.token(\":\");\n this.space();\n this.print(node.falseType);\n}\n\nexport function TSInferType(this: Printer, node: t.TSInferType) {\n this.token(\"infer\");\n this.space();\n this.print(node.typeParameter);\n}\n\nexport function TSParenthesizedType(\n this: Printer,\n node: t.TSParenthesizedType,\n) {\n this.token(\"(\");\n this.print(node.typeAnnotation);\n this.token(\")\");\n}\n\nexport function TSTypeOperator(this: Printer, node: t.TSTypeOperator) {\n this.word(node.operator);\n this.space();\n this.print(node.typeAnnotation);\n}\n\nexport function TSIndexedAccessType(\n this: Printer,\n node: t.TSIndexedAccessType,\n) {\n this.print(node.objectType, true);\n this.token(\"[\");\n this.print(node.indexType);\n this.token(\"]\");\n}\n\nexport function TSMappedType(this: Printer, node: t.TSMappedType) {\n const { nameType, optional, readonly, typeAnnotation } = node;\n this.token(\"{\");\n this.space();\n if (readonly) {\n tokenIfPlusMinus(this, readonly);\n this.word(\"readonly\");\n this.space();\n }\n\n this.token(\"[\");\n if (process.env.BABEL_8_BREAKING) {\n // @ts-ignore(Babel 7 vs Babel 8) Babel 8 AST shape\n this.word(node.key.name);\n } else {\n // @ts-ignore(Babel 7 vs Babel 8) Babel 7 AST shape\n this.word(node.typeParameter.name);\n }\n\n this.space();\n this.word(\"in\");\n this.space();\n if (process.env.BABEL_8_BREAKING) {\n // @ts-ignore(Babel 7 vs Babel 8) Babel 8 AST shape\n this.print(node.constraint);\n } else {\n // @ts-ignore(Babel 7 vs Babel 8) Babel 7 AST shape\n this.print(node.typeParameter.constraint);\n }\n\n if (nameType) {\n this.space();\n this.word(\"as\");\n this.space();\n this.print(nameType);\n }\n\n this.token(\"]\");\n\n if (optional) {\n tokenIfPlusMinus(this, optional);\n this.token(\"?\");\n }\n\n if (typeAnnotation) {\n this.token(\":\");\n this.space();\n this.print(typeAnnotation);\n }\n this.space();\n this.token(\"}\");\n}\n\nfunction tokenIfPlusMinus(self: Printer, tok: true | \"+\" | \"-\") {\n if (tok !== true) {\n self.token(tok);\n }\n}\n\nexport function TSLiteralType(this: Printer, node: t.TSLiteralType) {\n this.print(node.literal);\n}\n\nexport function TSExpressionWithTypeArguments(\n this: Printer,\n node: t.TSExpressionWithTypeArguments,\n) {\n this.print(node.expression);\n this.print(node.typeParameters);\n}\n\nexport function TSInterfaceDeclaration(\n this: Printer,\n node: t.TSInterfaceDeclaration,\n) {\n const { declare, id, typeParameters, extends: extendz, body } = node;\n if (declare) {\n this.word(\"declare\");\n this.space();\n }\n this.word(\"interface\");\n this.space();\n this.print(id);\n this.print(typeParameters);\n if (extendz?.length) {\n this.space();\n this.word(\"extends\");\n this.space();\n this.printList(extendz);\n }\n this.space();\n this.print(body);\n}\n\nexport function TSInterfaceBody(this: Printer, node: t.TSInterfaceBody) {\n this.tsPrintTypeLiteralOrInterfaceBody(node.body, node);\n}\n\nexport function TSTypeAliasDeclaration(\n this: Printer,\n node: t.TSTypeAliasDeclaration,\n) {\n const { declare, id, typeParameters, typeAnnotation } = node;\n if (declare) {\n this.word(\"declare\");\n this.space();\n }\n this.word(\"type\");\n this.space();\n this.print(id);\n this.print(typeParameters);\n this.space();\n this.token(\"=\");\n this.space();\n this.print(typeAnnotation);\n this.semicolon();\n}\n\nfunction TSTypeExpression(\n this: Printer,\n node: t.TSAsExpression | t.TSSatisfiesExpression,\n) {\n const { type, expression, typeAnnotation } = node;\n const forceParens = expression.trailingComments?.some(\n c => c.type === \"CommentLine\" || /[\\r\\n\\u2028\\u2029]/.test(c.value),\n );\n this.print(expression, true, undefined, forceParens);\n this.space();\n this.word(type === \"TSAsExpression\" ? \"as\" : \"satisfies\");\n this.space();\n this.print(typeAnnotation);\n}\n\nexport {\n TSTypeExpression as TSAsExpression,\n TSTypeExpression as TSSatisfiesExpression,\n};\n\nexport function TSTypeAssertion(this: Printer, node: t.TSTypeAssertion) {\n const { typeAnnotation, expression } = node;\n this.token(\"<\");\n this.print(typeAnnotation);\n this.token(\">\");\n this.space();\n this.print(expression);\n}\n\nexport function TSInstantiationExpression(\n this: Printer,\n node: t.TSInstantiationExpression,\n) {\n this.print(node.expression);\n this.print(node.typeParameters);\n}\n\nexport function TSEnumDeclaration(this: Printer, node: t.TSEnumDeclaration) {\n const { declare, const: isConst, id, members } = node;\n if (declare) {\n this.word(\"declare\");\n this.space();\n }\n if (isConst) {\n this.word(\"const\");\n this.space();\n }\n this.word(\"enum\");\n this.space();\n this.print(id);\n this.space();\n tsPrintBraced(this, members, node);\n}\n\nexport function TSEnumMember(this: Printer, node: t.TSEnumMember) {\n const { id, initializer } = node;\n this.print(id);\n if (initializer) {\n this.space();\n this.token(\"=\");\n this.space();\n this.print(initializer);\n }\n this.token(\",\");\n}\n\nexport function TSModuleDeclaration(\n this: Printer,\n node: t.TSModuleDeclaration,\n) {\n const { declare, id } = node;\n\n if (declare) {\n this.word(\"declare\");\n this.space();\n }\n\n if (!node.global) {\n this.word(id.type === \"Identifier\" ? \"namespace\" : \"module\");\n this.space();\n }\n this.print(id);\n\n if (!node.body) {\n this.semicolon();\n return;\n }\n\n let body = node.body;\n while (body.type === \"TSModuleDeclaration\") {\n this.token(\".\");\n this.print(body.id);\n body = body.body;\n }\n\n this.space();\n this.print(body);\n}\n\nexport function TSModuleBlock(this: Printer, node: t.TSModuleBlock) {\n tsPrintBraced(this, node.body, node);\n}\n\nexport function TSImportType(this: Printer, node: t.TSImportType) {\n const { argument, qualifier, typeParameters } = node;\n this.word(\"import\");\n this.token(\"(\");\n this.print(argument);\n this.token(\")\");\n if (qualifier) {\n this.token(\".\");\n this.print(qualifier);\n }\n if (typeParameters) {\n this.print(typeParameters);\n }\n}\n\nexport function TSImportEqualsDeclaration(\n this: Printer,\n node: t.TSImportEqualsDeclaration,\n) {\n const { isExport, id, moduleReference } = node;\n if (isExport) {\n this.word(\"export\");\n this.space();\n }\n this.word(\"import\");\n this.space();\n this.print(id);\n this.space();\n this.token(\"=\");\n this.space();\n this.print(moduleReference);\n this.semicolon();\n}\n\nexport function TSExternalModuleReference(\n this: Printer,\n node: t.TSExternalModuleReference,\n) {\n this.token(\"require(\");\n this.print(node.expression);\n this.token(\")\");\n}\n\nexport function TSNonNullExpression(\n this: Printer,\n node: t.TSNonNullExpression,\n) {\n this.print(node.expression);\n this.token(\"!\");\n}\n\nexport function TSExportAssignment(this: Printer, node: t.TSExportAssignment) {\n this.word(\"export\");\n this.space();\n this.token(\"=\");\n this.space();\n this.print(node.expression);\n this.semicolon();\n}\n\nexport function TSNamespaceExportDeclaration(\n this: Printer,\n node: t.TSNamespaceExportDeclaration,\n) {\n this.word(\"export\");\n this.space();\n this.word(\"as\");\n this.space();\n this.word(\"namespace\");\n this.space();\n this.print(node.id);\n this.semicolon();\n}\n\nexport function tsPrintSignatureDeclarationBase(this: Printer, node: any) {\n const { typeParameters } = node;\n const parameters = process.env.BABEL_8_BREAKING\n ? node.params\n : node.parameters;\n this.print(typeParameters);\n this.token(\"(\");\n this._parameters(parameters);\n this.token(\")\");\n const returnType = process.env.BABEL_8_BREAKING\n ? node.returnType\n : node.typeAnnotation;\n this.print(returnType);\n}\n\nexport function tsPrintClassMemberModifiers(\n this: Printer,\n node:\n | t.ClassProperty\n | t.ClassAccessorProperty\n | t.ClassMethod\n | t.ClassPrivateMethod\n | t.TSDeclareMethod,\n) {\n const isField =\n node.type === \"ClassAccessorProperty\" || node.type === \"ClassProperty\";\n if (isField && node.declare) {\n this.word(\"declare\");\n this.space();\n }\n if (node.accessibility) {\n this.word(node.accessibility);\n this.space();\n }\n if (node.static) {\n this.word(\"static\");\n this.space();\n }\n if (node.override) {\n this.word(\"override\");\n this.space();\n }\n if (node.abstract) {\n this.word(\"abstract\");\n this.space();\n }\n if (isField && node.readonly) {\n this.word(\"readonly\");\n this.space();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGO,SAASA,gBAAgBA,CAAgBC,IAAwB,EAAE;EACxE,IAAI,CAACC,SAAK,GAAI,CAAC;EACf,IAAI,CAACC,KAAK,CAAC,CAAC;EAEZ,IAAIF,IAAI,CAACG,QAAQ,EAAE,IAAI,CAACF,SAAK,GAAI,CAAC;EAClC,IAAI,CAACG,KAAK,CAACJ,IAAI,CAACK,cAAc,CAAC;AACjC;AAEO,SAASC,4BAA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AO,IAAI9J,IAAI,CAACyB,OAAO,EAAE;IAC3B,IAAI,CAACX,IAAI,CAAC,SAAS,CAAC;IACpB,IAAI,CAACZ,KAAK,CAAC,CAAC;EACd;EACA,IAAIF,IAAI,CAACoB,aAAa,EAAE;IACtB,IAAI,CAACN,IAAI,CAACd,IAAI,CAACoB,aAAa,CAAC;IAC7B,IAAI,CAAClB,KAAK,CAAC,CAAC;EACd;EACA,IAAIF,IAAI,CAAC2C,MAAM,EAAE;IACf,IAAI,CAAC7B,IAAI,CAAC,QAAQ,CAAC;IACnB,IAAI,CAACZ,KAAK,CAAC,CAAC;EACd;EACA,IAAIF,IAAI,CAAC+J,QAAQ,EAAE;IACjB,IAAI,CAACjJ,IAAI,CAAC,UAAU,CAAC;IACrB,IAAI,CAACZ,KAAK,CAAC,CAAC;EACd;EACA,IAAIF,IAAI,CAACgE,QAAQ,EAAE;IACjB,IAAI,CAAClD,IAAI,CAAC,UAAU,CAAC;IACrB,IAAI,CAACZ,KAAK,CAAC,CAAC;EACd;EACA,IAAI4J,OAAO,IAAI9J,IAAI,CAACqB,QAAQ,EAAE;IAC5B,IAAI,CAACP,IAAI,CAAC,UAAU,CAAC;IACrB,IAAI,CAACZ,KAAK,CAAC,CAAC;EACd;AACF","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/index.js b/node_modules/@babel/generator/lib/index.js new file mode 100644 index 0000000..2678931 --- /dev/null +++ b/node_modules/@babel/generator/lib/index.js @@ -0,0 +1,89 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = generate; +var _sourceMap = require("./source-map.js"); +var _printer = require("./printer.js"); +function normalizeOptions(code, opts) { + const format = { + auxiliaryCommentBefore: opts.auxiliaryCommentBefore, + auxiliaryCommentAfter: opts.auxiliaryCommentAfter, + shouldPrintComment: opts.shouldPrintComment, + retainLines: opts.retainLines, + retainFunctionParens: opts.retainFunctionParens, + comments: opts.comments == null || opts.comments, + compact: opts.compact, + minified: opts.minified, + concise: opts.concise, + indent: { + adjustMultilineComment: true, + style: " " + }, + jsescOption: Object.assign({ + quotes: "double", + wrap: true, + minimal: false + }, opts.jsescOption), + topicToken: opts.topicToken, + importAttributesKeyword: opts.importAttributesKeyword + }; + { + var _opts$recordAndTupleS; + format.decoratorsBeforeExport = opts.decoratorsBeforeExport; + format.jsescOption.json = opts.jsonCompatibleStrings; + format.recordAndTupleSyntaxType = (_opts$recordAndTupleS = opts.recordAndTupleSyntaxType) != null ? _opts$recordAndTupleS : "hash"; + } + if (format.minified) { + format.compact = true; + format.shouldPrintComment = format.shouldPrintComment || (() => format.comments); + } else { + format.shouldPrintComment = format.shouldPrintComment || (value => format.comments || value.includes("@license") || value.includes("@preserve")); + } + if (format.compact === "auto") { + format.compact = typeof code === "string" && code.length > 500000; + if (format.compact) { + console.error("[BABEL] Note: The code generator has deoptimised the styling of " + `${opts.filename} as it exceeds the max of ${"500KB"}.`); + } + } + if (format.compact) { + format.indent.adjustMultilineComment = false; + } + const { + auxiliaryCommentBefore, + auxiliaryCommentAfter, + shouldPrintComment + } = format; + if (auxiliaryCommentBefore && !shouldPrintComment(auxiliaryCommentBefore)) { + format.auxiliaryCommentBefore = undefined; + } + if (auxiliaryCommentAfter && !shouldPrintComment(auxiliaryCommentAfter)) { + format.auxiliaryCommentAfter = undefined; + } + return format; +} +{ + exports.CodeGenerator = class CodeGenerator { + constructor(ast, opts = {}, code) { + this._ast = void 0; + this._format = void 0; + this._map = void 0; + this._ast = ast; + this._format = normalizeOptions(code, opts); + this._map = opts.sourceMaps ? new _sourceMap.default(opts, code) : null; + } + generate() { + const printer = new _printer.default(this._format, this._map); + return printer.generate(this._ast); + } + }; +} +function generate(ast, opts = {}, code) { + const format = normalizeOptions(code, opts); + const map = opts.sourceMaps ? new _sourceMap.default(opts, code) : null; + const printer = new _printer.default(format, map); + return printer.generate(ast); +} + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/generator/lib/index.js.map b/node_modules/@babel/generator/lib/index.js.map new file mode 100644 index 0000000..c2a1eee --- /dev/null +++ b/node_modules/@babel/generator/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_sourceMap","require","_printer","normalizeOptions","code","opts","format","auxiliaryCommentBefore","auxiliaryCommentAfter","shouldPrintComment","retainLines","retainFunctionParens","comments","compact","minified","concise","indent","adjustMultilineComment","style","jsescOption","Object","assign","quotes","wrap","minimal","topicToken","importAttributesKeyword","_opts$recordAndTupleS","decoratorsBeforeExport","json","jsonCompatibleStrings","recordAndTupleSyntaxType","value","includes","length","console","error","filename","undefined","exports","CodeGenerator","constructor","ast","_ast","_format","_map","sourceMaps","SourceMap","generate","printer","Printer","map"],"sources":["../src/index.ts"],"sourcesContent":["import SourceMap from \"./source-map.ts\";\nimport Printer from \"./printer.ts\";\nimport type * as t from \"@babel/types\";\nimport type { Opts as jsescOptions } from \"jsesc\";\nimport type { Format } from \"./printer.ts\";\nimport type {\n EncodedSourceMap,\n DecodedSourceMap,\n Mapping,\n} from \"@jridgewell/gen-mapping\";\n\n/**\n * Normalize generator options, setting defaults.\n *\n * - Detects code indentation.\n * - If `opts.compact = \"auto\"` and the code is over 500KB, `compact` will be set to `true`.\n */\n\nfunction normalizeOptions(\n code: string | { [filename: string]: string },\n opts: GeneratorOptions,\n): Format {\n const format: Format = {\n auxiliaryCommentBefore: opts.auxiliaryCommentBefore,\n auxiliaryCommentAfter: opts.auxiliaryCommentAfter,\n shouldPrintComment: opts.shouldPrintComment,\n retainLines: opts.retainLines,\n retainFunctionParens: opts.retainFunctionParens,\n comments: opts.comments == null || opts.comments,\n compact: opts.compact,\n minified: opts.minified,\n concise: opts.concise,\n indent: {\n adjustMultilineComment: true,\n style: \" \",\n },\n jsescOption: {\n quotes: \"double\",\n wrap: true,\n minimal: process.env.BABEL_8_BREAKING ? true : false,\n ...opts.jsescOption,\n },\n topicToken: opts.topicToken,\n importAttributesKeyword: opts.importAttributesKeyword,\n };\n\n if (!process.env.BABEL_8_BREAKING) {\n format.decoratorsBeforeExport = opts.decoratorsBeforeExport;\n format.jsescOption.json = opts.jsonCompatibleStrings;\n format.recordAndTupleSyntaxType = opts.recordAndTupleSyntaxType ?? \"hash\";\n }\n\n if (format.minified) {\n format.compact = true;\n\n format.shouldPrintComment =\n format.shouldPrintComment || (() => format.comments);\n } else {\n format.shouldPrintComment =\n format.shouldPrintComment ||\n (value =>\n format.comments ||\n value.includes(\"@license\") ||\n value.includes(\"@preserve\"));\n }\n\n if (format.compact === \"auto\") {\n format.compact = typeof code === \"string\" && code.length > 500_000; // 500KB\n\n if (format.compact) {\n console.error(\n \"[BABEL] Note: The code generator has deoptimised the styling of \" +\n `${opts.filename} as it exceeds the max of ${\"500KB\"}.`,\n );\n }\n }\n\n if (format.compact) {\n format.indent.adjustMultilineComment = false;\n }\n\n const { auxiliaryCommentBefore, auxiliaryCommentAfter, shouldPrintComment } =\n format;\n\n if (auxiliaryCommentBefore && !shouldPrintComment(auxiliaryCommentBefore)) {\n format.auxiliaryCommentBefore = undefined;\n }\n if (auxiliaryCommentAfter && !shouldPrintComment(auxiliaryCommentAfter)) {\n format.auxiliaryCommentAfter = undefined;\n }\n\n return format;\n}\n\nexport interface GeneratorOptions {\n /**\n * Optional string to add as a block comment at the start of the output file.\n */\n auxiliaryCommentBefore?: string;\n\n /**\n * Optional string to add as a block comment at the end of the output file.\n */\n auxiliaryCommentAfter?: string;\n\n /**\n * Function that takes a comment (as a string) and returns true if the comment should be included in the output.\n * By default, comments are included if `opts.comments` is `true` or if `opts.minified` is `false` and the comment\n * contains `@preserve` or `@license`.\n */\n shouldPrintComment?(comment: string): boolean;\n\n /**\n * Attempt to use the same line numbers in the output code as in the source code (helps preserve stack traces).\n * Defaults to `false`.\n */\n retainLines?: boolean;\n\n /**\n * Retain parens around function expressions (could be used to change engine parsing behavior)\n * Defaults to `false`.\n */\n retainFunctionParens?: boolean;\n\n /**\n * Should comments be included in output? Defaults to `true`.\n */\n comments?: boolean;\n\n /**\n * Set to true to avoid adding whitespace for formatting. Defaults to the value of `opts.minified`.\n */\n compact?: boolean | \"auto\";\n\n /**\n * Should the output be minified. Defaults to `false`.\n */\n minified?: boolean;\n\n /**\n * Set to true to reduce whitespace (but not as much as opts.compact). Defaults to `false`.\n */\n concise?: boolean;\n\n /**\n * Used in warning messages\n */\n filename?: string;\n\n /**\n * Enable generating source maps. Defaults to `false`.\n */\n sourceMaps?: boolean;\n\n inputSourceMap?: any;\n\n /**\n * A root for all relative URLs in the source map.\n */\n sourceRoot?: string;\n\n /**\n * The filename for the source code (i.e. the code in the `code` argument).\n * This will only be used if `code` is a string.\n */\n sourceFileName?: string;\n\n /**\n * Set to true to run jsesc with \"json\": true to print \"\\u00A9\" vs. \"©\";\n * @deprecated use `jsescOptions: { json: true }` instead\n */\n jsonCompatibleStrings?: boolean;\n\n /**\n * Set to true to enable support for experimental decorators syntax before\n * module exports. If not specified, decorators will be printed in the same\n * position as they were in the input source code.\n * @deprecated Removed in Babel 8\n */\n decoratorsBeforeExport?: boolean;\n\n /**\n * Options for outputting jsesc representation.\n */\n jsescOption?: jsescOptions;\n\n /**\n * For use with the recordAndTuple token.\n * @deprecated It will be removed in Babel 8.\n */\n recordAndTupleSyntaxType?: \"bar\" | \"hash\";\n\n /**\n * For use with the Hack-style pipe operator.\n * Changes what token is used for pipe bodies’ topic references.\n */\n topicToken?: \"%\" | \"#\" | \"@@\" | \"^^\" | \"^\";\n\n /**\n * The import attributes syntax style:\n * - \"with\" : `import { a } from \"b\" with { type: \"json\" };`\n * - \"assert\" : `import { a } from \"b\" assert { type: \"json\" };`\n * - \"with-legacy\" : `import { a } from \"b\" with type: \"json\";`\n */\n importAttributesKeyword?: \"with\" | \"assert\" | \"with-legacy\";\n}\n\nexport interface GeneratorResult {\n code: string;\n map: EncodedSourceMap | null;\n decodedMap: DecodedSourceMap | undefined;\n rawMappings: Mapping[] | undefined;\n}\n\nif (!process.env.BABEL_8_BREAKING && !USE_ESM) {\n /**\n * We originally exported the Generator class above, but to make it extra clear that it is a private API,\n * we have moved that to an internal class instance and simplified the interface to the two public methods\n * that we wish to support.\n */\n\n // eslint-disable-next-line no-restricted-globals\n exports.CodeGenerator = class CodeGenerator {\n private _ast: t.Node;\n private _format: Format | undefined;\n private _map: SourceMap | null;\n constructor(ast: t.Node, opts: GeneratorOptions = {}, code?: string) {\n this._ast = ast;\n this._format = normalizeOptions(code, opts);\n this._map = opts.sourceMaps ? new SourceMap(opts, code) : null;\n }\n generate(): GeneratorResult {\n const printer = new Printer(this._format, this._map);\n\n return printer.generate(this._ast);\n }\n };\n}\n\n/**\n * Turns an AST into code, maintaining sourcemaps, user preferences, and valid output.\n * @param ast - the abstract syntax tree from which to generate output code.\n * @param opts - used for specifying options for code generation.\n * @param code - the original source code, used for source maps.\n * @returns - an object containing the output code and source map.\n */\nexport default function generate(\n ast: t.Node,\n opts: GeneratorOptions = {},\n code?: string | { [filename: string]: string },\n): GeneratorResult {\n const format = normalizeOptions(code, opts);\n const map = opts.sourceMaps ? new SourceMap(opts, code) : null;\n\n const printer = new Printer(format, map);\n\n return printer.generate(ast);\n}\n"],"mappings":";;;;;;AAAA,IAAAA,UAAA,GAAAC,OAAA;AACA,IAAAC,QAAA,GAAAD,OAAA;AAiBA,SAASE,gBAAgBA,CACvBC,IAA6C,EAC7CC,IAAsB,EACd;EACR,MAAMC,MAAc,GAAG;IACrBC,sBAAsB,EAAEF,IAAI,CAACE,sBAAsB;IACnDC,qBAAqB,EAAEH,IAAI,CAACG,qBAAqB;IACjDC,kBAAkB,EAAEJ,IAAI,CAACI,kBAAkB;IAC3CC,WAAW,EAAEL,IAAI,CAACK,WAAW;IAC7BC,oBAAoB,EAAEN,IAAI,CAACM,oBAAoB;IAC/CC,QAAQ,EAAEP,IAAI,CAACO,QAAQ,IAAI,IAAI,IAAIP,IAAI,CAACO,QAAQ;IAChDC,OAAO,EAAER,IAAI,CAACQ,OAAO;IACrBC,QAAQ,EAAET,IAAI,CAACS,QAAQ;IACvBC,OAAO,EAAEV,IAAI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AGH,gBAAgB,CAACC,IAAI,EAAEC,IAAI,CAAC;EAC3C,MAAM8C,GAAG,GAAG9C,IAAI,CAACyC,UAAU,GAAG,IAAIC,kBAAS,CAAC1C,IAAI,EAAED,IAAI,CAAC,GAAG,IAAI;EAE9D,MAAM6C,OAAO,GAAG,IAAIC,gBAAO,CAAC5C,MAAM,EAAE6C,GAAG,CAAC;EAExC,OAAOF,OAAO,CAACD,QAAQ,CAACN,GAAG,CAAC;AAC9B","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/node/index.js b/node_modules/@babel/generator/lib/node/index.js new file mode 100644 index 0000000..b564050 --- /dev/null +++ b/node_modules/@babel/generator/lib/node/index.js @@ -0,0 +1,101 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TokenContext = void 0; +exports.needsParens = needsParens; +exports.needsWhitespace = needsWhitespace; +exports.needsWhitespaceAfter = needsWhitespaceAfter; +exports.needsWhitespaceBefore = needsWhitespaceBefore; +var whitespace = require("./whitespace.js"); +var parens = require("./parentheses.js"); +var _t = require("@babel/types"); +const { + FLIPPED_ALIAS_KEYS, + isCallExpression, + isDecorator, + isExpressionStatement, + isMemberExpression, + isNewExpression, + isParenthesizedExpression +} = _t; +const TokenContext = exports.TokenContext = { + expressionStatement: 1, + arrowBody: 2, + exportDefault: 4, + forHead: 8, + forInHead: 16, + forOfHead: 32, + arrowFlowReturnType: 64 +}; +function expandAliases(obj) { + const map = new Map(); + function add(type, func) { + const fn = map.get(type); + map.set(type, fn ? function (node, parent, stack, inForInit) { + var _fn; + return (_fn = fn(node, parent, stack, inForInit)) != null ? _fn : func(node, parent, stack, inForInit); + } : func); + } + for (const type of Object.keys(obj)) { + const aliases = FLIPPED_ALIAS_KEYS[type]; + if (aliases) { + for (const alias of aliases) { + add(alias, obj[type]); + } + } else { + add(type, obj[type]); + } + } + return map; +} +const expandedParens = expandAliases(parens); +const expandedWhitespaceNodes = expandAliases(whitespace.nodes); +function isOrHasCallExpression(node) { + if (isCallExpression(node)) { + return true; + } + return isMemberExpression(node) && isOrHasCallExpression(node.object); +} +function needsWhitespace(node, parent, type) { + var _expandedWhitespaceNo; + if (!node) return false; + if (isExpressionStatement(node)) { + node = node.expression; + } + const flag = (_expandedWhitespaceNo = expandedWhitespaceNodes.get(node.type)) == null ? void 0 : _expandedWhitespaceNo(node, parent); + if (typeof flag === "number") { + return (flag & type) !== 0; + } + return false; +} +function needsWhitespaceBefore(node, parent) { + return needsWhitespace(node, parent, 1); +} +function needsWhitespaceAfter(node, parent) { + return needsWhitespace(node, parent, 2); +} +function needsParens(node, parent, tokenContext, inForInit) { + var _expandedParens$get; + if (!parent) return false; + if (isNewExpression(parent) && parent.callee === node) { + if (isOrHasCallExpression(node)) return true; + } + if (isDecorator(parent)) { + return !isDecoratorMemberExpression(node) && !(isCallExpression(node) && isDecoratorMemberExpression(node.callee)) && !isParenthesizedExpression(node); + } + return (_expandedParens$get = expandedParens.get(node.type)) == null ? void 0 : _expandedParens$get(node, parent, tokenContext, inForInit); +} +function isDecoratorMemberExpression(node) { + switch (node.type) { + case "Identifier": + return true; + case "MemberExpression": + return !node.computed && node.property.type === "Identifier" && isDecoratorMemberExpression(node.object); + default: + return false; + } +} + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/generator/lib/node/index.js.map b/node_modules/@babel/generator/lib/node/index.js.map new file mode 100644 index 0000000..9603a6e --- /dev/null +++ b/node_modules/@babel/generator/lib/node/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["whitespace","require","parens","_t","FLIPPED_ALIAS_KEYS","isCallExpression","isDecorator","isExpressionStatement","isMemberExpression","isNewExpression","isParenthesizedExpression","TokenContext","exports","expressionStatement","arrowBody","exportDefault","forHead","forInHead","forOfHead","arrowFlowReturnType","expandAliases","obj","map","Map","add","type","func","fn","get","set","node","parent","stack","inForInit","_fn","Object","keys","aliases","alias","expandedParens","expandedWhitespaceNodes","nodes","isOrHasCallExpression","object","needsWhitespace","_expandedWhitespaceNo","expression","flag","needsWhitespaceBefore","needsWhitespaceAfter","needsParens","tokenContext","_expandedParens$get","callee","isDecoratorMemberExpression","computed","property"],"sources":["../../src/node/index.ts"],"sourcesContent":["import * as whitespace from \"./whitespace.ts\";\nimport * as parens from \"./parentheses.ts\";\nimport {\n FLIPPED_ALIAS_KEYS,\n isCallExpression,\n isDecorator,\n isExpressionStatement,\n isMemberExpression,\n isNewExpression,\n isParenthesizedExpression,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\n\nimport type { WhitespaceFlag } from \"./whitespace.ts\";\n\nexport const enum TokenContext {\n expressionStatement = 1 << 0,\n arrowBody = 1 << 1,\n exportDefault = 1 << 2,\n forHead = 1 << 3,\n forInHead = 1 << 4,\n forOfHead = 1 << 5,\n arrowFlowReturnType = 1 << 6,\n}\n\ntype NodeHandler = (\n node: t.Node,\n // todo:\n // node: K extends keyof typeof t\n // ? Extract\n // : t.Node,\n parent: t.Node,\n tokenContext?: number,\n inForStatementInit?: boolean,\n) => R;\n\nexport type NodeHandlers = {\n [K in string]?: NodeHandler;\n};\n\nfunction expandAliases(obj: NodeHandlers) {\n const map = new Map>();\n\n function add(type: string, func: NodeHandler) {\n const fn = map.get(type);\n map.set(\n type,\n fn\n ? function (node, parent, stack, inForInit) {\n return (\n fn(node, parent, stack, inForInit) ??\n func(node, parent, stack, inForInit)\n );\n }\n : func,\n );\n }\n\n for (const type of Object.keys(obj)) {\n const aliases = FLIPPED_ALIAS_KEYS[type];\n if (aliases) {\n for (const alias of aliases) {\n add(alias, obj[type]);\n }\n } else {\n add(type, obj[type]);\n }\n }\n\n return map;\n}\n\n// Rather than using `t.is` on each object property, we pre-expand any type aliases\n// into concrete types so that the 'find' call below can be as fast as possible.\nconst expandedParens = expandAliases(parens);\nconst expandedWhitespaceNodes = expandAliases(whitespace.nodes);\n\nfunction isOrHasCallExpression(node: t.Node): boolean {\n if (isCallExpression(node)) {\n return true;\n }\n\n return isMemberExpression(node) && isOrHasCallExpression(node.object);\n}\n\nexport function needsWhitespace(\n node: t.Node,\n parent: t.Node,\n type: WhitespaceFlag,\n): boolean {\n if (!node) return false;\n\n if (isExpressionStatement(node)) {\n node = node.expression;\n }\n\n const flag = expandedWhitespaceNodes.get(node.type)?.(node, parent);\n\n if (typeof flag === \"number\") {\n return (flag & type) !== 0;\n }\n\n return false;\n}\n\nexport function needsWhitespaceBefore(node: t.Node, parent: t.Node) {\n return needsWhitespace(node, parent, 1);\n}\n\nexport function needsWhitespaceAfter(node: t.Node, parent: t.Node) {\n return needsWhitespace(node, parent, 2);\n}\n\nexport function needsParens(\n node: t.Node,\n parent: t.Node,\n tokenContext?: number,\n inForInit?: boolean,\n) {\n if (!parent) return false;\n\n if (isNewExpression(parent) && parent.callee === node) {\n if (isOrHasCallExpression(node)) return true;\n }\n\n if (isDecorator(parent)) {\n return (\n !isDecoratorMemberExpression(node) &&\n !(isCallExpression(node) && isDecoratorMemberExpression(node.callee)) &&\n !isParenthesizedExpression(node)\n );\n }\n\n return expandedParens.get(node.type)?.(node, parent, tokenContext, inForInit);\n}\n\nfunction isDecoratorMemberExpression(node: t.Node): boolean {\n switch (node.type) {\n case \"Identifier\":\n return true;\n case \"MemberExpression\":\n return (\n !node.computed &&\n node.property.type === \"Identifier\" &&\n isDecoratorMemberExpression(node.object)\n );\n default:\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;AAAA,IAAAA,UAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,EAAA,GAAAF,OAAA;AAQsB;EAPpBG,kBAAkB;EAClBC,gBAAgB;EAChBC,WAAW;EACXC,qBAAqB;EACrBC,kBAAkB;EAClBC,eAAe;EACfC;AAAyB,IAAAP,EAAA;AAAA,MAMTQ,YAAY,GAAAC,OAAA,CAAAD,YAAA;EAAAE,mBAAA;EAAAC,SAAA;EAAAC,aAAA;EAAAC,OAAA;EAAAC,SAAA;EAAAC,SAAA;EAAAC,mBAAA;AAAA;AAyB9B,SAASC,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I,CAACuB,MAAM,CAAC,CAAC,IACrE,CAAC3C,yBAAyB,CAACoB,IAAI,CAAC;EAEpC;EAEA,QAAAsB,mBAAA,GAAOb,cAAc,CAACX,GAAG,CAACE,IAAI,CAACL,IAAI,CAAC,qBAA7B2B,mBAAA,CAAgCtB,IAAI,EAAEC,MAAM,EAAEoB,YAAY,EAAElB,SAAS,CAAC;AAC/E;AAEA,SAASqB,2BAA2BA,CAACxB,IAAY,EAAW;EAC1D,QAAQA,IAAI,CAACL,IAAI;IACf,KAAK,YAAY;MACf,OAAO,IAAI;IACb,KAAK,kBAAkB;MACrB,OACE,CAACK,IAAI,CAACyB,QAAQ,IACdzB,IAAI,CAAC0B,QAAQ,CAAC/B,IAAI,KAAK,YAAY,IACnC6B,2BAA2B,CAACxB,IAAI,CAACa,MAAM,CAAC;IAE5C;MACE,OAAO,KAAK;EAChB;AACF","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/node/parentheses.js b/node_modules/@babel/generator/lib/node/parentheses.js new file mode 100644 index 0000000..37514b0 --- /dev/null +++ b/node_modules/@babel/generator/lib/node/parentheses.js @@ -0,0 +1,221 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AssignmentExpression = AssignmentExpression; +exports.Binary = Binary; +exports.BinaryExpression = BinaryExpression; +exports.ClassExpression = ClassExpression; +exports.ArrowFunctionExpression = exports.ConditionalExpression = ConditionalExpression; +exports.DoExpression = DoExpression; +exports.FunctionExpression = FunctionExpression; +exports.FunctionTypeAnnotation = FunctionTypeAnnotation; +exports.Identifier = Identifier; +exports.LogicalExpression = LogicalExpression; +exports.NullableTypeAnnotation = NullableTypeAnnotation; +exports.ObjectExpression = ObjectExpression; +exports.OptionalIndexedAccessType = OptionalIndexedAccessType; +exports.OptionalCallExpression = exports.OptionalMemberExpression = OptionalMemberExpression; +exports.SequenceExpression = SequenceExpression; +exports.TSSatisfiesExpression = exports.TSAsExpression = TSAsExpression; +exports.TSInferType = TSInferType; +exports.TSInstantiationExpression = TSInstantiationExpression; +exports.UnaryLike = exports.TSTypeAssertion = UnaryLike; +exports.TSIntersectionType = exports.TSUnionType = TSUnionType; +exports.IntersectionTypeAnnotation = exports.UnionTypeAnnotation = UnionTypeAnnotation; +exports.UpdateExpression = UpdateExpression; +exports.AwaitExpression = exports.YieldExpression = YieldExpression; +var _t = require("@babel/types"); +var _index = require("./index.js"); +const { + isArrayTypeAnnotation, + isBinaryExpression, + isCallExpression, + isForOfStatement, + isIndexedAccessType, + isMemberExpression, + isObjectPattern, + isOptionalMemberExpression, + isYieldExpression, + isStatement +} = _t; +const PRECEDENCE = new Map([["||", 0], ["??", 0], ["|>", 0], ["&&", 1], ["|", 2], ["^", 3], ["&", 4], ["==", 5], ["===", 5], ["!=", 5], ["!==", 5], ["<", 6], [">", 6], ["<=", 6], [">=", 6], ["in", 6], ["instanceof", 6], [">>", 7], ["<<", 7], [">>>", 7], ["+", 8], ["-", 8], ["*", 9], ["/", 9], ["%", 9], ["**", 10]]); +function getBinaryPrecedence(node, nodeType) { + if (nodeType === "BinaryExpression" || nodeType === "LogicalExpression") { + return PRECEDENCE.get(node.operator); + } + if (nodeType === "TSAsExpression" || nodeType === "TSSatisfiesExpression") { + return PRECEDENCE.get("in"); + } +} +function isTSTypeExpression(nodeType) { + return nodeType === "TSAsExpression" || nodeType === "TSSatisfiesExpression" || nodeType === "TSTypeAssertion"; +} +const isClassExtendsClause = (node, parent) => { + const parentType = parent.type; + return (parentType === "ClassDeclaration" || parentType === "ClassExpression") && parent.superClass === node; +}; +const hasPostfixPart = (node, parent) => { + const parentType = parent.type; + return (parentType === "MemberExpression" || parentType === "OptionalMemberExpression") && parent.object === node || (parentType === "CallExpression" || parentType === "OptionalCallExpression" || parentType === "NewExpression") && parent.callee === node || parentType === "TaggedTemplateExpression" && parent.tag === node || parentType === "TSNonNullExpression"; +}; +function NullableTypeAnnotation(node, parent) { + return isArrayTypeAnnotation(parent); +} +function FunctionTypeAnnotation(node, parent, tokenContext) { + const parentType = parent.type; + return parentType === "UnionTypeAnnotation" || parentType === "IntersectionTypeAnnotation" || parentType === "ArrayTypeAnnotation" || Boolean(tokenContext & _index.TokenContext.arrowFlowReturnType); +} +function UpdateExpression(node, parent) { + return hasPostfixPart(node, parent) || isClassExtendsClause(node, parent); +} +function needsParenBeforeExpressionBrace(tokenContext) { + return Boolean(tokenContext & (_index.TokenContext.expressionStatement | _index.TokenContext.arrowBody)); +} +function ObjectExpression(node, parent, tokenContext) { + return needsParenBeforeExpressionBrace(tokenContext); +} +function DoExpression(node, parent, tokenContext) { + return !node.async && Boolean(tokenContext & _index.TokenContext.expressionStatement); +} +function Binary(node, parent) { + const parentType = parent.type; + if (node.type === "BinaryExpression" && node.operator === "**" && parentType === "BinaryExpression" && parent.operator === "**") { + return parent.left === node; + } + if (isClassExtendsClause(node, parent)) { + return true; + } + if (hasPostfixPart(node, parent) || parentType === "UnaryExpression" || parentType === "SpreadElement" || parentType === "AwaitExpression") { + return true; + } + const parentPos = getBinaryPrecedence(parent, parentType); + if (parentPos != null) { + const nodePos = getBinaryPrecedence(node, node.type); + if (parentPos === nodePos && parentType === "BinaryExpression" && parent.right === node || parentPos > nodePos) { + return true; + } + } + return undefined; +} +function UnionTypeAnnotation(node, parent) { + const parentType = parent.type; + return parentType === "ArrayTypeAnnotation" || parentType === "NullableTypeAnnotation" || parentType === "IntersectionTypeAnnotation" || parentType === "UnionTypeAnnotation"; +} +function OptionalIndexedAccessType(node, parent) { + return isIndexedAccessType(parent) && parent.objectType === node; +} +function TSAsExpression(node, parent) { + if ((parent.type === "AssignmentExpression" || parent.type === "AssignmentPattern") && parent.left === node) { + return true; + } + if (parent.type === "BinaryExpression" && (parent.operator === "|" || parent.operator === "&") && node === parent.left) { + return true; + } + return Binary(node, parent); +} +function TSUnionType(node, parent) { + const parentType = parent.type; + return parentType === "TSArrayType" || parentType === "TSOptionalType" || parentType === "TSIntersectionType" || parentType === "TSRestType"; +} +function TSInferType(node, parent) { + const parentType = parent.type; + return parentType === "TSArrayType" || parentType === "TSOptionalType"; +} +function TSInstantiationExpression(node, parent) { + const parentType = parent.type; + return (parentType === "CallExpression" || parentType === "OptionalCallExpression" || parentType === "NewExpression" || parentType === "TSInstantiationExpression") && !!parent.typeParameters; +} +function BinaryExpression(node, parent, tokenContext, inForStatementInit) { + return node.operator === "in" && inForStatementInit; +} +function SequenceExpression(node, parent) { + const parentType = parent.type; + if (parentType === "SequenceExpression" || parentType === "ParenthesizedExpression" || parentType === "MemberExpression" && parent.property === node || parentType === "OptionalMemberExpression" && parent.property === node || parentType === "TemplateLiteral") { + return false; + } + if (parentType === "ClassDeclaration") { + return true; + } + if (parentType === "ForOfStatement") { + return parent.right === node; + } + if (parentType === "ExportDefaultDeclaration") { + return true; + } + return !isStatement(parent); +} +function YieldExpression(node, parent) { + const parentType = parent.type; + return parentType === "BinaryExpression" || parentType === "LogicalExpression" || parentType === "UnaryExpression" || parentType === "SpreadElement" || hasPostfixPart(node, parent) || parentType === "AwaitExpression" && isYieldExpression(node) || parentType === "ConditionalExpression" && node === parent.test || isClassExtendsClause(node, parent) || isTSTypeExpression(parentType); +} +function ClassExpression(node, parent, tokenContext) { + return Boolean(tokenContext & (_index.TokenContext.expressionStatement | _index.TokenContext.exportDefault)); +} +function UnaryLike(node, parent) { + return hasPostfixPart(node, parent) || isBinaryExpression(parent) && parent.operator === "**" && parent.left === node || isClassExtendsClause(node, parent); +} +function FunctionExpression(node, parent, tokenContext) { + return Boolean(tokenContext & (_index.TokenContext.expressionStatement | _index.TokenContext.exportDefault)); +} +function ConditionalExpression(node, parent) { + const parentType = parent.type; + if (parentType === "UnaryExpression" || parentType === "SpreadElement" || parentType === "BinaryExpression" || parentType === "LogicalExpression" || parentType === "ConditionalExpression" && parent.test === node || parentType === "AwaitExpression" || isTSTypeExpression(parentType)) { + return true; + } + return UnaryLike(node, parent); +} +function OptionalMemberExpression(node, parent) { + return isCallExpression(parent) && parent.callee === node || isMemberExpression(parent) && parent.object === node; +} +function AssignmentExpression(node, parent, tokenContext) { + if (needsParenBeforeExpressionBrace(tokenContext) && isObjectPattern(node.left)) { + return true; + } else { + return ConditionalExpression(node, parent); + } +} +function LogicalExpression(node, parent) { + const parentType = parent.type; + if (isTSTypeExpression(parentType)) return true; + if (parentType !== "LogicalExpression") return false; + switch (node.operator) { + case "||": + return parent.operator === "??" || parent.operator === "&&"; + case "&&": + return parent.operator === "??"; + case "??": + return parent.operator !== "??"; + } +} +function Identifier(node, parent, tokenContext) { + var _node$extra; + const parentType = parent.type; + if ((_node$extra = node.extra) != null && _node$extra.parenthesized && parentType === "AssignmentExpression" && parent.left === node) { + const rightType = parent.right.type; + if ((rightType === "FunctionExpression" || rightType === "ClassExpression") && parent.right.id == null) { + return true; + } + } + if (node.name === "let") { + const isFollowedByBracket = isMemberExpression(parent, { + object: node, + computed: true + }) || isOptionalMemberExpression(parent, { + object: node, + computed: true, + optional: false + }); + if (isFollowedByBracket && tokenContext & (_index.TokenContext.expressionStatement | _index.TokenContext.forHead | _index.TokenContext.forInHead)) { + return true; + } + return Boolean(tokenContext & _index.TokenContext.forOfHead); + } + return node.name === "async" && isForOfStatement(parent, { + left: node, + await: false + }); +} + +//# sourceMappingURL=parentheses.js.map diff --git a/node_modules/@babel/generator/lib/node/parentheses.js.map b/node_modules/@babel/generator/lib/node/parentheses.js.map new file mode 100644 index 0000000..18577d6 --- /dev/null +++ b/node_modules/@babel/generator/lib/node/parentheses.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_t","require","_index","isArrayTypeAnnotation","isBinaryExpression","isCallExpression","isForOfStatement","isIndexedAccessType","isMemberExpression","isObjectPattern","isOptionalMemberExpression","isYieldExpression","isStatement","PRECEDENCE","Map","getBinaryPrecedence","node","nodeType","get","operator","isTSTypeExpression","isClassExtendsClause","parent","parentType","type","superClass","hasPostfixPart","object","callee","tag","NullableTypeAnnotation","FunctionTypeAnnotation","tokenContext","Boolean","TokenContext","arrowFlowReturnType","UpdateExpression","needsParenBeforeExpressionBrace","expressionStatement","arrowBody","ObjectExpression","DoExpression","async","Binary","left","parentPos","nodePos","right","undefined","UnionTypeAnnotation","OptionalIndexedAccessType","objectType","TSAsExpression","TSUnionType","TSInferType","TSInstantiationExpression","typeParameters","BinaryExpression","inForStatementInit","SequenceExpression","property","YieldExpression","test","ClassExpression","exportDefault","UnaryLike","FunctionExpression","ConditionalExpression","OptionalMemberExpression","AssignmentExpression","LogicalExpression","Identifier","_node$extra","extra","parenthesized","rightType","id","name","isFollowedByBracket","computed","optional","forHead","forInHead","forOfHead","await"],"sources":["../../src/node/parentheses.ts"],"sourcesContent":["import {\n isArrayTypeAnnotation,\n isBinaryExpression,\n isCallExpression,\n isForOfStatement,\n isIndexedAccessType,\n isMemberExpression,\n isObjectPattern,\n isOptionalMemberExpression,\n isYieldExpression,\n isStatement,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\n\nimport { TokenContext } from \"./index.ts\";\n\nconst PRECEDENCE = new Map([\n [\"||\", 0],\n [\"??\", 0],\n [\"|>\", 0],\n [\"&&\", 1],\n [\"|\", 2],\n [\"^\", 3],\n [\"&\", 4],\n [\"==\", 5],\n [\"===\", 5],\n [\"!=\", 5],\n [\"!==\", 5],\n [\"<\", 6],\n [\">\", 6],\n [\"<=\", 6],\n [\">=\", 6],\n [\"in\", 6],\n [\"instanceof\", 6],\n [\">>\", 7],\n [\"<<\", 7],\n [\">>>\", 7],\n [\"+\", 8],\n [\"-\", 8],\n [\"*\", 9],\n [\"/\", 9],\n [\"%\", 9],\n [\"**\", 10],\n]);\n\nfunction getBinaryPrecedence(\n node: t.Binary | t.TSAsExpression | t.TSSatisfiesExpression,\n nodeType: string,\n): number;\nfunction getBinaryPrecedence(\n node: t.Node,\n nodeType: string,\n): number | undefined;\nfunction getBinaryPrecedence(node: t.Node, nodeType: string) {\n if (nodeType === \"BinaryExpression\" || nodeType === \"LogicalExpression\") {\n return PRECEDENCE.get((node as t.Binary).operator);\n }\n if (nodeType === \"TSAsExpression\" || nodeType === \"TSSatisfiesExpression\") {\n return PRECEDENCE.get(\"in\");\n }\n}\n\nfunction isTSTypeExpression(nodeType: string) {\n return (\n nodeType === \"TSAsExpression\" ||\n nodeType === \"TSSatisfiesExpression\" ||\n nodeType === \"TSTypeAssertion\"\n );\n}\n\nconst isClassExtendsClause = (\n node: t.Node,\n parent: t.Node,\n): parent is t.Class => {\n const parentType = parent.type;\n return (\n (parentType === \"ClassDeclaration\" || parentType === \"ClassExpression\") &&\n parent.superClass === node\n );\n};\n\nconst hasPostfixPart = (node: t.Node, parent: t.Node) => {\n const parentType = parent.type;\n return (\n ((parentType === \"MemberExpression\" ||\n parentType === \"OptionalMemberExpression\") &&\n parent.object === node) ||\n ((parentType === \"CallExpression\" ||\n parentType === \"OptionalCallExpression\" ||\n parentType === \"NewExpression\") &&\n parent.callee === node) ||\n (parentType === \"TaggedTemplateExpression\" && parent.tag === node) ||\n parentType === \"TSNonNullExpression\"\n );\n};\n\nexport function NullableTypeAnnotation(\n node: t.NullableTypeAnnotation,\n parent: t.Node,\n): boolean {\n return isArrayTypeAnnotation(parent);\n}\n\nexport function FunctionTypeAnnotation(\n node: t.FunctionTypeAnnotation,\n parent: t.Node,\n tokenContext: number,\n): boolean {\n const parentType = parent.type;\n return (\n // (() => A) | (() => B)\n parentType === \"UnionTypeAnnotation\" ||\n // (() => A) & (() => B)\n parentType === \"IntersectionTypeAnnotation\" ||\n // (() => A)[]\n parentType === \"ArrayTypeAnnotation\" ||\n Boolean(tokenContext & TokenContext.arrowFlowReturnType)\n );\n}\n\nexport function UpdateExpression(\n node: t.UpdateExpression,\n parent: t.Node,\n): boolean {\n return hasPostfixPart(node, parent) || isClassExtendsClause(node, parent);\n}\n\nfunction needsParenBeforeExpressionBrace(tokenContext: number) {\n return Boolean(\n tokenContext & (TokenContext.expressionStatement | TokenContext.arrowBody),\n );\n}\n\nexport function ObjectExpression(\n node: t.ObjectExpression,\n parent: t.Node,\n tokenContext: number,\n): boolean {\n return needsParenBeforeExpressionBrace(tokenContext);\n}\n\nexport function DoExpression(\n node: t.DoExpression,\n parent: t.Node,\n tokenContext: number,\n): boolean {\n // `async do` can start an expression statement\n return (\n !node.async && Boolean(tokenContext & TokenContext.expressionStatement)\n );\n}\n\nexport function Binary(\n node: t.Binary | t.TSAsExpression | t.TSSatisfiesExpression,\n parent: t.Node,\n): boolean | undefined {\n const parentType = parent.type;\n if (\n node.type === \"BinaryExpression\" &&\n node.operator === \"**\" &&\n parentType === \"BinaryExpression\" &&\n parent.operator === \"**\"\n ) {\n return parent.left === node;\n }\n\n if (isClassExtendsClause(node, parent)) {\n return true;\n }\n\n if (\n hasPostfixPart(node, parent) ||\n parentType === \"UnaryExpression\" ||\n parentType === \"SpreadElement\" ||\n parentType === \"AwaitExpression\"\n ) {\n return true;\n }\n\n const parentPos = getBinaryPrecedence(parent, parentType);\n if (parentPos != null) {\n const nodePos = getBinaryPrecedence(node, node.type);\n if (\n // Logical expressions with the same precedence don't need parens.\n (parentPos === nodePos &&\n parentType === \"BinaryExpression\" &&\n parent.right === node) ||\n parentPos > nodePos\n ) {\n return true;\n }\n }\n\n return undefined;\n}\n\nexport function UnionTypeAnnotation(\n node: t.UnionTypeAnnotation,\n parent: t.Node,\n): boolean {\n const parentType = parent.type;\n return (\n parentType === \"ArrayTypeAnnotation\" ||\n parentType === \"NullableTypeAnnotation\" ||\n parentType === \"IntersectionTypeAnnotation\" ||\n parentType === \"UnionTypeAnnotation\"\n );\n}\n\nexport { UnionTypeAnnotation as IntersectionTypeAnnotation };\n\nexport function OptionalIndexedAccessType(\n node: t.OptionalIndexedAccessType,\n parent: t.Node,\n): boolean {\n return isIndexedAccessType(parent) && parent.objectType === node;\n}\n\nexport function TSAsExpression(\n node: t.TSAsExpression | t.TSSatisfiesExpression,\n parent: t.Node,\n): boolean {\n if (\n (parent.type === \"AssignmentExpression\" ||\n parent.type === \"AssignmentPattern\") &&\n parent.left === node\n ) {\n return true;\n }\n if (\n parent.type === \"BinaryExpression\" &&\n (parent.operator === \"|\" || parent.operator === \"&\") &&\n node === parent.left\n ) {\n return true;\n }\n return Binary(node, parent);\n}\n\nexport { TSAsExpression as TSSatisfiesExpression };\n\nexport { UnaryLike as TSTypeAssertion };\n\nexport function TSUnionType(node: t.TSUnionType, parent: t.Node): boolean {\n const parentType = parent.type;\n return (\n parentType === \"TSArrayType\" ||\n parentType === \"TSOptionalType\" ||\n parentType === \"TSIntersectionType\" ||\n parentType === \"TSRestType\"\n );\n}\n\nexport { TSUnionType as TSIntersectionType };\n\nexport function TSInferType(node: t.TSInferType, parent: t.Node): boolean {\n const parentType = parent.type;\n return parentType === \"TSArrayType\" || parentType === \"TSOptionalType\";\n}\n\nexport function TSInstantiationExpression(\n node: t.TSInstantiationExpression,\n parent: t.Node,\n) {\n const parentType = parent.type;\n return (\n (parentType === \"CallExpression\" ||\n parentType === \"OptionalCallExpression\" ||\n parentType === \"NewExpression\" ||\n parentType === \"TSInstantiationExpression\") &&\n !!parent.typeParameters\n );\n}\n\nexport function BinaryExpression(\n node: t.BinaryExpression,\n parent: t.Node,\n tokenContext: unknown,\n inForStatementInit: boolean,\n): boolean {\n // for ((1 in []);;);\n // for (var x = (1 in []) in 2);\n return node.operator === \"in\" && inForStatementInit;\n}\n\nexport function SequenceExpression(\n node: t.SequenceExpression,\n parent: t.Node,\n): boolean {\n const parentType = parent.type;\n if (\n parentType === \"SequenceExpression\" ||\n parentType === \"ParenthesizedExpression\" ||\n (parentType === \"MemberExpression\" && parent.property === node) ||\n (parentType === \"OptionalMemberExpression\" && parent.property === node) ||\n parentType === \"TemplateLiteral\"\n ) {\n return false;\n }\n if (parentType === \"ClassDeclaration\") {\n return true;\n }\n if (parentType === \"ForOfStatement\") {\n return parent.right === node;\n }\n if (parentType === \"ExportDefaultDeclaration\") {\n return true;\n }\n\n return !isStatement(parent);\n}\n\nexport function YieldExpression(\n node: t.YieldExpression,\n parent: t.Node,\n): boolean {\n const parentType = parent.type;\n return (\n parentType === \"BinaryExpression\" ||\n parentType === \"LogicalExpression\" ||\n parentType === \"UnaryExpression\" ||\n parentType === \"SpreadElement\" ||\n hasPostfixPart(node, parent) ||\n (parentType === \"AwaitExpression\" && isYieldExpression(node)) ||\n (parentType === \"ConditionalExpression\" && node === parent.test) ||\n isClassExtendsClause(node, parent) ||\n isTSTypeExpression(parentType)\n );\n}\n\nexport { YieldExpression as AwaitExpression };\n\nexport function ClassExpression(\n node: t.ClassExpression,\n parent: t.Node,\n tokenContext: number,\n): boolean {\n return Boolean(\n tokenContext &\n (TokenContext.expressionStatement | TokenContext.exportDefault),\n );\n}\n\nexport function UnaryLike(\n node:\n | t.UnaryLike\n | t.TSTypeAssertion\n | t.ArrowFunctionExpression\n | t.ConditionalExpression\n | t.AssignmentExpression,\n parent: t.Node,\n): boolean {\n return (\n hasPostfixPart(node, parent) ||\n (isBinaryExpression(parent) &&\n parent.operator === \"**\" &&\n parent.left === node) ||\n isClassExtendsClause(node, parent)\n );\n}\n\nexport function FunctionExpression(\n node: t.FunctionExpression,\n parent: t.Node,\n tokenContext: number,\n): boolean {\n return Boolean(\n tokenContext &\n (TokenContext.expressionStatement | TokenContext.exportDefault),\n );\n}\n\nexport function ConditionalExpression(\n node:\n | t.ConditionalExpression\n | t.ArrowFunctionExpression\n | t.AssignmentExpression,\n parent?: t.Node,\n): boolean {\n const parentType = parent.type;\n if (\n parentType === \"UnaryExpression\" ||\n parentType === \"SpreadElement\" ||\n parentType === \"BinaryExpression\" ||\n parentType === \"LogicalExpression\" ||\n (parentType === \"ConditionalExpression\" && parent.test === node) ||\n parentType === \"AwaitExpression\" ||\n isTSTypeExpression(parentType)\n ) {\n return true;\n }\n\n return UnaryLike(node, parent);\n}\n\nexport { ConditionalExpression as ArrowFunctionExpression };\n\nexport function OptionalMemberExpression(\n node: t.OptionalMemberExpression,\n parent: t.Node,\n): boolean {\n return (\n (isCallExpression(parent) && parent.callee === node) ||\n (isMemberExpression(parent) && parent.object === node)\n );\n}\n\nexport { OptionalMemberExpression as OptionalCallExpression };\n\nexport function AssignmentExpression(\n node: t.AssignmentExpression,\n parent: t.Node,\n tokenContext: number,\n): boolean {\n if (\n needsParenBeforeExpressionBrace(tokenContext) &&\n isObjectPattern(node.left)\n ) {\n return true;\n } else {\n return ConditionalExpression(node, parent);\n }\n}\n\nexport function LogicalExpression(\n node: t.LogicalExpression,\n parent: t.Node,\n): boolean {\n const parentType = parent.type;\n if (isTSTypeExpression(parentType)) return true;\n if (parentType !== \"LogicalExpression\") return false;\n switch (node.operator) {\n case \"||\":\n return parent.operator === \"??\" || parent.operator === \"&&\";\n case \"&&\":\n return parent.operator === \"??\";\n case \"??\":\n return parent.operator !== \"??\";\n }\n}\n\nexport function Identifier(\n node: t.Identifier,\n parent: t.Node,\n tokenContext: number,\n): boolean {\n const parentType = parent.type;\n // 13.15.2 AssignmentExpression RS: Evaluation\n // (fn) = function () {};\n if (\n node.extra?.parenthesized &&\n parentType === \"AssignmentExpression\" &&\n parent.left === node\n ) {\n const rightType = parent.right.type;\n if (\n (rightType === \"FunctionExpression\" || rightType === \"ClassExpression\") &&\n parent.right.id == null\n ) {\n return true;\n }\n }\n // Non-strict code allows the identifier `let`, but it cannot occur as-is in\n // certain contexts to avoid ambiguity with contextual keyword `let`.\n if (node.name === \"let\") {\n // Some contexts only forbid `let [`, so check if the next token would\n // be the left bracket of a computed member expression.\n const isFollowedByBracket =\n isMemberExpression(parent, {\n object: node,\n computed: true,\n }) ||\n isOptionalMemberExpression(parent, {\n object: node,\n computed: true,\n optional: false,\n });\n if (\n isFollowedByBracket &&\n tokenContext &\n (TokenContext.expressionStatement |\n TokenContext.forHead |\n TokenContext.forInHead)\n ) {\n return true;\n }\n return Boolean(tokenContext & TokenContext.forOfHead);\n }\n\n // ECMAScript specifically forbids a for-of loop from starting with the\n // token sequence `for (async of`, because it would be ambiguous with\n // `for (async of => {};;)`, so we need to add extra parentheses.\n return (\n node.name === \"async\" &&\n isForOfStatement(parent, { left: node, await: false })\n );\n}\n"],"mappings":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AAY,CAACI,mBAAmB,GAC/BJ,mBAAY,CAAC+C,OAAO,GACpB/C,mBAAY,CAACgD,SAAS,CAAC,EAC3B;MACA,OAAO,IAAI;IACb;IACA,OAAOjD,OAAO,CAACD,YAAY,GAAGE,mBAAY,CAACiD,SAAS,CAAC;EACvD;EAKA,OACEnE,IAAI,CAAC6D,IAAI,KAAK,OAAO,IACrBvE,gBAAgB,CAACgB,MAAM,EAAE;IAAEsB,IAAI,EAAE5B,IAAI;IAAEoE,KAAK,EAAE;EAAM,CAAC,CAAC;AAE1D","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/node/whitespace.js b/node_modules/@babel/generator/lib/node/whitespace.js new file mode 100644 index 0000000..181b956 --- /dev/null +++ b/node_modules/@babel/generator/lib/node/whitespace.js @@ -0,0 +1,145 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.nodes = void 0; +var _t = require("@babel/types"); +const { + FLIPPED_ALIAS_KEYS, + isArrayExpression, + isAssignmentExpression, + isBinary, + isBlockStatement, + isCallExpression, + isFunction, + isIdentifier, + isLiteral, + isMemberExpression, + isObjectExpression, + isOptionalCallExpression, + isOptionalMemberExpression, + isStringLiteral +} = _t; +function crawlInternal(node, state) { + if (!node) return state; + if (isMemberExpression(node) || isOptionalMemberExpression(node)) { + crawlInternal(node.object, state); + if (node.computed) crawlInternal(node.property, state); + } else if (isBinary(node) || isAssignmentExpression(node)) { + crawlInternal(node.left, state); + crawlInternal(node.right, state); + } else if (isCallExpression(node) || isOptionalCallExpression(node)) { + state.hasCall = true; + crawlInternal(node.callee, state); + } else if (isFunction(node)) { + state.hasFunction = true; + } else if (isIdentifier(node)) { + state.hasHelper = state.hasHelper || node.callee && isHelper(node.callee); + } + return state; +} +function crawl(node) { + return crawlInternal(node, { + hasCall: false, + hasFunction: false, + hasHelper: false + }); +} +function isHelper(node) { + if (!node) return false; + if (isMemberExpression(node)) { + return isHelper(node.object) || isHelper(node.property); + } else if (isIdentifier(node)) { + return node.name === "require" || node.name.charCodeAt(0) === 95; + } else if (isCallExpression(node)) { + return isHelper(node.callee); + } else if (isBinary(node) || isAssignmentExpression(node)) { + return isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right); + } else { + return false; + } +} +function isType(node) { + return isLiteral(node) || isObjectExpression(node) || isArrayExpression(node) || isIdentifier(node) || isMemberExpression(node); +} +const nodes = exports.nodes = { + AssignmentExpression(node) { + const state = crawl(node.right); + if (state.hasCall && state.hasHelper || state.hasFunction) { + return state.hasFunction ? 1 | 2 : 2; + } + }, + SwitchCase(node, parent) { + return (!!node.consequent.length || parent.cases[0] === node ? 1 : 0) | (!node.consequent.length && parent.cases[parent.cases.length - 1] === node ? 2 : 0); + }, + LogicalExpression(node) { + if (isFunction(node.left) || isFunction(node.right)) { + return 2; + } + }, + Literal(node) { + if (isStringLiteral(node) && node.value === "use strict") { + return 2; + } + }, + CallExpression(node) { + if (isFunction(node.callee) || isHelper(node)) { + return 1 | 2; + } + }, + OptionalCallExpression(node) { + if (isFunction(node.callee)) { + return 1 | 2; + } + }, + VariableDeclaration(node) { + for (let i = 0; i < node.declarations.length; i++) { + const declar = node.declarations[i]; + let enabled = isHelper(declar.id) && !isType(declar.init); + if (!enabled && declar.init) { + const state = crawl(declar.init); + enabled = isHelper(declar.init) && state.hasCall || state.hasFunction; + } + if (enabled) { + return 1 | 2; + } + } + }, + IfStatement(node) { + if (isBlockStatement(node.consequent)) { + return 1 | 2; + } + } +}; +nodes.ObjectProperty = nodes.ObjectTypeProperty = nodes.ObjectMethod = function (node, parent) { + if (parent.properties[0] === node) { + return 1; + } +}; +nodes.ObjectTypeCallProperty = function (node, parent) { + var _parent$properties; + if (parent.callProperties[0] === node && !((_parent$properties = parent.properties) != null && _parent$properties.length)) { + return 1; + } +}; +nodes.ObjectTypeIndexer = function (node, parent) { + var _parent$properties2, _parent$callPropertie; + if (parent.indexers[0] === node && !((_parent$properties2 = parent.properties) != null && _parent$properties2.length) && !((_parent$callPropertie = parent.callProperties) != null && _parent$callPropertie.length)) { + return 1; + } +}; +nodes.ObjectTypeInternalSlot = function (node, parent) { + var _parent$properties3, _parent$callPropertie2, _parent$indexers; + if (parent.internalSlots[0] === node && !((_parent$properties3 = parent.properties) != null && _parent$properties3.length) && !((_parent$callPropertie2 = parent.callProperties) != null && _parent$callPropertie2.length) && !((_parent$indexers = parent.indexers) != null && _parent$indexers.length)) { + return 1; + } +}; +[["Function", true], ["Class", true], ["Loop", true], ["LabeledStatement", true], ["SwitchStatement", true], ["TryStatement", true]].forEach(function ([type, amounts]) { + [type].concat(FLIPPED_ALIAS_KEYS[type] || []).forEach(function (type) { + const ret = amounts ? 1 | 2 : 0; + nodes[type] = () => ret; + }); +}); + +//# sourceMappingURL=whitespace.js.map diff --git a/node_modules/@babel/generator/lib/node/whitespace.js.map b/node_modules/@babel/generator/lib/node/whitespace.js.map new file mode 100644 index 0000000..dea7ddc --- /dev/null +++ b/node_modules/@babel/generator/lib/node/whitespace.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_t","require","FLIPPED_ALIAS_KEYS","isArrayExpression","isAssignmentExpression","isBinary","isBlockStatement","isCallExpression","isFunction","isIdentifier","isLiteral","isMemberExpression","isObjectExpression","isOptionalCallExpression","isOptionalMemberExpression","isStringLiteral","crawlInternal","node","state","object","computed","property","left","right","hasCall","callee","hasFunction","hasHelper","isHelper","crawl","name","charCodeAt","isType","nodes","exports","AssignmentExpression","SwitchCase","parent","consequent","length","cases","LogicalExpression","Literal","value","CallExpression","OptionalCallExpression","VariableDeclaration","i","declarations","declar","enabled","id","init","IfStatement","ObjectProperty","ObjectTypeProperty","ObjectMethod","properties","ObjectTypeCallProperty","_parent$properties","callProperties","ObjectTypeIndexer","_parent$properties2","_parent$callPropertie","indexers","ObjectTypeInternalSlot","_parent$properties3","_parent$callPropertie2","_parent$indexers","internalSlots","forEach","type","amounts","concat","ret"],"sources":["../../src/node/whitespace.ts"],"sourcesContent":["import {\n FLIPPED_ALIAS_KEYS,\n isArrayExpression,\n isAssignmentExpression,\n isBinary,\n isBlockStatement,\n isCallExpression,\n isFunction,\n isIdentifier,\n isLiteral,\n isMemberExpression,\n isObjectExpression,\n isOptionalCallExpression,\n isOptionalMemberExpression,\n isStringLiteral,\n} from \"@babel/types\";\n\n// We inline this package\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport * as charCodes from \"charcodes\";\n\nimport type { NodeHandlers } from \"./index.ts\";\n\nimport type * as t from \"@babel/types\";\n\nconst enum WhitespaceFlag {\n before = 1 << 0,\n after = 1 << 1,\n}\n\nexport type { WhitespaceFlag };\n\nfunction crawlInternal(\n node: t.Node,\n state: { hasCall: boolean; hasFunction: boolean; hasHelper: boolean },\n) {\n if (!node) return state;\n\n if (isMemberExpression(node) || isOptionalMemberExpression(node)) {\n crawlInternal(node.object, state);\n if (node.computed) crawlInternal(node.property, state);\n } else if (isBinary(node) || isAssignmentExpression(node)) {\n crawlInternal(node.left, state);\n crawlInternal(node.right, state);\n } else if (isCallExpression(node) || isOptionalCallExpression(node)) {\n state.hasCall = true;\n crawlInternal(node.callee, state);\n } else if (isFunction(node)) {\n state.hasFunction = true;\n } else if (isIdentifier(node)) {\n state.hasHelper =\n // @ts-expect-error todo(flow->ts): node.callee is not really expected here…\n state.hasHelper || (node.callee && isHelper(node.callee));\n }\n\n return state;\n}\n\n/**\n * Crawl a node to test if it contains a CallExpression, a Function, or a Helper.\n *\n * @example\n * crawl(node)\n * // { hasCall: false, hasFunction: true, hasHelper: false }\n */\n\nfunction crawl(node: t.Node) {\n return crawlInternal(node, {\n hasCall: false,\n hasFunction: false,\n hasHelper: false,\n });\n}\n\n/**\n * Test if a node is or has a helper.\n */\n\nfunction isHelper(node: t.Node): boolean {\n if (!node) return false;\n\n if (isMemberExpression(node)) {\n return isHelper(node.object) || isHelper(node.property);\n } else if (isIdentifier(node)) {\n return (\n node.name === \"require\" ||\n node.name.charCodeAt(0) === charCodes.underscore\n );\n } else if (isCallExpression(node)) {\n return isHelper(node.callee);\n } else if (isBinary(node) || isAssignmentExpression(node)) {\n return (\n (isIdentifier(node.left) && isHelper(node.left)) || isHelper(node.right)\n );\n } else {\n return false;\n }\n}\n\nfunction isType(node: t.Node) {\n return (\n isLiteral(node) ||\n isObjectExpression(node) ||\n isArrayExpression(node) ||\n isIdentifier(node) ||\n isMemberExpression(node)\n );\n}\n\n/**\n * Tests for node types that need whitespace.\n */\n\nexport const nodes: NodeHandlers = {\n /**\n * Test if AssignmentExpression needs whitespace.\n */\n\n AssignmentExpression(node: t.AssignmentExpression): WhitespaceFlag {\n const state = crawl(node.right);\n if ((state.hasCall && state.hasHelper) || state.hasFunction) {\n return state.hasFunction\n ? WhitespaceFlag.before | WhitespaceFlag.after\n : WhitespaceFlag.after;\n }\n },\n\n /**\n * Test if SwitchCase needs whitespace.\n */\n\n SwitchCase(node: t.SwitchCase, parent: t.SwitchStatement): WhitespaceFlag {\n return (\n (!!node.consequent.length || parent.cases[0] === node\n ? WhitespaceFlag.before\n : 0) |\n (!node.consequent.length && parent.cases[parent.cases.length - 1] === node\n ? WhitespaceFlag.after\n : 0)\n );\n },\n\n /**\n * Test if LogicalExpression needs whitespace.\n */\n\n LogicalExpression(node: t.LogicalExpression): WhitespaceFlag {\n if (isFunction(node.left) || isFunction(node.right)) {\n return WhitespaceFlag.after;\n }\n },\n\n /**\n * Test if Literal needs whitespace.\n */\n\n Literal(node: t.Literal): WhitespaceFlag {\n if (isStringLiteral(node) && node.value === \"use strict\") {\n return WhitespaceFlag.after;\n }\n },\n\n /**\n * Test if CallExpressionish needs whitespace.\n */\n\n CallExpression(node: t.CallExpression): WhitespaceFlag {\n if (isFunction(node.callee) || isHelper(node)) {\n return WhitespaceFlag.before | WhitespaceFlag.after;\n }\n },\n\n OptionalCallExpression(node: t.OptionalCallExpression): WhitespaceFlag {\n if (isFunction(node.callee)) {\n return WhitespaceFlag.before | WhitespaceFlag.after;\n }\n },\n\n /**\n * Test if VariableDeclaration needs whitespace.\n */\n\n VariableDeclaration(node: t.VariableDeclaration): WhitespaceFlag {\n for (let i = 0; i < node.declarations.length; i++) {\n const declar = node.declarations[i];\n\n let enabled = isHelper(declar.id) && !isType(declar.init);\n if (!enabled && declar.init) {\n const state = crawl(declar.init);\n enabled = (isHelper(declar.init) && state.hasCall) || state.hasFunction;\n }\n\n if (enabled) {\n return WhitespaceFlag.before | WhitespaceFlag.after;\n }\n }\n },\n\n /**\n * Test if IfStatement needs whitespace.\n */\n\n IfStatement(node: t.IfStatement): WhitespaceFlag {\n if (isBlockStatement(node.consequent)) {\n return WhitespaceFlag.before | WhitespaceFlag.after;\n }\n },\n};\n\n/**\n * Test if Property needs whitespace.\n */\n\nnodes.ObjectProperty =\n nodes.ObjectTypeProperty =\n nodes.ObjectMethod =\n function (\n node: t.ObjectProperty | t.ObjectTypeProperty | t.ObjectMethod,\n parent: t.ObjectExpression,\n ): WhitespaceFlag {\n if (parent.properties[0] === node) {\n return WhitespaceFlag.before;\n }\n };\n\nnodes.ObjectTypeCallProperty = function (\n node: t.ObjectTypeCallProperty,\n parent: t.ObjectTypeAnnotation,\n): WhitespaceFlag {\n if (parent.callProperties[0] === node && !parent.properties?.length) {\n return WhitespaceFlag.before;\n }\n};\n\nnodes.ObjectTypeIndexer = function (\n node: t.ObjectTypeIndexer,\n parent: t.ObjectTypeAnnotation,\n): WhitespaceFlag {\n if (\n parent.indexers[0] === node &&\n !parent.properties?.length &&\n !parent.callProperties?.length\n ) {\n return WhitespaceFlag.before;\n }\n};\n\nnodes.ObjectTypeInternalSlot = function (\n node: t.ObjectTypeInternalSlot,\n parent: t.ObjectTypeAnnotation,\n): WhitespaceFlag {\n if (\n parent.internalSlots[0] === node &&\n !parent.properties?.length &&\n !parent.callProperties?.length &&\n !parent.indexers?.length\n ) {\n return WhitespaceFlag.before;\n }\n};\n\n/**\n * Add whitespace tests for nodes and their aliases.\n */\n\n(\n [\n [\"Function\", true],\n [\"Class\", true],\n [\"Loop\", true],\n [\"LabeledStatement\", true],\n [\"SwitchStatement\", true],\n [\"TryStatement\", true],\n ] as const\n).forEach(function ([type, amounts]) {\n [type as string]\n .concat(FLIPPED_ALIAS_KEYS[type] || [])\n .forEach(function (type) {\n const ret = amounts ? WhitespaceFlag.before | WhitespaceFlag.after : 0;\n nodes[type] = () => ret;\n });\n});\n"],"mappings":";;;;;;AAAA,IAAAA,EAAA,GAAAC,OAAA;AAesB;EAdpBC,kBAAkB;EAClBC,iBAAiB;EACjBC,sBAAsB;EACtBC,QAAQ;EACRC,gBAAgB;EAChBC,gBAAgB;EAChBC,UAAU;EACVC,YAAY;EACZC,SAAS;EACTC,kBAAkB;EAClBC,kBAAkB;EAClBC,wBAAwB;EACxBC,0BAA0B;EAC1BC;AAAe,IAAAf,EAAA;AAkBjB,SAASgB,aAAaA,CACpBC,IAAY,EACZC,KAAqE,EACrE;EACA,IAAI,CAACD,IAAI,EAAE,OAAOC,KAAK;EAEvB,IAAIP,kBAAkB,CAACM,IAAI,CAAC,IAAIH,0BAA0B,CAACG,IAAI,CAAC,EAAE;IAChED,aAAa,CAACC,IAAI,CAACE,MAAM,EAAED,KAAK,CAAC;IACjC,IAAID,IAAI,CAACG,QAAQ,EAAEJ,aAAa,CAACC,IAAI,CAACI,QAAQ,EAAEH,KAAK,CAAC;EACxD,CAAC,MAAM,IAAIb,QAAQ,CAACY,IAAI,CAAC,IAAIb,sBAAsB,CAACa,IAAI,CAAC,EAAE;IACzDD,aAAa,CAACC,IAAI,CAACK,IAAI,EAAEJ,KAAK,CAAC;IAC/BF,aAAa,CAACC,IAAI,CAACM,KAAK,EAAEL,KAAK,CAAC;EAClC,CAAC,MAAM,IAAIX,gBAAgB,CAACU,IAAI,CAAC,IAAIJ,wBAAwB,CAACI,IAAI,CAAC,EAAE;IACnEC,KAAK,CAACM,OAAO,GAAG,IAAI;IACpBR,aAAa,CAACC,IAAI,CAACQ,MAAM,EAAEP,KAAK,CAAC;EACnC,CAAC,MAAM,IAAIV,UAAU,CAACS,IAAI,CAAC,EAAE;IA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1B,CAAC,iBAAiB,EAAE,IAAI,CAAC,EACzB,CAAC,cAAc,EAAE,IAAI,CAAC,CACvB,CACD+B,OAAO,CAAC,UAAU,CAACC,IAAI,EAAEC,OAAO,CAAC,EAAE;EACnC,CAACD,IAAI,CAAW,CACbE,MAAM,CAACvE,kBAAkB,CAACqE,IAAI,CAAC,IAAI,EAAE,CAAC,CACtCD,OAAO,CAAC,UAAUC,IAAI,EAAE;IACvB,MAAMG,GAAG,GAAGF,OAAO,GAAG,KAA4C,GAAG,CAAC;IACtEvC,KAAK,CAACsC,IAAI,CAAC,GAAG,MAAMG,GAAG;EACzB,CAAC,CAAC;AACN,CAAC,CAAC","ignoreList":[]} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/printer.js b/node_modules/@babel/generator/lib/printer.js new file mode 100644 index 0000000..caf822a --- /dev/null +++ b/node_modules/@babel/generator/lib/printer.js @@ -0,0 +1,695 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _buffer = require("./buffer.js"); +var n = require("./node/index.js"); +var _t = require("@babel/types"); +var generatorFunctions = require("./generators/index.js"); +const { + isFunction, + isStatement, + isClassBody, + isTSInterfaceBody, + isTSEnumDeclaration +} = _t; +const SCIENTIFIC_NOTATION = /e/i; +const ZERO_DECIMAL_INTEGER = /\.0+$/; +const HAS_NEWLINE = /[\n\r\u2028\u2029]/; +const HAS_NEWLINE_OR_BlOCK_COMMENT_END = /[\n\r\u2028\u2029]|\*\//; +const { + needsParens +} = n; +class Printer { + constructor(format, map) { + this.inForStatementInit = false; + this.tokenContext = 0; + this._currentNode = null; + this._indent = 0; + this._indentRepeat = 0; + this._insideAux = false; + this._parenPushNewlineState = null; + this._noLineTerminator = false; + this._printAuxAfterOnNextUserNode = false; + this._printedComments = new Set(); + this._endsWithInteger = false; + this._endsWithWord = false; + this._endsWithDiv = false; + this._lastCommentLine = 0; + this._endsWithInnerRaw = false; + this._indentInnerComments = true; + this.format = format; + this._indentRepeat = format.indent.style.length; + this._inputMap = map == null ? void 0 : map._inputMap; + this._buf = new _buffer.default(map, format.indent.style[0]); + } + enterForStatementInit(val) { + const old = this.inForStatementInit; + if (old === val) return () => {}; + this.inForStatementInit = val; + return () => { + this.inForStatementInit = old; + }; + } + generate(ast) { + this.print(ast); + this._maybeAddAuxComment(); + return this._buf.get(); + } + indent() { + if (this.format.compact || this.format.concise) return; + this._indent++; + } + dedent() { + if (this.format.compact || this.format.concise) return; + this._indent--; + } + semicolon(force = false) { + this._maybeAddAuxComment(); + if (force) { + this._appendChar(59); + } else { + this._queue(59); + } + this._noLineTerminator = false; + } + rightBrace(node) { + if (this.format.minified) { + this._buf.removeLastSemicolon(); + } + this.sourceWithOffset("end", node.loc, -1); + this.tokenChar(125); + } + rightParens(node) { + this.sourceWithOffset("end", node.loc, -1); + this.tokenChar(41); + } + space(force = false) { + if (this.format.compact) return; + if (force) { + this._space(); + } else if (this._buf.hasContent()) { + const lastCp = this.getLastChar(); + if (lastCp !== 32 && lastCp !== 10) { + this._space(); + } + } + } + word(str, noLineTerminatorAfter = false) { + this.tokenContext = 0; + this._maybePrintInnerComments(); + if (this._endsWithWord || this._endsWithDiv && str.charCodeAt(0) === 47) { + this._space(); + } + this._maybeAddAuxComment(); + this._append(str, false); + this._endsWithWord = true; + this._noLineTerminator = noLineTerminatorAfter; + } + number(str, number) { + function isNonDecimalLiteral(str) { + if (str.length > 2 && str.charCodeAt(0) === 48) { + const secondChar = str.charCodeAt(1); + return secondChar === 98 || secondChar === 111 || secondChar === 120; + } + return false; + } + this.word(str); + this._endsWithInteger = Number.isInteger(number) && !isNonDecimalLiteral(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str.charCodeAt(str.length - 1) !== 46; + } + token(str, maybeNewline = false) { + this.tokenContext = 0; + this._maybePrintInnerComments(); + const lastChar = this.getLastChar(); + const strFirst = str.charCodeAt(0); + if (lastChar === 33 && (str === "--" || strFirst === 61) || strFirst === 43 && lastChar === 43 || strFirst === 45 && lastChar === 45 || strFirst === 46 && this._endsWithInteger) { + this._space(); + } + this._maybeAddAuxComment(); + this._append(str, maybeNewline); + this._noLineTerminator = false; + } + tokenChar(char) { + this.tokenContext = 0; + this._maybePrintInnerComments(); + const lastChar = this.getLastChar(); + if (char === 43 && lastChar === 43 || char === 45 && lastChar === 45 || char === 46 && this._endsWithInteger) { + this._space(); + } + this._maybeAddAuxComment(); + this._appendChar(char); + this._noLineTerminator = false; + } + newline(i = 1, force) { + if (i <= 0) return; + if (!force) { + if (this.format.retainLines || this.format.compact) return; + if (this.format.concise) { + this.space(); + return; + } + } + if (i > 2) i = 2; + i -= this._buf.getNewlineCount(); + for (let j = 0; j < i; j++) { + this._newline(); + } + return; + } + endsWith(char) { + return this.getLastChar() === char; + } + getLastChar() { + return this._buf.getLastChar(); + } + endsWithCharAndNewline() { + return this._buf.endsWithCharAndNewline(); + } + removeTrailingNewline() { + this._buf.removeTrailingNewline(); + } + exactSource(loc, cb) { + if (!loc) { + cb(); + return; + } + this._catchUp("start", loc); + this._buf.exactSource(loc, cb); + } + source(prop, loc) { + if (!loc) return; + this._catchUp(prop, loc); + this._buf.source(prop, loc); + } + sourceWithOffset(prop, loc, columnOffset) { + if (!loc) return; + this._catchUp(prop, loc); + this._buf.sourceWithOffset(prop, loc, columnOffset); + } + sourceIdentifierName(identifierName, pos) { + if (!this._buf._canMarkIdName) return; + const sourcePosition = this._buf._sourcePosition; + sourcePosition.identifierNamePos = pos; + sourcePosition.identifierName = identifierName; + } + _space() { + this._queue(32); + } + _newline() { + this._queue(10); + } + _append(str, maybeNewline) { + this._maybeAddParen(str); + this._maybeIndent(str.charCodeAt(0)); + this._buf.append(str, maybeNewline); + this._endsWithWord = false; + this._endsWithInteger = false; + this._endsWithDiv = false; + } + _appendChar(char) { + this._maybeAddParenChar(char); + this._maybeIndent(char); + this._buf.appendChar(char); + this._endsWithWord = false; + this._endsWithInteger = false; + this._endsWithDiv = false; + } + _queue(char) { + this._maybeAddParenChar(char); + this._maybeIndent(char); + this._buf.queue(char); + this._endsWithWord = false; + this._endsWithInteger = false; + } + _maybeIndent(firstChar) { + if (this._indent && firstChar !== 10 && this.endsWith(10)) { + this._buf.queueIndentation(this._getIndent()); + } + } + _shouldIndent(firstChar) { + if (this._indent && firstChar !== 10 && this.endsWith(10)) { + return true; + } + } + _maybeAddParenChar(char) { + const parenPushNewlineState = this._parenPushNewlineState; + if (!parenPushNewlineState) return; + if (char === 32) { + return; + } + if (char !== 10) { + this._parenPushNewlineState = null; + return; + } + this.tokenChar(40); + this.indent(); + parenPushNewlineState.printed = true; + } + _maybeAddParen(str) { + const parenPushNewlineState = this._parenPushNewlineState; + if (!parenPushNewlineState) return; + const len = str.length; + let i; + for (i = 0; i < len && str.charCodeAt(i) === 32; i++) continue; + if (i === len) { + return; + } + const cha = str.charCodeAt(i); + if (cha !== 10) { + if (cha !== 47 || i + 1 === len) { + this._parenPushNewlineState = null; + return; + } + const chaPost = str.charCodeAt(i + 1); + if (chaPost === 42) { + return; + } else if (chaPost !== 47) { + this._parenPushNewlineState = null; + return; + } + } + this.tokenChar(40); + this.indent(); + parenPushNewlineState.printed = true; + } + catchUp(line) { + if (!this.format.retainLines) return; + const count = line - this._buf.getCurrentLine(); + for (let i = 0; i < count; i++) { + this._newline(); + } + } + _catchUp(prop, loc) { + var _loc$prop; + if (!this.format.retainLines) return; + const line = loc == null || (_loc$prop = loc[prop]) == null ? void 0 : _loc$prop.line; + if (line != null) { + const count = line - this._buf.getCurrentLine(); + for (let i = 0; i < count; i++) { + this._newline(); + } + } + } + _getIndent() { + return this._indentRepeat * this._indent; + } + printTerminatorless(node, isLabel) { + if (isLabel) { + this._noLineTerminator = true; + this.print(node); + } else { + const terminatorState = { + printed: false + }; + this._parenPushNewlineState = terminatorState; + this.print(node); + if (terminatorState.printed) { + this.dedent(); + this.newline(); + this.tokenChar(41); + } + } + } + print(node, noLineTerminatorAfter, trailingCommentsLineOffset, forceParens) { + var _node$extra, _node$leadingComments; + if (!node) return; + this._endsWithInnerRaw = false; + const nodeType = node.type; + const format = this.format; + const oldConcise = format.concise; + if (node._compact) { + format.concise = true; + } + const printMethod = this[nodeType]; + if (printMethod === undefined) { + throw new ReferenceError(`unknown node of type ${JSON.stringify(nodeType)} with constructor ${JSON.stringify(node.constructor.name)}`); + } + const parent = this._currentNode; + this._currentNode = node; + const oldInAux = this._insideAux; + this._insideAux = node.loc == null; + this._maybeAddAuxComment(this._insideAux && !oldInAux); + const parenthesized = (_node$extra = node.extra) == null ? void 0 : _node$extra.parenthesized; + let shouldPrintParens = forceParens || parenthesized && format.retainFunctionParens && nodeType === "FunctionExpression" || needsParens(node, parent, this.tokenContext, this.inForStatementInit); + if (!shouldPrintParens && parenthesized && (_node$leadingComments = node.leadingComments) != null && _node$leadingComments.length && node.leadingComments[0].type === "CommentBlock") { + const parentType = parent == null ? void 0 : parent.type; + switch (parentType) { + case "ExpressionStatement": + case "VariableDeclarator": + case "AssignmentExpression": + case "ReturnStatement": + break; + case "CallExpression": + case "OptionalCallExpression": + case "NewExpression": + if (parent.callee !== node) break; + default: + shouldPrintParens = true; + } + } + let exitInForStatementInit; + if (shouldPrintParens) { + this.tokenChar(40); + this._endsWithInnerRaw = false; + exitInForStatementInit = this.enterForStatementInit(false); + } + this._lastCommentLine = 0; + this._printLeadingComments(node, parent); + const loc = nodeType === "Program" || nodeType === "File" ? null : node.loc; + this.exactSource(loc, printMethod.bind(this, node, parent)); + if (shouldPrintParens) { + this._printTrailingComments(node, parent); + this.tokenChar(41); + this._noLineTerminator = noLineTerminatorAfter; + exitInForStatementInit(); + } else if (noLineTerminatorAfter && !this._noLineTerminator) { + this._noLineTerminator = true; + this._printTrailingComments(node, parent); + } else { + this._printTrailingComments(node, parent, trailingCommentsLineOffset); + } + this._currentNode = parent; + format.concise = oldConcise; + this._insideAux = oldInAux; + this._endsWithInnerRaw = false; + } + _maybeAddAuxComment(enteredPositionlessNode) { + if (enteredPositionlessNode) this._printAuxBeforeComment(); + if (!this._insideAux) this._printAuxAfterComment(); + } + _printAuxBeforeComment() { + if (this._printAuxAfterOnNextUserNode) return; + this._printAuxAfterOnNextUserNode = true; + const comment = this.format.auxiliaryCommentBefore; + if (comment) { + this._printComment({ + type: "CommentBlock", + value: comment + }, 0); + } + } + _printAuxAfterComment() { + if (!this._printAuxAfterOnNextUserNode) return; + this._printAuxAfterOnNextUserNode = false; + const comment = this.format.auxiliaryCommentAfter; + if (comment) { + this._printComment({ + type: "CommentBlock", + value: comment + }, 0); + } + } + getPossibleRaw(node) { + const extra = node.extra; + if ((extra == null ? void 0 : extra.raw) != null && extra.rawValue != null && node.value === extra.rawValue) { + return extra.raw; + } + } + printJoin(nodes, opts = {}) { + if (!(nodes != null && nodes.length)) return; + let { + indent + } = opts; + if (indent == null && this.format.retainLines) { + var _nodes$0$loc; + const startLine = (_nodes$0$loc = nodes[0].loc) == null ? void 0 : _nodes$0$loc.start.line; + if (startLine != null && startLine !== this._buf.getCurrentLine()) { + indent = true; + } + } + if (indent) this.indent(); + const newlineOpts = { + addNewlines: opts.addNewlines, + nextNodeStartLine: 0 + }; + const separator = opts.separator ? opts.separator.bind(this) : null; + const len = nodes.length; + for (let i = 0; i < len; i++) { + const node = nodes[i]; + if (!node) continue; + if (opts.statement) this._printNewline(i === 0, newlineOpts); + this.print(node, undefined, opts.trailingCommentsLineOffset || 0); + opts.iterator == null || opts.iterator(node, i); + if (i < len - 1) separator == null || separator(); + if (opts.statement) { + var _node$trailingComment; + if (!((_node$trailingComment = node.trailingComments) != null && _node$trailingComment.length)) { + this._lastCommentLine = 0; + } + if (i + 1 === len) { + this.newline(1); + } else { + var _nextNode$loc; + const nextNode = nodes[i + 1]; + newlineOpts.nextNodeStartLine = ((_nextNode$loc = nextNode.loc) == null ? void 0 : _nextNode$loc.start.line) || 0; + this._printNewline(true, newlineOpts); + } + } + } + if (indent) this.dedent(); + } + printAndIndentOnComments(node) { + const indent = node.leadingComments && node.leadingComments.length > 0; + if (indent) this.indent(); + this.print(node); + if (indent) this.dedent(); + } + printBlock(parent) { + const node = parent.body; + if (node.type !== "EmptyStatement") { + this.space(); + } + this.print(node); + } + _printTrailingComments(node, parent, lineOffset) { + const { + innerComments, + trailingComments + } = node; + if (innerComments != null && innerComments.length) { + this._printComments(2, innerComments, node, parent, lineOffset); + } + if (trailingComments != null && trailingComments.length) { + this._printComments(2, trailingComments, node, parent, lineOffset); + } + } + _printLeadingComments(node, parent) { + const comments = node.leadingComments; + if (!(comments != null && comments.length)) return; + this._printComments(0, comments, node, parent); + } + _maybePrintInnerComments() { + if (this._endsWithInnerRaw) this.printInnerComments(); + this._endsWithInnerRaw = true; + this._indentInnerComments = true; + } + printInnerComments() { + const node = this._currentNode; + const comments = node.innerComments; + if (!(comments != null && comments.length)) return; + const hasSpace = this.endsWith(32); + const indent = this._indentInnerComments; + const printedCommentsCount = this._printedComments.size; + if (indent) this.indent(); + this._printComments(1, comments, node); + if (hasSpace && printedCommentsCount !== this._printedComments.size) { + this.space(); + } + if (indent) this.dedent(); + } + noIndentInnerCommentsHere() { + this._indentInnerComments = false; + } + printSequence(nodes, opts = {}) { + var _opts$indent; + opts.statement = true; + (_opts$indent = opts.indent) != null ? _opts$indent : opts.indent = false; + this.printJoin(nodes, opts); + } + printList(items, opts = {}) { + if (opts.separator == null) { + opts.separator = commaSeparator; + } + this.printJoin(items, opts); + } + _printNewline(newLine, opts) { + const format = this.format; + if (format.retainLines || format.compact) return; + if (format.concise) { + this.space(); + return; + } + if (!newLine) { + return; + } + const startLine = opts.nextNodeStartLine; + const lastCommentLine = this._lastCommentLine; + if (startLine > 0 && lastCommentLine > 0) { + const offset = startLine - lastCommentLine; + if (offset >= 0) { + this.newline(offset || 1); + return; + } + } + if (this._buf.hasContent()) { + this.newline(1); + } + } + _shouldPrintComment(comment) { + if (comment.ignore) return 0; + if (this._printedComments.has(comment)) return 0; + if (this._noLineTerminator && HAS_NEWLINE_OR_BlOCK_COMMENT_END.test(comment.value)) { + return 2; + } + this._printedComments.add(comment); + if (!this.format.shouldPrintComment(comment.value)) { + return 0; + } + return 1; + } + _printComment(comment, skipNewLines) { + const noLineTerminator = this._noLineTerminator; + const isBlockComment = comment.type === "CommentBlock"; + const printNewLines = isBlockComment && skipNewLines !== 1 && !this._noLineTerminator; + if (printNewLines && this._buf.hasContent() && skipNewLines !== 2) { + this.newline(1); + } + const lastCharCode = this.getLastChar(); + if (lastCharCode !== 91 && lastCharCode !== 123 && lastCharCode !== 40) { + this.space(); + } + let val; + if (isBlockComment) { + const { + _parenPushNewlineState + } = this; + if ((_parenPushNewlineState == null ? void 0 : _parenPushNewlineState.printed) === false && HAS_NEWLINE.test(comment.value)) { + this.tokenChar(40); + this.indent(); + _parenPushNewlineState.printed = true; + } + val = `/*${comment.value}*/`; + if (this.format.indent.adjustMultilineComment) { + var _comment$loc; + const offset = (_comment$loc = comment.loc) == null ? void 0 : _comment$loc.start.column; + if (offset) { + const newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); + val = val.replace(newlineRegex, "\n"); + } + if (this.format.concise) { + val = val.replace(/\n(?!$)/g, `\n`); + } else { + let indentSize = this.format.retainLines ? 0 : this._buf.getCurrentColumn(); + if (this._shouldIndent(47) || this.format.retainLines) { + indentSize += this._getIndent(); + } + val = val.replace(/\n(?!$)/g, `\n${" ".repeat(indentSize)}`); + } + } + } else if (!noLineTerminator) { + val = `//${comment.value}`; + } else { + val = `/*${comment.value}*/`; + } + if (this._endsWithDiv) this._space(); + this.source("start", comment.loc); + this._append(val, isBlockComment); + if (!isBlockComment && !noLineTerminator) { + this.newline(1, true); + } + if (printNewLines && skipNewLines !== 3) { + this.newline(1); + } + } + _printComments(type, comments, node, parent, lineOffset = 0) { + const nodeLoc = node.loc; + const len = comments.length; + let hasLoc = !!nodeLoc; + const nodeStartLine = hasLoc ? nodeLoc.start.line : 0; + const nodeEndLine = hasLoc ? nodeLoc.end.line : 0; + let lastLine = 0; + let leadingCommentNewline = 0; + const maybeNewline = this._noLineTerminator ? function () {} : this.newline.bind(this); + for (let i = 0; i < len; i++) { + const comment = comments[i]; + const shouldPrint = this._shouldPrintComment(comment); + if (shouldPrint === 2) { + hasLoc = false; + break; + } + if (hasLoc && comment.loc && shouldPrint === 1) { + const commentStartLine = comment.loc.start.line; + const commentEndLine = comment.loc.end.line; + if (type === 0) { + let offset = 0; + if (i === 0) { + if (this._buf.hasContent() && (comment.type === "CommentLine" || commentStartLine !== commentEndLine)) { + offset = leadingCommentNewline = 1; + } + } else { + offset = commentStartLine - lastLine; + } + lastLine = commentEndLine; + maybeNewline(offset); + this._printComment(comment, 1); + if (i + 1 === len) { + maybeNewline(Math.max(nodeStartLine - lastLine, leadingCommentNewline)); + lastLine = nodeStartLine; + } + } else if (type === 1) { + const offset = commentStartLine - (i === 0 ? nodeStartLine : lastLine); + lastLine = commentEndLine; + maybeNewline(offset); + this._printComment(comment, 1); + if (i + 1 === len) { + maybeNewline(Math.min(1, nodeEndLine - lastLine)); + lastLine = nodeEndLine; + } + } else { + const offset = commentStartLine - (i === 0 ? nodeEndLine - lineOffset : lastLine); + lastLine = commentEndLine; + maybeNewline(offset); + this._printComment(comment, 1); + } + } else { + hasLoc = false; + if (shouldPrint !== 1) { + continue; + } + if (len === 1) { + const singleLine = comment.loc ? comment.loc.start.line === comment.loc.end.line : !HAS_NEWLINE.test(comment.value); + const shouldSkipNewline = singleLine && !isStatement(node) && !isClassBody(parent) && !isTSInterfaceBody(parent) && !isTSEnumDeclaration(parent); + if (type === 0) { + this._printComment(comment, shouldSkipNewline && node.type !== "ObjectExpression" || singleLine && isFunction(parent, { + body: node + }) ? 1 : 0); + } else if (shouldSkipNewline && type === 2) { + this._printComment(comment, 1); + } else { + this._printComment(comment, 0); + } + } else if (type === 1 && !(node.type === "ObjectExpression" && node.properties.length > 1) && node.type !== "ClassBody" && node.type !== "TSInterfaceBody") { + this._printComment(comment, i === 0 ? 2 : i === len - 1 ? 3 : 0); + } else { + this._printComment(comment, 0); + } + } + } + if (type === 2 && hasLoc && lastLine) { + this._lastCommentLine = lastLine; + } + } +} +Object.assign(Printer.prototype, generatorFunctions); +{ + Printer.prototype.Noop = function Noop() {}; +} +var _default = exports.default = Printer; +function commaSeparator() { + this.tokenChar(44); + this.space(); +} + +//# sourceMappingURL=printer.js.map diff --git a/node_modules/@babel/generator/lib/printer.js.map b/node_modules/@babel/generator/lib/printer.js.map new file mode 100644 index 0000000..9a9083e --- /dev/null +++ b/node_modules/@babel/generator/lib/printer.js.map @@ -0,0 +1 @@ +{"version":3,"names":["_buffer","require","n","_t","generatorFunctions","isFunction","isStatement","isClassBody","isTSInterfaceBody","isTSEnumDeclaration","SCIENTIFIC_NOTATION","ZERO_DECIMAL_INTEGER","HAS_NEWLINE","HAS_NEWLINE_OR_BlOCK_COMMENT_END","needsParens","Printer","constructor","format","map","inForStatementInit","tokenContext","_currentNode","_indent","_indentRepeat","_insideAux","_parenPushNewlineState","_noLineTerminator","_printAuxAfterOnNextUserNode","_printedComments","Set","_endsWithInteger","_endsWithWord","_endsWithDiv","_lastCommentLine","_endsWithInnerRaw","_indentInnerComments","indent","style","length","_inputMap","_buf","Buffer","enterForStatementInit","val","old","generate","ast","print","_maybeAddAuxComment","get","compact","concise","dedent","semicolon","force","_appendChar","_queue","rightBrace","node","minified","removeLastSemicolon","sourceWithOffset","loc","token","rightParens","space","_space","hasContent","lastCp","getLastChar","word","str","noLineTerminatorAfter","_maybePrintInnerComments","charCodeAt","_append","number","isNonDecimalLiteral","secondChar","Number","isInteger","test","maybeNewline","lastChar","strFirst","tokenChar","char","newline","i","retainLines","getNewlineCount","j","_newline","endsWith","endsWithCharAndNewline","removeTrailingNewline","exactSource","cb","_catchUp","source","prop","columnOffset","sourceIdentifierName","identifierName","pos","_canMarkIdName","sourcePosition","_sourcePosition","identifierNamePos","_maybeAddParen","_maybeIndent","append","_maybeAddParenChar","appendChar","queue","firstChar","queueIndentation","_getIndent","_shouldIndent","parenPushNewlineState","printed","len","cha","chaPost","catchUp","line","count","getCurrentLine","_loc$prop","printTerminatorless","isLabel","terminatorState","trailingCommentsLineOffset","forceParens","_node$extra","_node$leadingComments","nodeType","type","oldConcise","_compact","printMethod","undefined","ReferenceError","JSON","stringify","name","parent","oldInAux","parenthesized","extra","shouldPrintParens","retainFunctionParens","leadingComments","parentType","callee","exitInForStatementInit","_printLeadingComments","bind","_printTrailingComments","enteredPositionlessNode","_printAuxBeforeComment","_printAuxAfterComment","comment","auxiliaryCommentBefore","_printComment","value","auxiliaryCommentAfter","getPossibleRaw","raw","rawValue","printJoin","nodes","opts","_nodes$0$loc","startLine","start","newlineOpts","addNewlines","nextNodeStartLine","separator","statement","_printNewline","iterator","_node$trailingComment","trailingComments","_nextNode$loc","nextNode","printAndIndentOnComments","printBlock","body","lineOffset","innerComments","_printComments","comments","printInnerComments","hasSpace","printedCommentsCount","size","noIndentInnerCommentsHere","printSequence","_opts$indent","printList","items","commaSeparator","newLine","lastCommentLine","offset","_shouldPrintComment","ignore","has","add","shouldPrintComment","skipNewLines","noLineTerminator","isBlockComment","printNewLines","lastCharCode","adjustMultilineComment","_comment$loc","column","newlineRegex","RegExp","replace","indentSize","getCurrentColumn","repeat","nodeLoc","hasLoc","nodeStartLine","nodeEndLine","end","lastLine","leadingCommentNewline","shouldPrint","commentStartLine","commentEndLine","Math","max","min","singleLine","shouldSkipNewline","properties","Object","assign","prototype","Noop","_default","exports","default"],"sources":["../src/printer.ts"],"sourcesContent":["import Buffer, { type Pos } from \"./buffer.ts\";\nimport type { Loc } from \"./buffer.ts\";\nimport * as n from \"./node/index.ts\";\nimport type * as t from \"@babel/types\";\nimport {\n isFunction,\n isStatement,\n isClassBody,\n isTSInterfaceBody,\n isTSEnumDeclaration,\n} from \"@babel/types\";\nimport type { Opts as jsescOptions } from \"jsesc\";\n\nimport type { GeneratorOptions } from \"./index.ts\";\nimport * as generatorFunctions from \"./generators/index.ts\";\nimport type SourceMap from \"./source-map.ts\";\nimport type { TraceMap } from \"@jridgewell/trace-mapping\";\n\n// We inline this package\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport * as charCodes from \"charcodes\";\n\nconst SCIENTIFIC_NOTATION = /e/i;\nconst ZERO_DECIMAL_INTEGER = /\\.0+$/;\nconst HAS_NEWLINE = /[\\n\\r\\u2028\\u2029]/;\nconst HAS_NEWLINE_OR_BlOCK_COMMENT_END = /[\\n\\r\\u2028\\u2029]|\\*\\//;\n\nconst { needsParens } = n;\n\nconst enum COMMENT_TYPE {\n LEADING,\n INNER,\n TRAILING,\n}\n\nconst enum COMMENT_SKIP_NEWLINE {\n DEFAULT,\n ALL,\n LEADING,\n TRAILING,\n}\n\nconst enum PRINT_COMMENT_HINT {\n SKIP,\n ALLOW,\n DEFER,\n}\n\nexport type Format = {\n shouldPrintComment: (comment: string) => boolean;\n retainLines: boolean;\n retainFunctionParens: boolean;\n comments: boolean;\n auxiliaryCommentBefore: string;\n auxiliaryCommentAfter: string;\n compact: boolean | \"auto\";\n minified: boolean;\n concise: boolean;\n indent: {\n adjustMultilineComment: boolean;\n style: string;\n };\n /**\n * @deprecated Removed in Babel 8, syntax type is always 'hash'\n */\n recordAndTupleSyntaxType?: GeneratorOptions[\"recordAndTupleSyntaxType\"];\n jsescOption: jsescOptions;\n /**\n * @deprecated Removed in Babel 8, use `jsescOption` instead\n */\n jsonCompatibleStrings?: boolean;\n /**\n * For use with the Hack-style pipe operator.\n * Changes what token is used for pipe bodies’ topic references.\n */\n topicToken?: GeneratorOptions[\"topicToken\"];\n /**\n * @deprecated Removed in Babel 8\n */\n decoratorsBeforeExport?: boolean;\n /**\n * The import attributes syntax style:\n * - \"with\" : `import { a } from \"b\" with { type: \"json\" };`\n * - \"assert\" : `import { a } from \"b\" assert { type: \"json\" };`\n * - \"with-legacy\" : `import { a } from \"b\" with type: \"json\";`\n */\n importAttributesKeyword?: \"with\" | \"assert\" | \"with-legacy\";\n};\n\ninterface AddNewlinesOptions {\n addNewlines(leading: boolean, node: t.Node): number;\n nextNodeStartLine: number;\n}\n\ninterface PrintSequenceOptions extends Partial {\n statement?: boolean;\n indent?: boolean;\n trailingCommentsLineOffset?: number;\n}\n\ninterface PrintListOptions {\n separator?: (this: Printer) => void;\n iterator?: (node: t.Node, index: number) => void;\n statement?: boolean;\n indent?: boolean;\n}\n\nexport type PrintJoinOptions = PrintListOptions & PrintSequenceOptions;\nclass Printer {\n constructor(format: Format, map: SourceMap) {\n this.format = format;\n\n this._indentRepeat = format.indent.style.length;\n\n this._inputMap = map?._inputMap;\n\n this._buf = new Buffer(map, format.indent.style[0]);\n }\n declare _inputMap: TraceMap;\n\n declare format: Format;\n\n inForStatementInit: boolean = false;\n enterForStatementInit(val: boolean) {\n const old = this.inForStatementInit;\n if (old === val) return () => {};\n this.inForStatementInit = val;\n return () => {\n this.inForStatementInit = old;\n };\n }\n\n tokenContext: number = 0;\n\n declare _buf: Buffer;\n _currentNode: t.Node = null;\n _indent: number = 0;\n _indentRepeat: number = 0;\n _insideAux: boolean = false;\n _parenPushNewlineState: { printed: boolean } | null = null;\n _noLineTerminator: boolean = false;\n _printAuxAfterOnNextUserNode: boolean = false;\n _printedComments = new Set();\n _endsWithInteger = false;\n _endsWithWord = false;\n _endsWithDiv = false;\n _lastCommentLine = 0;\n _endsWithInnerRaw: boolean = false;\n _indentInnerComments: boolean = true;\n\n generate(ast: t.Node) {\n this.print(ast);\n this._maybeAddAuxComment();\n\n return this._buf.get();\n }\n\n /**\n * Increment indent size.\n */\n\n indent(): void {\n if (this.format.compact || this.format.concise) return;\n\n this._indent++;\n }\n\n /**\n * Decrement indent size.\n */\n\n dedent(): void {\n if (this.format.compact || this.format.concise) return;\n\n this._indent--;\n }\n\n /**\n * Add a semicolon to the buffer.\n */\n\n semicolon(force: boolean = false): void {\n this._maybeAddAuxComment();\n if (force) {\n this._appendChar(charCodes.semicolon);\n } else {\n this._queue(charCodes.semicolon);\n }\n this._noLineTerminator = false;\n }\n\n /**\n * Add a right brace to the buffer.\n */\n\n rightBrace(node: t.Node): void {\n if (this.format.minified) {\n this._buf.removeLastSemicolon();\n }\n this.sourceWithOffset(\"end\", node.loc, -1);\n this.token(\"}\");\n }\n\n rightParens(node: t.Node): void {\n this.sourceWithOffset(\"end\", node.loc, -1);\n this.token(\")\");\n }\n\n /**\n * Add a space to the buffer unless it is compact.\n */\n\n space(force: boolean = false): void {\n if (this.format.compact) return;\n\n if (force) {\n this._space();\n } else if (this._buf.hasContent()) {\n const lastCp = this.getLastChar();\n if (lastCp !== charCodes.space && lastCp !== charCodes.lineFeed) {\n this._space();\n }\n }\n }\n\n /**\n * Writes a token that can't be safely parsed without taking whitespace into account.\n */\n\n word(str: string, noLineTerminatorAfter: boolean = false): void {\n this.tokenContext = 0;\n\n this._maybePrintInnerComments();\n\n // prevent concatenating words and creating // comment out of division and regex\n if (\n this._endsWithWord ||\n (this._endsWithDiv && str.charCodeAt(0) === charCodes.slash)\n ) {\n this._space();\n }\n\n this._maybeAddAuxComment();\n this._append(str, false);\n\n this._endsWithWord = true;\n this._noLineTerminator = noLineTerminatorAfter;\n }\n\n /**\n * Writes a number token so that we can validate if it is an integer.\n */\n\n number(str: string, number?: number): void {\n // const NON_DECIMAL_LITERAL = /^0[box]/;\n function isNonDecimalLiteral(str: string) {\n if (str.length > 2 && str.charCodeAt(0) === charCodes.digit0) {\n const secondChar = str.charCodeAt(1);\n return (\n secondChar === charCodes.lowercaseB ||\n secondChar === charCodes.lowercaseO ||\n secondChar === charCodes.lowercaseX\n );\n }\n return false;\n }\n this.word(str);\n\n // Integer tokens need special handling because they cannot have '.'s inserted\n // immediately after them.\n this._endsWithInteger =\n Number.isInteger(number) &&\n !isNonDecimalLiteral(str) &&\n !SCIENTIFIC_NOTATION.test(str) &&\n !ZERO_DECIMAL_INTEGER.test(str) &&\n str.charCodeAt(str.length - 1) !== charCodes.dot;\n }\n\n /**\n * Writes a simple token.\n */\n token(str: string, maybeNewline = false): void {\n this.tokenContext = 0;\n\n this._maybePrintInnerComments();\n\n const lastChar = this.getLastChar();\n const strFirst = str.charCodeAt(0);\n if (\n (lastChar === charCodes.exclamationMark &&\n // space is mandatory to avoid outputting ` line comment\n const comment = this.skipLineComment(3);\n if (comment !== undefined) {\n this.addComment(comment);\n if (this.options.attachComment) comments.push(comment);\n }\n } else {\n break loop;\n }\n } else if (\n ch === charCodes.lessThan &&\n !this.inModule &&\n this.options.annexB\n ) {\n const pos = this.state.pos;\n if (\n this.input.charCodeAt(pos + 1) === charCodes.exclamationMark &&\n this.input.charCodeAt(pos + 2) === charCodes.dash &&\n this.input.charCodeAt(pos + 3) === charCodes.dash\n ) {\n // ` true + * console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN' + * console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' + * } + * ``` + * @since v14.3.0 + * @param [label='Header name'] Label for error message. + */ + function validateHeaderName(name: string): void; + /** + * Performs the low-level validations on the provided `value` that are done when `res.setHeader(name, value)` is called. + * + * Passing illegal value as `value` will result in a `TypeError` being thrown. + * + * * Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. + * * Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Examples: + * + * ```js + * import { validateHeaderValue } from 'node:http'; + * + * try { + * validateHeaderValue('x-my-header', undefined); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true + * console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' + * } + * + * try { + * validateHeaderValue('x-my-header', 'oʊmɪɡə'); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_INVALID_CHAR'); // --> true + * console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' + * } + * ``` + * @since v14.3.0 + * @param name Header name + * @param value Header value + */ + function validateHeaderValue(name: string, value: string): void; + /** + * Set the maximum number of idle HTTP parsers. + * @since v18.8.0, v16.18.0 + * @param [max=1000] + */ + function setMaxIdleHTTPParsers(max: number): void; + /** + * Global instance of `Agent` which is used as the default for all HTTP client + * requests. Diverges from a default `Agent` configuration by having `keepAlive` + * enabled and a `timeout` of 5 seconds. + * @since v0.5.9 + */ + let globalAgent: Agent; + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; + /** + * A browser-compatible implementation of [WebSocket](https://nodejs.org/docs/latest/api/http.html#websocket). + * @since v22.5.0 + */ + const WebSocket: import("undici-types").WebSocket; + /** + * @since v22.5.0 + */ + const CloseEvent: import("undici-types").CloseEvent; + /** + * @since v22.5.0 + */ + const MessageEvent: import("undici-types").MessageEvent; +} +declare module "node:http" { + export * from "http"; +} diff --git a/node_modules/@types/node/http2.d.ts b/node_modules/@types/node/http2.d.ts new file mode 100644 index 0000000..3e98e0d --- /dev/null +++ b/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2418 @@ +/** + * The `node:http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. + * It can be accessed using: + * + * ```js + * const http2 = require('node:http2'); + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/http2.js) + */ +declare module "http2" { + import EventEmitter = require("node:events"); + import * as fs from "node:fs"; + import * as net from "node:net"; + import * as stream from "node:stream"; + import * as tls from "node:tls"; + import * as url from "node:url"; + import { + IncomingHttpHeaders as Http1IncomingHttpHeaders, + IncomingMessage, + OutgoingHttpHeaders, + ServerResponse, + } from "node:http"; + export { OutgoingHttpHeaders } from "node:http"; + export interface IncomingHttpStatusHeader { + ":status"?: number | undefined; + } + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ":path"?: string | undefined; + ":method"?: string | undefined; + ":authority"?: string | undefined; + ":scheme"?: string | undefined; + } + // Http2Stream + export interface StreamPriorityOptions { + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + silent?: boolean | undefined; + } + export interface StreamState { + localWindowSize?: number | undefined; + state?: number | undefined; + localClose?: number | undefined; + remoteClose?: number | undefined; + sumDependencyWeight?: number | undefined; + weight?: number | undefined; + } + export interface ServerStreamResponseOptions { + endStream?: boolean | undefined; + waitForTrailers?: boolean | undefined; + } + export interface StatOptions { + offset: number; + length: number; + } + export interface ServerStreamFileResponseOptions { + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + statCheck?(stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions): void | boolean; + waitForTrailers?: boolean | undefined; + offset?: number | undefined; + length?: number | undefined; + } + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?(err: NodeJS.ErrnoException): void; + } + export interface Http2Stream extends stream.Duplex { + /** + * Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, + * the `'aborted'` event will have been emitted. + * @since v8.4.0 + */ + readonly aborted: boolean; + /** + * This property shows the number of characters currently buffered to be written. + * See `net.Socket.bufferSize` for details. + * @since v11.2.0, v10.16.0 + */ + readonly bufferSize: number; + /** + * Set to `true` if the `Http2Stream` instance has been closed. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Set to `true` if the `Http2Stream` instance has been destroyed and is no longer + * usable. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Set to `true` if the `END_STREAM` flag was set in the request or response + * HEADERS frame received, indicating that no additional data should be received + * and the readable side of the `Http2Stream` will be closed. + * @since v10.11.0 + */ + readonly endAfterHeaders: boolean; + /** + * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined` if the stream identifier has not yet been assigned. + * @since v8.4.0 + */ + readonly id?: number | undefined; + /** + * Set to `true` if the `Http2Stream` instance has not yet been assigned a + * numeric stream identifier. + * @since v9.4.0 + */ + readonly pending: boolean; + /** + * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is + * destroyed after either receiving an `RST_STREAM` frame from the connected peer, + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be `undefined` if the `Http2Stream` has not been closed. + * @since v8.4.0 + */ + readonly rstCode: number; + /** + * An object containing the outbound headers sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentHeaders: OutgoingHttpHeaders; + /** + * An array of objects containing the outbound informational (additional) headers + * sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined; + /** + * An object containing the outbound trailers sent for this `HttpStream`. + * @since v9.5.0 + */ + readonly sentTrailers?: OutgoingHttpHeaders | undefined; + /** + * A reference to the `Http2Session` instance that owns this `Http2Stream`. The + * value will be `undefined` after the `Http2Stream` instance is destroyed. + * @since v8.4.0 + */ + readonly session: Http2Session | undefined; + /** + * Provides miscellaneous information about the current state of the `Http2Stream`. + * + * A current state of this `Http2Stream`. + * @since v8.4.0 + */ + readonly state: StreamState; + /** + * Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the + * connected HTTP/2 peer. + * @since v8.4.0 + * @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code. + * @param callback An optional function registered to listen for the `'close'` event. + */ + close(code?: number, callback?: () => void): void; + /** + * Updates the priority for this `Http2Stream` instance. + * @since v8.4.0 + */ + priority(options: StreamPriorityOptions): void; + /** + * ```js + * const http2 = require('node:http2'); + * const client = http2.connect('http://example.org:8000'); + * const { NGHTTP2_CANCEL } = http2.constants; + * const req = client.request({ ':path': '/' }); + * + * // Cancel the stream if there's no activity after 5 seconds + * req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); + * ``` + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method + * will cause the `Http2Stream` to be immediately closed and must only be + * called after the `'wantTrailers'` event has been emitted. When sending a + * request or sending a response, the `options.waitForTrailers` option must be set + * in order to keep the `Http2Stream` open after the final `DATA` frame so that + * trailers can be sent. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond(undefined, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ xyz: 'abc' }); + * }); + * stream.end('Hello World'); + * }); + * ``` + * + * The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header + * fields (e.g. `':method'`, `':path'`, etc). + * @since v10.0.0 + */ + sendTrailers(headers: OutgoingHttpHeaders): void; + addListener(event: "aborted", listener: () => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: "streamClosed", listener: (code: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "wantTrailers", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted"): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "frameError", frameType: number, errorCode: number): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: "streamClosed", code: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "wantTrailers"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: () => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: "streamClosed", listener: (code: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "wantTrailers", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: () => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: "streamClosed", listener: (code: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "wantTrailers", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: () => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "streamClosed", listener: (code: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "wantTrailers", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: () => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "wantTrailers", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: "continue", listener: () => {}): this; + addListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "continue"): boolean; + emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "continue", listener: () => {}): this; + on( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "continue", listener: () => {}): this; + once( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "continue", listener: () => {}): this; + prependListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "continue", listener: () => {}): this; + prependOnceListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ServerHttp2Stream extends Http2Stream { + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote + * client's most recent `SETTINGS` frame. Will be `true` if the remote peer + * accepts push streams, `false` otherwise. Settings are the same for every `Http2Stream` in the same `Http2Session`. + * @since v8.4.0 + */ + readonly pushAllowed: boolean; + /** + * Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. + * @since v8.4.0 + */ + additionalHeaders(headers: OutgoingHttpHeaders): void; + /** + * Initiates a push stream. The callback is invoked with the new `Http2Stream` instance created for the push stream passed as the second argument, or an `Error` passed as the first argument. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { + * if (err) throw err; + * pushStream.respond({ ':status': 200 }); + * pushStream.end('some pushed data'); + * }); + * stream.end('some data'); + * }); + * ``` + * + * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass + * a `weight` value to `http2stream.priority` with the `silent` option set to `true` to enable server-side bandwidth balancing between concurrent streams. + * + * Calling `http2stream.pushStream()` from within a pushed stream is not permitted + * and will throw an error. + * @since v8.4.0 + * @param callback Callback that is called once the push stream has been initiated. + */ + pushStream( + headers: OutgoingHttpHeaders, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + pushStream( + headers: OutgoingHttpHeaders, + options?: StreamPriorityOptions, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + /** + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * Initiates a response. When the `options.waitForTrailers` option is set, the`'wantTrailers'` event will be emitted immediately after queuing the last chunk + * of payload data to be sent. The `http2stream.sendTrailers()` method can then be + * used to sent trailing header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either `http2stream.sendTrailers()` or `http2stream.close()` to close the `Http2Stream`. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * stream.end('some data'); + * }); + * ``` + * @since v8.4.0 + */ + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + /** + * Initiates a response whose data is read from the given file descriptor. No + * validation is performed on the given file descriptor. If an error occurs while + * attempting to read data using the file descriptor, the `Http2Stream` will be + * closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * ```js + * const http2 = require('node:http2'); + * const fs = require('node:fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers); + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given fd. If the `statCheck` function is provided, the `http2stream.respondWithFD()` method will perform an `fs.fstat()` call to + * collect details on the provided file descriptor. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The file descriptor or `FileHandle` is not closed when the stream is closed, + * so it will need to be closed manually once it is no longer needed. + * Using the same file descriptor concurrently for multiple streams + * is not supported and may result in data loss. Re-using a file descriptor + * after a stream has finished is supported. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code _must_ call either `http2stream.sendTrailers()` or `http2stream.close()` to close the `Http2Stream`. + * + * ```js + * const http2 = require('node:http2'); + * const fs = require('node:fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * @since v8.4.0 + * @param fd A readable file descriptor. + */ + respondWithFD( + fd: number | fs.promises.FileHandle, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptions, + ): void; + /** + * Sends a regular file as the response. The `path` must specify a regular file + * or an `'error'` event will be emitted on the `Http2Stream` object. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given file: + * + * If an error occurs while attempting to read the file data, the `Http2Stream` will be closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. If the `onError` callback is + * defined, then it will be called. Otherwise + * the stream will be destroyed. + * + * Example using a file path: + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * headers['last-modified'] = stat.mtime.toUTCString(); + * } + * + * function onError(err) { + * // stream.respond() can throw if the stream has been destroyed by + * // the other side. + * try { + * if (err.code === 'ENOENT') { + * stream.respond({ ':status': 404 }); + * } else { + * stream.respond({ ':status': 500 }); + * } + * } catch (err) { + * // Perform actual error handling. + * console.error(err); + * } + * stream.end(); + * } + * + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck, onError }); + * }); + * ``` + * + * The `options.statCheck` function may also be used to cancel the send operation + * by returning `false`. For instance, a conditional request may check the stat + * results to determine if the file has been modified to return an appropriate `304` response: + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * // Check the stat here... + * stream.respond({ ':status': 304 }); + * return false; // Cancel the send operation + * } + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck }); + * }); + * ``` + * + * The `content-length` header field will be automatically set. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The `options.onError` function may also be used to handle all the errors + * that could happen before the delivery of the file is initiated. The + * default behavior is to destroy the stream. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * }); + * ``` + * @since v8.4.0 + */ + respondWithFile( + path: string, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptionsWithError, + ): void; + } + // Http2Session + export interface Settings { + headerTableSize?: number | undefined; + enablePush?: boolean | undefined; + initialWindowSize?: number | undefined; + maxFrameSize?: number | undefined; + maxConcurrentStreams?: number | undefined; + maxHeaderListSize?: number | undefined; + enableConnectProtocol?: boolean | undefined; + } + export interface ClientSessionRequestOptions { + endStream?: boolean | undefined; + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + waitForTrailers?: boolean | undefined; + signal?: AbortSignal | undefined; + } + export interface SessionState { + effectiveLocalWindowSize?: number | undefined; + effectiveRecvDataLength?: number | undefined; + nextStreamID?: number | undefined; + localWindowSize?: number | undefined; + lastProcStreamID?: number | undefined; + remoteWindowSize?: number | undefined; + outboundQueueSize?: number | undefined; + deflateDynamicTableSize?: number | undefined; + inflateDynamicTableSize?: number | undefined; + } + export interface Http2Session extends EventEmitter { + /** + * Value will be `undefined` if the `Http2Session` is not yet connected to a + * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or + * will return the value of the connected `TLSSocket`'s own `alpnProtocol` property. + * @since v9.4.0 + */ + readonly alpnProtocol?: string | undefined; + /** + * Will be `true` if this `Http2Session` instance has been closed, otherwise `false`. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Will be `true` if this `Http2Session` instance is still connecting, will be set + * to `false` before emitting `connect` event and/or calling the `http2.connect` callback. + * @since v10.0.0 + */ + readonly connecting: boolean; + /** + * Will be `true` if this `Http2Session` instance has been destroyed and must no + * longer be used, otherwise `false`. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Value is `undefined` if the `Http2Session` session socket has not yet been + * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, + * and `false` if the `Http2Session` is connected to any other kind of socket + * or stream. + * @since v9.4.0 + */ + readonly encrypted?: boolean | undefined; + /** + * A prototype-less object describing the current local settings of this `Http2Session`. The local settings are local to _this_`Http2Session` instance. + * @since v8.4.0 + */ + readonly localSettings: Settings; + /** + * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property + * will return an `Array` of origins for which the `Http2Session` may be + * considered authoritative. + * + * The `originSet` property is only available when using a secure TLS connection. + * @since v9.4.0 + */ + readonly originSet?: string[] | undefined; + /** + * Indicates whether the `Http2Session` is currently waiting for acknowledgment of + * a sent `SETTINGS` frame. Will be `true` after calling the `http2session.settings()` method. Will be `false` once all sent `SETTINGS` frames have been acknowledged. + * @since v8.4.0 + */ + readonly pendingSettingsAck: boolean; + /** + * A prototype-less object describing the current remote settings of this`Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer. + * @since v8.4.0 + */ + readonly remoteSettings: Settings; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * limits available methods to ones safe to use with HTTP/2. + * + * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw + * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. + * + * `setTimeout` method will be called on this `Http2Session`. + * + * All other interactions will be routed directly to the socket. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * Provides miscellaneous information about the current state of the`Http2Session`. + * + * An object describing the current status of this `Http2Session`. + * @since v8.4.0 + */ + readonly state: SessionState; + /** + * The `http2session.type` will be equal to `http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a + * client. + * @since v8.4.0 + */ + readonly type: number; + /** + * Gracefully closes the `Http2Session`, allowing any existing streams to + * complete on their own and preventing new `Http2Stream` instances from being + * created. Once closed, `http2session.destroy()`_might_ be called if there + * are no open `Http2Stream` instances. + * + * If specified, the `callback` function is registered as a handler for the`'close'` event. + * @since v9.4.0 + */ + close(callback?: () => void): void; + /** + * Immediately terminates the `Http2Session` and the associated `net.Socket` or `tls.TLSSocket`. + * + * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error` is not undefined, an `'error'` event will be emitted immediately before the `'close'` event. + * + * If there are any remaining open `Http2Streams` associated with the `Http2Session`, those will also be destroyed. + * @since v8.4.0 + * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. + * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. + */ + destroy(error?: Error, code?: number): void; + /** + * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. + * @since v9.4.0 + * @param code An HTTP/2 error code + * @param lastStreamID The numeric ID of the last processed `Http2Stream` + * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. + */ + goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; + /** + * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must + * be provided. The method will return `true` if the `PING` was sent, `false` otherwise. + * + * The maximum number of outstanding (unacknowledged) pings is determined by the `maxOutstandingPings` configuration option. The default maximum is 10. + * + * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView` containing 8 bytes of data that will be transmitted with the `PING` and + * returned with the ping acknowledgment. + * + * The callback will be invoked with three arguments: an error argument that will + * be `null` if the `PING` was successfully acknowledged, a `duration` argument + * that reports the number of milliseconds elapsed since the ping was sent and the + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING` payload. + * + * ```js + * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { + * if (!err) { + * console.log(`Ping acknowledged in ${duration} milliseconds`); + * console.log(`With payload '${payload.toString()}'`); + * } + * }); + * ``` + * + * If the `payload` argument is not specified, the default payload will be the + * 64-bit timestamp (little endian) marking the start of the `PING` duration. + * @since v8.9.3 + * @param payload Optional ping payload. + */ + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping( + payload: NodeJS.ArrayBufferView, + callback: (err: Error | null, duration: number, payload: Buffer) => void, + ): boolean; + /** + * Calls `ref()` on this `Http2Session` instance's underlying `net.Socket`. + * @since v9.4.0 + */ + ref(): void; + /** + * Sets the local endpoint's window size. + * The `windowSize` is the total window size to set, not + * the delta. + * + * ```js + * const http2 = require('node:http2'); + * + * const server = http2.createServer(); + * const expectedWindowSize = 2 ** 20; + * server.on('connect', (session) => { + * + * // Set local window size to be 2 ** 20 + * session.setLocalWindowSize(expectedWindowSize); + * }); + * ``` + * @since v15.3.0, v14.18.0 + */ + setLocalWindowSize(windowSize: number): void; + /** + * Used to set a callback function that is called when there is no activity on + * the `Http2Session` after `msecs` milliseconds. The given `callback` is + * registered as a listener on the `'timeout'` event. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Updates the current local settings for this `Http2Session` and sends a new `SETTINGS` frame to the connected HTTP/2 peer. + * + * Once called, the `http2session.pendingSettingsAck` property will be `true` while the session is waiting for the remote peer to acknowledge the new + * settings. + * + * The new settings will not become effective until the `SETTINGS` acknowledgment + * is received and the `'localSettings'` event is emitted. It is possible to send + * multiple `SETTINGS` frames while acknowledgment is still pending. + * @since v8.4.0 + * @param callback Callback that is called once the session is connected or right away if the session is already connected. + */ + settings( + settings: Settings, + callback?: (err: Error | null, settings: Settings, duration: number) => void, + ): void; + /** + * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + unref(): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + addListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + addListener(event: "localSettings", listener: (settings: Settings) => void): this; + addListener(event: "ping", listener: () => void): this; + addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; + emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData?: Buffer): boolean; + emit(event: "localSettings", settings: Settings): boolean; + emit(event: "ping"): boolean; + emit(event: "remoteSettings", settings: Settings): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this; + on(event: "localSettings", listener: (settings: Settings) => void): this; + on(event: "ping", listener: () => void): this; + on(event: "remoteSettings", listener: (settings: Settings) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this; + once(event: "localSettings", listener: (settings: Settings) => void): this; + once(event: "ping", listener: () => void): this; + once(event: "remoteSettings", listener: (settings: Settings) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + prependListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + prependListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependListener(event: "ping", listener: () => void): this; + prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + prependOnceListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "ping", listener: () => void): this; + prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Session extends Http2Session { + /** + * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()` creates and returns an `Http2Stream` instance that can be used to send an + * HTTP/2 request to the connected server. + * + * When a `ClientHttp2Session` is first created, the socket may not yet be + * connected. if `clienthttp2session.request()` is called during this time, the + * actual request will be deferred until the socket is ready to go. + * If the `session` is closed before the actual request be executed, an `ERR_HTTP2_GOAWAY_SESSION` is thrown. + * + * This method is only available if `http2session.type` is equal to `http2.constants.NGHTTP2_SESSION_CLIENT`. + * + * ```js + * const http2 = require('node:http2'); + * const clientSession = http2.connect('https://localhost:1234'); + * const { + * HTTP2_HEADER_PATH, + * HTTP2_HEADER_STATUS, + * } = http2.constants; + * + * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); + * req.on('response', (headers) => { + * console.log(headers[HTTP2_HEADER_STATUS]); + * req.on('data', (chunk) => { // .. }); + * req.on('end', () => { // .. }); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * is emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be called to send trailing + * headers to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * When `options.signal` is set with an `AbortSignal` and then `abort` on the + * corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error. + * + * The `:method` and `:path` pseudo-headers are not specified within `headers`, + * they respectively default to: + * + * * `:method` \= `'GET'` + * * `:path` \= `/` + * @since v8.4.0 + */ + request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; + addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: "origin", listener: (origins: string[]) => void): this; + addListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + addListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; + emit(event: "origin", origins: readonly string[]): boolean; + emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit( + event: "stream", + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + on(event: "origin", listener: (origins: string[]) => void): this; + on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + once(event: "origin", listener: (origins: string[]) => void): this; + once( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + once( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: "origin", listener: (origins: string[]) => void): this; + prependListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: "origin", listener: (origins: string[]) => void): this; + prependOnceListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependOnceListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + export interface ServerHttp2Session extends Http2Session { + readonly server: Http2Server | Http2SecureServer; + /** + * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. + * + * ```js + * const http2 = require('node:http2'); + * + * const server = http2.createServer(); + * server.on('session', (session) => { + * // Set altsvc for origin https://example.org:80 + * session.altsvc('h2=":8000"', 'https://example.org:80'); + * }); + * + * server.on('stream', (stream) => { + * // Set altsvc for a specific stream + * stream.session.altsvc('h2=":8000"', stream.id); + * }); + * ``` + * + * Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate + * service is associated with the origin of the given `Http2Stream`. + * + * The `alt` and origin string _must_ contain only ASCII bytes and are + * strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given + * domain. + * + * When a string is passed for the `originOrStream` argument, it will be parsed as + * a URL and the origin will be derived. For instance, the origin for the + * HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * @since v9.4.0 + * @param alt A description of the alternative service configuration as defined by `RFC 7838`. + * @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the + * `http2stream.id` property. + */ + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + /** + * Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client + * to advertise the set of origins for which the server is capable of providing + * authoritative responses. + * + * ```js + * const http2 = require('node:http2'); + * const options = getSecureOptionsSomehow(); + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * server.on('session', (session) => { + * session.origin('https://example.com', 'https://example.org'); + * }); + * ``` + * + * When a string is passed as an `origin`, it will be parsed as a URL and the + * origin will be derived. For instance, the origin for the HTTP URL `'https://example.org/foo/bar'` is the ASCII string` 'https://example.org'`. An error will be thrown if either the given + * string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as + * an `origin`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * + * Alternatively, the `origins` option may be used when creating a new HTTP/2 + * server using the `http2.createSecureServer()` method: + * + * ```js + * const http2 = require('node:http2'); + * const options = getSecureOptionsSomehow(); + * options.origins = ['https://example.com', 'https://example.org']; + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * ``` + * @since v10.12.0 + * @param origins One or more URL Strings passed as separate arguments. + */ + origin( + ...origins: Array< + | string + | url.URL + | { + origin: string; + } + > + ): void; + addListener( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + // Http2Server + export interface SessionOptions { + maxDeflateDynamicTableSize?: number | undefined; + maxSessionMemory?: number | undefined; + maxHeaderListPairs?: number | undefined; + maxOutstandingPings?: number | undefined; + maxSendHeaderBlockLength?: number | undefined; + paddingStrategy?: number | undefined; + peerMaxConcurrentStreams?: number | undefined; + settings?: Settings | undefined; + remoteCustomSettings?: number[] | undefined; + /** + * Specifies a timeout in milliseconds that + * a server should wait when an [`'unknownProtocol'`][] is emitted. If the + * socket has not been destroyed by that time the server will destroy it. + * @default 100000 + */ + unknownProtocolTimeout?: number | undefined; + selectPadding?(frameLen: number, maxFrameLen: number): number; + } + export interface ClientSessionOptions extends SessionOptions { + maxReservedRemoteStreams?: number | undefined; + createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; + protocol?: "http:" | "https:" | undefined; + } + export interface ServerSessionOptions extends SessionOptions { + Http1IncomingMessage?: typeof IncomingMessage | undefined; + Http1ServerResponse?: typeof ServerResponse | undefined; + Http2ServerRequest?: typeof Http2ServerRequest | undefined; + Http2ServerResponse?: typeof Http2ServerResponse | undefined; + } + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions {} + export interface ServerOptions extends ServerSessionOptions {} + export interface SecureServerOptions extends SecureServerSessionOptions { + allowHTTP1?: boolean | undefined; + origins?: string[] | undefined; + } + interface HTTP2ServerCommon { + setTimeout(msec?: number, callback?: () => void): this; + /** + * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. + * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. + */ + updateSettings(settings: Settings): void; + } + export interface Http2Server extends net.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "session", session: ServerHttp2Session): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "session", listener: (session: ServerHttp2Session) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "session", listener: (session: ServerHttp2Session) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface Http2SecureServer extends tls.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "session", session: ServerHttp2Session): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "session", listener: (session: ServerHttp2Session) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "session", listener: (session: ServerHttp2Session) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status, + * headers, and + * data. + * @since v8.4.0 + */ + export class Http2ServerRequest extends stream.Readable { + constructor( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + options: stream.ReadableOptions, + rawHeaders: readonly string[], + ); + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ + readonly aborted: boolean; + /** + * The request authority pseudo header field. Because HTTP/2 allows requests + * to set either `:authority` or `host`, this value is derived from `req.headers[':authority']` if present. Otherwise, it is derived from `req.headers['host']`. + * @since v8.4.0 + */ + readonly authority: string; + /** + * See `request.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * The `request.complete` property will be `true` if the request has + * been completed, aborted, or destroyed. + * @since v12.10.0 + */ + readonly complete: boolean; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * See `HTTP/2 Headers Object`. + * + * In HTTP/2, the request path, host name, protocol, and method are represented as + * special headers prefixed with the `:` character (e.g. `':path'`). These special + * headers will be included in the `request.headers` object. Care must be taken not + * to inadvertently modify these special headers or errors may occur. For instance, + * removing all headers from the request will cause errors to occur: + * + * ```js + * removeAllHeaders(request.headers); + * assert(request.url); // Fails because the :path header has been removed + * ``` + * @since v8.4.0 + */ + readonly headers: IncomingHttpHeaders; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. Returns `'2.0'`. + * + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. + * @since v8.4.0 + */ + readonly httpVersion: string; + readonly httpVersionMinor: number; + readonly httpVersionMajor: number; + /** + * The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. + * @since v8.4.0 + */ + readonly method: string; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v8.4.0 + */ + readonly rawHeaders: string[]; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly rawTrailers: string[]; + /** + * The request scheme pseudo header field indicating the scheme + * portion of the target URL. + * @since v8.4.0 + */ + readonly scheme: string; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `request.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `request.stream`. + * + * `setTimeout` method will be called on `request.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. With TLS support, + * use `request.socket.getPeerCertificate()` to obtain the client's + * authentication details. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the request. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly trailers: IncomingHttpHeaders; + /** + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. If the request is: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * Then `request.url` will be: + * + * ```js + * '/status?name=ryan' + * ``` + * + * To parse the url into its parts, `new URL()` can be used: + * + * ```console + * $ node + * > new URL('/status?name=ryan', 'http://example.com') + * URL { + * href: 'http://example.com/status?name=ryan', + * origin: 'http://example.com', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'example.com', + * hostname: 'example.com', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v8.4.0 + */ + url: string; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream`s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + read(size?: number): Buffer | string | null; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted", hadError: boolean, code: number): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v8.4.0 + */ + export class Http2ServerResponse extends stream.Writable { + constructor(stream: ServerHttp2Stream); + /** + * See `response.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple times. + * + * If there were no previous values for the header, this is equivalent to calling {@link setHeader}. + * + * Attempting to set a header field name or value that contains invalid characters will result in a + * [TypeError](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-typeerror) being thrown. + * + * ```js + * // Returns headers including "set-cookie: a" and "set-cookie: b" + * const server = http2.createServer((req, res) => { + * res.setHeader('set-cookie', 'a'); + * res.appendHeader('set-cookie', 'b'); + * res.writeHead(200); + * res.end('ok'); + * }); + * ``` + * @since v20.12.0 + */ + appendHeader(name: string, value: string | string[]): void; + /** + * Boolean value that indicates whether the response has completed. Starts + * as `false`. After `response.end()` executes, the value will be `true`. + * @since v8.4.0 + * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. + */ + readonly finished: boolean; + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * A reference to the original HTTP2 `request` object. + * @since v15.7.0 + */ + readonly req: Http2ServerRequest; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `response.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `response.stream`. + * + * `setTimeout` method will be called on `response.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer((req, res) => { + * const ip = req.socket.remoteAddress; + * const port = req.socket.remotePort; + * res.end(`Your IP address is ${ip} and your source port is ${port}.`); + * }).listen(3000); + * ``` + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the response. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * When true, the Date header will be automatically generated and sent in + * the response if it is not already present in the headers. Defaults to true. + * + * This should only be disabled for testing; HTTP requires the Date header + * in responses. + * @since v8.4.0 + */ + sendDate: boolean; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v8.4.0 + */ + statusCode: number; + /** + * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns + * an empty string. + * @since v8.4.0 + */ + statusMessage: ""; + /** + * This method adds HTTP trailing headers (a header but at the end of the + * message) to the response. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + addTrailers(trailers: OutgoingHttpHeaders): void; + /** + * This method signals to the server that all of the response headers and body + * have been sent; that server should consider this message complete. + * The method, `response.end()`, MUST be called on each response. + * + * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. + * + * If `callback` is specified, it will be called when the response stream + * is finished. + * @since v8.4.0 + */ + end(callback?: () => void): this; + end(data: string | Uint8Array, callback?: () => void): this; + end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): this; + /** + * Reads out a header that has already been queued but not sent to the client. + * The name is case-insensitive. + * + * ```js + * const contentType = response.getHeader('content-type'); + * ``` + * @since v8.4.0 + */ + getHeader(name: string): string; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All header names are lowercase. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = response.getHeaderNames(); + * // headerNames === ['foo', 'set-cookie'] + * ``` + * @since v8.4.0 + */ + getHeaderNames(): string[]; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow copy + * is used, array values may be mutated without additional calls to various + * header-related http module methods. The keys of the returned object are the + * header names and the values are the respective header values. All header names + * are lowercase. + * + * The object returned by the `response.getHeaders()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = response.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.4.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name matching is case-insensitive. + * + * ```js + * const hasContentType = response.hasHeader('content-type'); + * ``` + * @since v8.4.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that has been queued for implicit sending. + * + * ```js + * response.removeHeader('Content-Encoding'); + * ``` + * @since v8.4.0 + */ + removeHeader(name: string): void; + /** + * Sets a single header value for implicit headers. If this header already exists + * in the to-be-sent headers, its value will be replaced. Use an array of strings + * here to send multiple headers with the same name. + * + * ```js + * response.setHeader('Content-Type', 'text/html; charset=utf-8'); + * ``` + * + * or + * + * ```js + * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * @since v8.4.0 + */ + setHeader(name: string, value: number | string | readonly string[]): void; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * If this method is called and `response.writeHead()` has not been called, + * it will switch to implicit header mode and flush the implicit headers. + * + * This sends a chunk of the response body. This method may + * be called multiple times to provide successive parts of the body. + * + * In the `node:http` module, the response body is omitted when the + * request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body. + * + * `chunk` can be a string or a buffer. If `chunk` is a string, + * the second parameter specifies how to encode it into a byte stream. + * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk + * of data is flushed. + * + * This is the raw HTTP body and has nothing to do with higher-level multi-part + * body encodings that may be used. + * + * The first time `response.write()` is called, it will send the buffered + * header information and the first chunk of the body to the client. The second + * time `response.write()` is called, Node.js assumes data will be streamed, + * and sends the new data separately. That is, the response is buffered up to the + * first chunk of the body. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again. + * @since v8.4.0 + */ + write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; + /** + * Sends a status `100 Continue` to the client, indicating that the request body + * should be sent. See the `'checkContinue'` event on `Http2Server` and `Http2SecureServer`. + * @since v8.4.0 + */ + writeContinue(): void; + /** + * Sends a status `103 Early Hints` to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }); + * ``` + * @since v18.11.0 + */ + writeEarlyHints(hints: Record): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * + * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. + * + * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be + * passed as the second argument. However, because the `statusMessage` has no + * meaning within HTTP/2, the argument will have no effect and a process warning + * will be emitted. + * + * ```js + * const body = 'hello world'; + * response.writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain; charset=utf-8', + * }); + * ``` + * + * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a + * given encoding. On outbound messages, Node.js does not check if Content-Length + * and the length of the body being transmitted are equal or not. However, when + * receiving messages, Node.js will automatically reject messages when the `Content-Length` does not match the actual payload size. + * + * This method may be called at most one time on a message before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; + /** + * Call `http2stream.pushStream()` with the given headers, and wrap the + * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback + * parameter if successful. When `Http2ServerRequest` is closed, the callback is + * called with an error `ERR_HTTP2_INVALID_STREAM`. + * @since v8.4.0 + * @param headers An object describing the headers + * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of + * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method + */ + createPushResponse( + headers: OutgoingHttpHeaders, + callback: (err: Error | null, res: Http2ServerResponse) => void, + ): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + /** + * This symbol can be set as a property on the HTTP/2 headers object with + * an array value in order to provide a list of headers considered sensitive. + */ + export const sensitiveHeaders: symbol; + /** + * Returns an object containing the default settings for an `Http2Session` instance. This method returns a new object instance every time it is called + * so instances returned may be safely modified for use. + * @since v8.4.0 + */ + export function getDefaultSettings(): Settings; + /** + * Returns a `Buffer` instance containing serialized representation of the given + * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended + * for use with the `HTTP2-Settings` header field. + * + * ```js + * const http2 = require('node:http2'); + * + * const packed = http2.getPackedSettings({ enablePush: false }); + * + * console.log(packed.toString('base64')); + * // Prints: AAIAAAAA + * ``` + * @since v8.4.0 + */ + export function getPackedSettings(settings: Settings): Buffer; + /** + * Returns a `HTTP/2 Settings Object` containing the deserialized settings from + * the given `Buffer` as generated by `http2.getPackedSettings()`. + * @since v8.4.0 + * @param buf The packed settings. + */ + export function getUnpackedSettings(buf: Uint8Array): Settings; + /** + * Returns a `net.Server` instance that creates and manages `Http2Session` instances. + * + * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when + * communicating + * with browser clients. + * + * ```js + * const http2 = require('node:http2'); + * + * // Create an unencrypted HTTP/2 server. + * // Since there are no browsers known that support + * // unencrypted HTTP/2, the use of `http2.createSecureServer()` + * // is necessary when communicating with browser clients. + * const server = http2.createServer(); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8000); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + export function createServer( + options: ServerOptions, + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session` instances. + * + * ```js + * const http2 = require('node:http2'); + * const fs = require('node:fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * }; + * + * // Create a secure HTTP/2 server + * const server = http2.createSecureServer(options); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8443); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createSecureServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + export function createSecureServer( + options: SecureServerOptions, + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * const http2 = require('node:http2'); + * const client = http2.connect('https://localhost:1234'); + * + * // Use the client + * + * client.close(); + * ``` + * @since v8.4.0 + * @param authority The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port + * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. + * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. + */ + export function connect( + authority: string | url.URL, + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + /** + * Create an HTTP/2 server session from an existing socket. + * @param socket A Duplex Stream + * @param options Any `{@link createServer}` options can be provided. + * @since v20.12.0 + */ + export function performServerHandshake(socket: stream.Duplex, options?: ServerOptions): ServerHttp2Session; +} +declare module "node:http2" { + export * from "http2"; +} diff --git a/node_modules/@types/node/https.d.ts b/node_modules/@types/node/https.d.ts new file mode 100644 index 0000000..3a821e3 --- /dev/null +++ b/node_modules/@types/node/https.d.ts @@ -0,0 +1,550 @@ +/** + * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a + * separate module. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/https.js) + */ +declare module "https" { + import { Duplex } from "node:stream"; + import * as tls from "node:tls"; + import * as http from "node:http"; + import { URL } from "node:url"; + type ServerOptions< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; + type RequestOptions = + & http.RequestOptions + & tls.SecureContextOptions + & { + checkServerIdentity?: typeof tls.checkServerIdentity | undefined; + rejectUnauthorized?: boolean | undefined; // Defaults to true + servername?: string | undefined; // SNI TLS Extension + }; + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + rejectUnauthorized?: boolean | undefined; + maxCachedSessions?: number | undefined; + } + /** + * An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information. + * @since v0.4.5 + */ + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + } + interface Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > extends http.Server {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor( + options: ServerOptions, + requestListener?: http.RequestListener, + ); + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Duplex) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: http.RequestListener): this; + addListener(event: "checkExpectation", listener: http.RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + addListener(event: "request", listener: http.RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "keylog", line: Buffer, tlsSocket: tls.TLSSocket): boolean; + emit( + event: "newSession", + sessionId: Buffer, + sessionData: Buffer, + callback: (err: Error, resp: Buffer) => void, + ): boolean; + emit( + event: "OCSPRequest", + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ): boolean; + emit(event: "resumeSession", sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; + emit(event: "secureConnection", tlsSocket: tls.TLSSocket): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: tls.TLSSocket): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Duplex): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType & { + req: InstanceType; + }, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType & { + req: InstanceType; + }, + ): boolean; + emit(event: "clientError", err: Error, socket: Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: Duplex, head: Buffer): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType & { + req: InstanceType; + }, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + on( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + on( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Duplex) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: http.RequestListener): this; + on(event: "checkExpectation", listener: http.RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + on(event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + on(event: "request", listener: http.RequestListener): this; + on(event: "upgrade", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Duplex) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: http.RequestListener): this; + once(event: "checkExpectation", listener: http.RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + once(event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + once(event: "request", listener: http.RequestListener): this; + once(event: "upgrade", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Duplex) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: http.RequestListener): this; + prependListener(event: "checkExpectation", listener: http.RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependListener(event: "request", listener: http.RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Duplex) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: http.RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: http.RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: "request", listener: http.RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + } + /** + * ```js + * // curl -k https://localhost:8000/ + * const https = require('node:https'); + * const fs = require('node:fs'); + * + * const options = { + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * + * Or + * + * ```js + * const https = require('node:https'); + * const fs = require('node:fs'); + * + * const options = { + * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), + * passphrase: 'sample', + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * @since v0.3.4 + * @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`. + * @param requestListener A listener to be added to the `'request'` event. + */ + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + >(requestListener?: http.RequestListener): Server; + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + >( + options: ServerOptions, + requestListener?: http.RequestListener, + ): Server; + /** + * Makes a request to a secure web server. + * + * The following additional `options` from `tls.connect()` are also accepted: `ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`, `honorCipherOrder`, `key`, `passphrase`, + * `pfx`, `rejectUnauthorized`, `secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`, `highWaterMark`. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * const https = require('node:https'); + * + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * }; + * + * const req = https.request(options, (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(e); + * }); + * req.end(); + * ``` + * + * Example using options from `tls.connect()`: + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * options.agent = new https.Agent(options); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Alternatively, opt out of connection pooling by not using an `Agent`. + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * agent: false, + * }; + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('https://abc:xyz@example.com'); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): + * + * ```js + * const tls = require('node:tls'); + * const https = require('node:https'); + * const crypto = require('node:crypto'); + * + * function sha256(s) { + * return crypto.createHash('sha256').update(s).digest('base64'); + * } + * const options = { + * hostname: 'github.com', + * port: 443, + * path: '/', + * method: 'GET', + * checkServerIdentity: function(host, cert) { + * // Make sure the certificate is issued to the host we are connected to + * const err = tls.checkServerIdentity(host, cert); + * if (err) { + * return err; + * } + * + * // Pin the public key, similar to HPKP pin-sha256 pinning + * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; + * if (sha256(cert.pubkey) !== pubkey256) { + * const msg = 'Certificate verification error: ' + + * `The public key of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // Pin the exact certificate, rather than the pub key + * const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + + * 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; + * if (cert.fingerprint256 !== cert256) { + * const msg = 'Certificate verification error: ' + + * `The certificate of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // This loop is informational only. + * // Print the certificate and public key fingerprints of all certs in the + * // chain. Its common to pin the public key of the issuer on the public + * // internet, while pinning the public key of the service in sensitive + * // environments. + * do { + * console.log('Subject Common Name:', cert.subject.CN); + * console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); + * + * hash = crypto.createHash('sha256'); + * console.log(' Public key ping-sha256:', sha256(cert.pubkey)); + * + * lastprint256 = cert.fingerprint256; + * cert = cert.issuerCertificate; + * } while (cert.fingerprint256 !== lastprint256); + * + * }, + * }; + * + * options.agent = new https.Agent(options); + * const req = https.request(options, (res) => { + * console.log('All OK. Server matched our pinned cert or public key'); + * console.log('statusCode:', res.statusCode); + * // Print the HPKP values + * console.log('headers:', res.headers['public-key-pins']); + * + * res.on('data', (d) => {}); + * }); + * + * req.on('error', (e) => { + * console.error(e.message); + * }); + * req.end(); + * ``` + * + * Outputs for example: + * + * ```text + * Subject Common Name: github.com + * Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 + * Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= + * Subject Common Name: DigiCert SHA2 Extended Validation Server CA + * Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A + * Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= + * Subject Common Name: DigiCert High Assurance EV Root CA + * Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF + * Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= + * All OK. Server matched our pinned cert or public key + * statusCode: 200 + * headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; + * pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; + * pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains + * ``` + * @since v0.3.6 + * @param options Accepts all `options` from `request`, with some differences in default values: + */ + function request( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + /** + * Like `http.get()` but for HTTPS. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * ```js + * const https = require('node:https'); + * + * https.get('https://encrypted.google.com/', (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * + * }).on('error', (e) => { + * console.error(e); + * }); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. + */ + function get( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function get( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + let globalAgent: Agent; +} +declare module "node:https" { + export * from "https"; +} diff --git a/node_modules/@types/node/index.d.ts b/node_modules/@types/node/index.d.ts new file mode 100644 index 0000000..e575985 --- /dev/null +++ b/node_modules/@types/node/index.d.ts @@ -0,0 +1,90 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +// NOTE: These definitions support NodeJS and TypeScript 4.9+. + +// Reference required types from the default lib: +/// +/// +/// +/// + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +/// diff --git a/node_modules/@types/node/inspector.d.ts b/node_modules/@types/node/inspector.d.ts new file mode 100644 index 0000000..a27ab04 --- /dev/null +++ b/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,3696 @@ +// These definitions are automatically generated by the generate-inspector script. +// Do not edit this file directly. +// See scripts/generate-inspector/README.md for information on how to update the protocol definitions. +// Changes to the module itself should be added to the generator template (scripts/generate-inspector/inspector.d.ts.template). + +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/inspector.js) + */ +declare module 'inspector' { + import EventEmitter = require('node:events'); + + interface InspectorNotification { + method: string; + params: T; + } + + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string | undefined; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview | undefined; + /** + * @experimental + */ + customPreview?: CustomPreview | undefined; + } + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId | undefined; + } + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[] | undefined; + } + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + } + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean | undefined; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | undefined; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject | undefined; + } + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + } + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + } + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: {} | undefined; + } + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId | undefined; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string | undefined; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace | undefined; + /** + * Exception object if available. + */ + exception?: RemoteObject | undefined; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId | undefined; + } + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string | undefined; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace | undefined; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId | undefined; + } + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId | undefined; + } + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + } + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId | undefined; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string | undefined; + } + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean | undefined; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean | undefined; + } + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace | undefined; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string | undefined; + } + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: {}; + } + } + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + /** + * Call frame identifier. + */ + type CallFrameId = string; + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + } + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location | undefined; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject | undefined; + } + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string | undefined; + /** + * Location in the source code where scope starts + */ + startLocation?: Location | undefined; + /** + * Location in the source code where scope ends + */ + endLocation?: Location | undefined; + } + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + type?: string | undefined; + } + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string | undefined; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string | undefined; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location | undefined; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean | undefined; + } + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string | undefined; + } + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean | undefined; + } + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean | undefined; + } + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean | undefined; + } + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean | undefined; + } + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[] | undefined; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + } + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: {} | undefined; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[] | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId | undefined; + } + } + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number | undefined; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number | undefined; + } + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number | undefined; + /** + * Child node ids. + */ + children?: number[] | undefined; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string | undefined; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[] | undefined; + } + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[] | undefined; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[] | undefined; + } + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean | undefined; + /** + * Collect block-based coverage. + */ + detailed?: boolean | undefined; + } + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + } + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean | undefined; + } + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean | undefined; + } + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean | undefined; + } + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + } + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number | undefined; + } + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean | undefined; + } + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string | undefined; + /** + * Included category filters. + */ + includedCategories: string[]; + } + interface StartParameterType { + traceConfig: TraceConfig; + } + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + interface DataCollectedEventDataType { + value: Array<{}>; + } + } + namespace NodeWorker { + type WorkerID = string; + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + interface DetachParameterType { + sessionId: SessionID; + } + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend. + */ + constructor(); + + /** + * Connects a session to the inspector back-end. + */ + connect(): void; + + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + * @since v12.11.0 + */ + connectToMainThread(): void; + + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * `session.connect()` will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + + /** + * Posts a message to the inspector back-end. `callback` will be notified when + * a response is received. `callback` is a function that accepts two optional + * arguments: error and message-specific result. + * + * ```js + * session.post('Runtime.evaluate', { expression: '2 + 2' }, + * (error, { result }) => console.log(result)); + * // Output: { type: 'number', value: 4, description: '4' } + * ``` + * + * The latest version of the V8 inspector protocol is published on the + * [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + */ + post(method: string, callback?: (err: Error | null, params?: object) => void): void; + post(method: string, params?: object, callback?: (err: Error | null, params?: object) => void): void; + /** + * Returns supported domains. + */ + post(method: 'Schema.getDomains', callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Evaluates expression on global object. + */ + post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: 'Runtime.evaluate', callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: 'Runtime.awaitPromise', callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: 'Runtime.callFunctionOn', callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: 'Runtime.getProperties', callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + /** + * Releases remote object with given id. + */ + post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObject', callback?: (err: Error | null) => void): void; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObjectGroup', callback?: (err: Error | null) => void): void; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger', callback?: (err: Error | null) => void): void; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: 'Runtime.enable', callback?: (err: Error | null) => void): void; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable', callback?: (err: Error | null) => void): void; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.setCustomObjectFormatterEnabled', callback?: (err: Error | null) => void): void; + /** + * Compiles expression. + */ + post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: 'Runtime.compileScript', callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + /** + * Runs script with given id in a given context. + */ + post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.runScript', callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: 'Runtime.queryObjects', callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: 'Runtime.globalLexicalScopeNames', + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: 'Runtime.globalLexicalScopeNames', callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: 'Debugger.enable', callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable', callback?: (err: Error | null) => void): void; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBreakpointsActive', callback?: (err: Error | null) => void): void; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setSkipAllPauses', callback?: (err: Error | null) => void): void; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: 'Debugger.setBreakpointByUrl', callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: 'Debugger.setBreakpoint', callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + /** + * Removes JavaScript breakpoint. + */ + post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.removeBreakpoint', callback?: (err: Error | null) => void): void; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: 'Debugger.getPossibleBreakpoints', + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: 'Debugger.getPossibleBreakpoints', callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + /** + * Continues execution until specific location is reached. + */ + post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.continueToLocation', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.pauseOnAsyncCall', callback?: (err: Error | null) => void): void; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver', callback?: (err: Error | null) => void): void; + /** + * Steps into the function call. + */ + post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.stepInto', callback?: (err: Error | null) => void): void; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut', callback?: (err: Error | null) => void): void; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause', callback?: (err: Error | null) => void): void; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: 'Debugger.scheduleStepIntoAsync', callback?: (err: Error | null) => void): void; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume', callback?: (err: Error | null) => void): void; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: 'Debugger.getStackTrace', callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + /** + * Searches for given string in script content. + */ + post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: 'Debugger.searchInContent', callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + /** + * Edits JavaScript source live. + */ + post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: 'Debugger.setScriptSource', callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + /** + * Restarts particular call frame from the beginning. + */ + post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: 'Debugger.restartFrame', callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + /** + * Returns source for the script with given id. + */ + post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: 'Debugger.getScriptSource', callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setPauseOnExceptions', callback?: (err: Error | null) => void): void; + /** + * Evaluates expression on a given call frame. + */ + post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: 'Debugger.evaluateOnCallFrame', callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setVariableValue', callback?: (err: Error | null) => void): void; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setReturnValue', callback?: (err: Error | null) => void): void; + /** + * Enables or disables async call stacks tracking. + */ + post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setAsyncCallStackDepth', callback?: (err: Error | null) => void): void; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxPatterns', callback?: (err: Error | null) => void): void; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxedRanges', callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable', callback?: (err: Error | null) => void): void; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable', callback?: (err: Error | null) => void): void; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.disable', callback?: (err: Error | null) => void): void; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.setSamplingInterval', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.start', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.stop', callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.startPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: 'Profiler.takePreciseCoverage', callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: 'Profiler.getBestEffortCoverage', callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + post(method: 'HeapProfiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.disable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.collectGarbage', callback?: (err: Error | null) => void): void; + post( + method: 'HeapProfiler.getObjectByHeapObjectId', + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: 'HeapProfiler.getObjectByHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.addInspectedHeapObject', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startSampling', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopSampling', callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + post(method: 'HeapProfiler.getSamplingProfile', callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: 'NodeTracing.getCategories', callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + /** + * Start trace events collection. + */ + post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeTracing.start', callback?: (err: Error | null) => void): void; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop', callback?: (err: Error | null) => void): void; + /** + * Sends protocol message over session with given id. + */ + post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.sendMessageToWorker', callback?: (err: Error | null) => void): void; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.enable', callback?: (err: Error | null) => void): void; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable', callback?: (err: Error | null) => void): void; + /** + * Detached from the worker with given sessionId. + */ + post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.detach', callback?: (err: Error | null) => void): void; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.enable', callback?: (err: Error | null) => void): void; + /** + * Disable NodeRuntime events + */ + post(method: 'NodeRuntime.disable', callback?: (err: Error | null) => void): void; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', callback?: (err: Error | null) => void): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'inspectorNotification', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextCreated', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextsCleared'): boolean; + emit(event: 'Runtime.exceptionThrown', message: InspectorNotification): boolean; + emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification): boolean; + emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification): boolean; + emit(event: 'Runtime.inspectRequested', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification): boolean; + emit(event: 'Debugger.breakpointResolved', message: InspectorNotification): boolean; + emit(event: 'Debugger.paused', message: InspectorNotification): boolean; + emit(event: 'Debugger.resumed'): boolean; + emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.resetProfiles'): boolean; + emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.dataCollected', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.tracingComplete'): boolean; + emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + emit(event: 'NodeRuntime.waitingForDebugger'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + on(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + } + + /** + * Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has + * started. + * + * If wait is `true`, will block until a client has connected to the inspect port + * and flow control has been passed to the debugger client. + * + * See the [security warning](https://nodejs.org/docs/latest-v22.x/api/cli.html#warning-binding-inspector-to-a-public-ipport-combination-is-insecure) + * regarding the `host` parameter usage. + * @param port Port to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param host Host to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param wait Block until a client has connected. Defaults to what was specified on the CLI. + * @returns Disposable that calls `inspector.close()`. + */ + function open(port?: number, host?: string, wait?: boolean): Disposable; + + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + + /** + * Return the URL of the active inspector, or `undefined` if there is none. + * + * ```console + * $ node --inspect -p 'inspector.url()' + * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * For help, see: https://nodejs.org/en/docs/inspector + * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * + * $ node --inspect=localhost:3000 -p 'inspector.url()' + * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * For help, see: https://nodejs.org/en/docs/inspector + * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * + * $ node -p 'inspector.url()' + * undefined + * ``` + */ + function url(): string | undefined; + + /** + * Blocks until a client (existing or connected later) has sent `Runtime.runIfWaitingForDebugger` command. + * + * An exception will be thrown if there is no active inspector. + * @since v12.7.0 + */ + function waitForDebugger(): void; + + // These methods are exposed by the V8 inspector console API (inspector/v8-console.h). + // The method signatures differ from those of the Node.js console, and are deliberately + // typed permissively. + interface InspectorConsole { + debug(...data: any[]): void; + error(...data: any[]): void; + info(...data: any[]): void; + log(...data: any[]): void; + warn(...data: any[]): void; + dir(...data: any[]): void; + dirxml(...data: any[]): void; + table(...data: any[]): void; + trace(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(...data: any[]): void; + clear(...data: any[]): void; + count(label?: any): void; + countReset(label?: any): void; + assert(value?: any, ...data: any[]): void; + profile(label?: any): void; + profileEnd(label?: any): void; + time(label?: any): void; + timeLog(label?: any): void; + timeStamp(label?: any): void; + } + + /** + * An object to send messages to the remote inspector console. + * @since v11.0.0 + */ + const console: InspectorConsole; +} + +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + */ +declare module 'node:inspector' { + export * from 'inspector'; +} + +/** + * The `node:inspector/promises` module provides an API for interacting with the V8 + * inspector. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/inspector/promises.js) + * @since v19.0.0 + */ +declare module 'inspector/promises' { + import EventEmitter = require('node:events'); + import { + open, + close, + url, + waitForDebugger, + console, + InspectorNotification, + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + NodeTracing, + NodeWorker, + NodeRuntime, + } from 'inspector'; + + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + * @since v19.0.0 + */ + class Session extends EventEmitter { + /** + * Create a new instance of the `inspector.Session` class. + * The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend. + */ + constructor(); + + /** + * Connects a session to the inspector back-end. + */ + connect(): void; + + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + */ + connectToMainThread(): void; + + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * `session.connect()` will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + + /** + * Posts a message to the inspector back-end. + * + * ```js + * import { Session } from 'node:inspector/promises'; + * try { + * const session = new Session(); + * session.connect(); + * const result = await session.post('Runtime.evaluate', { expression: '2 + 2' }); + * console.log(result); + * } catch (error) { + * console.error(error); + * } + * // Output: { result: { type: 'number', value: 4, description: '4' } } + * ``` + * + * The latest version of the V8 inspector protocol is published on the + * [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + */ + post(method: string, params?: object): Promise; + /** + * Returns supported domains. + */ + post(method: 'Schema.getDomains'): Promise; + /** + * Evaluates expression on global object. + */ + post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType): Promise; + /** + * Add handler to promise with given promise object id. + */ + post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType): Promise; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType): Promise; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType): Promise; + /** + * Releases remote object with given id. + */ + post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType): Promise; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType): Promise; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger'): Promise; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: 'Runtime.enable'): Promise; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable'): Promise; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries'): Promise; + /** + * @experimental + */ + post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType): Promise; + /** + * Compiles expression. + */ + post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType): Promise; + /** + * Runs script with given id in a given context. + */ + post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType): Promise; + post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType): Promise; + /** + * Returns all let, const and class variables from global scope. + */ + post(method: 'Runtime.globalLexicalScopeNames', params?: Runtime.GlobalLexicalScopeNamesParameterType): Promise; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: 'Debugger.enable'): Promise; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable'): Promise; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType): Promise; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType): Promise; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType): Promise; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType): Promise; + /** + * Removes JavaScript breakpoint. + */ + post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType): Promise; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post(method: 'Debugger.getPossibleBreakpoints', params?: Debugger.GetPossibleBreakpointsParameterType): Promise; + /** + * Continues execution until specific location is reached. + */ + post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType): Promise; + /** + * @experimental + */ + post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType): Promise; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver'): Promise; + /** + * Steps into the function call. + */ + post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType): Promise; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut'): Promise; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause'): Promise; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: 'Debugger.scheduleStepIntoAsync'): Promise; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume'): Promise; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType): Promise; + /** + * Searches for given string in script content. + */ + post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType): Promise; + /** + * Edits JavaScript source live. + */ + post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType): Promise; + /** + * Restarts particular call frame from the beginning. + */ + post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType): Promise; + /** + * Returns source for the script with given id. + */ + post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType): Promise; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType): Promise; + /** + * Evaluates expression on a given call frame. + */ + post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType): Promise; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType): Promise; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType): Promise; + /** + * Enables or disables async call stacks tracking. + */ + post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType): Promise; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType): Promise; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType): Promise; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable'): Promise; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable'): Promise; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages'): Promise; + post(method: 'Profiler.enable'): Promise; + post(method: 'Profiler.disable'): Promise; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType): Promise; + post(method: 'Profiler.start'): Promise; + post(method: 'Profiler.stop'): Promise; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType): Promise; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage'): Promise; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: 'Profiler.takePreciseCoverage'): Promise; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: 'Profiler.getBestEffortCoverage'): Promise; + post(method: 'HeapProfiler.enable'): Promise; + post(method: 'HeapProfiler.disable'): Promise; + post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType): Promise; + post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType): Promise; + post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType): Promise; + post(method: 'HeapProfiler.collectGarbage'): Promise; + post(method: 'HeapProfiler.getObjectByHeapObjectId', params?: HeapProfiler.GetObjectByHeapObjectIdParameterType): Promise; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType): Promise; + post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType): Promise; + post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType): Promise; + post(method: 'HeapProfiler.stopSampling'): Promise; + post(method: 'HeapProfiler.getSamplingProfile'): Promise; + /** + * Gets supported tracing categories. + */ + post(method: 'NodeTracing.getCategories'): Promise; + /** + * Start trace events collection. + */ + post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType): Promise; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop'): Promise; + /** + * Sends protocol message over session with given id. + */ + post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType): Promise; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType): Promise; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable'): Promise; + /** + * Detached from the worker with given sessionId. + */ + post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType): Promise; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.enable'): Promise; + /** + * Disable NodeRuntime events + */ + post(method: 'NodeRuntime.disable'): Promise; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType): Promise; + + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'inspectorNotification', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextCreated', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextsCleared'): boolean; + emit(event: 'Runtime.exceptionThrown', message: InspectorNotification): boolean; + emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification): boolean; + emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification): boolean; + emit(event: 'Runtime.inspectRequested', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification): boolean; + emit(event: 'Debugger.breakpointResolved', message: InspectorNotification): boolean; + emit(event: 'Debugger.paused', message: InspectorNotification): boolean; + emit(event: 'Debugger.resumed'): boolean; + emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.resetProfiles'): boolean; + emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.dataCollected', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.tracingComplete'): boolean; + emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + emit(event: 'NodeRuntime.waitingForDebugger'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + on(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + } + + export { + Session, + open, + close, + url, + waitForDebugger, + console, + InspectorNotification, + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + NodeTracing, + NodeWorker, + NodeRuntime, + }; +} + +/** + * The `node:inspector/promises` module provides an API for interacting with the V8 + * inspector. + * @since v19.0.0 + */ +declare module 'node:inspector/promises' { + export * from 'inspector/promises'; +} diff --git a/node_modules/@types/node/module.d.ts b/node_modules/@types/node/module.d.ts new file mode 100644 index 0000000..0d60bb1 --- /dev/null +++ b/node_modules/@types/node/module.d.ts @@ -0,0 +1,301 @@ +/** + * @since v0.3.7 + * @experimental + */ +declare module "module" { + import { URL } from "node:url"; + import { MessagePort } from "node:worker_threads"; + namespace Module { + /** + * The `module.syncBuiltinESMExports()` method updates all the live bindings for + * builtin `ES Modules` to match the properties of the `CommonJS` exports. It + * does not add or remove exported names from the `ES Modules`. + * + * ```js + * const fs = require('node:fs'); + * const assert = require('node:assert'); + * const { syncBuiltinESMExports } = require('node:module'); + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('node:fs').then((esmFS) => { + * // It syncs the existing readFile property with the new value + * assert.strictEqual(esmFS.readFile, newAPI); + * // readFileSync has been deleted from the required fs + * assert.strictEqual('readFileSync' in fs, false); + * // syncBuiltinESMExports() does not remove readFileSync from esmFS + * assert.strictEqual('readFileSync' in esmFS, true); + * // syncBuiltinESMExports() does not add names + * assert.strictEqual(esmFS.newAPI, undefined); + * }); + * ``` + * @since v12.12.0 + */ + function syncBuiltinESMExports(): void; + /** + * `path` is the resolved path for the file for which a corresponding source map + * should be fetched. + * @since v13.7.0, v12.17.0 + * @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise. + */ + function findSourceMap(path: string, error?: Error): SourceMap; + interface SourceMapPayload { + file: string; + version: number; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + sourceRoot: string; + } + interface SourceMapping { + generatedLine: number; + generatedColumn: number; + originalSource: string; + originalLine: number; + originalColumn: number; + } + interface SourceOrigin { + /** + * The name of the range in the source map, if one was provided + */ + name?: string; + /** + * The file name of the original source, as reported in the SourceMap + */ + fileName: string; + /** + * The 1-indexed lineNumber of the corresponding call site in the original source + */ + lineNumber: number; + /** + * The 1-indexed columnNumber of the corresponding call site in the original source + */ + columnNumber: number; + } + /** + * @since v13.7.0, v12.17.0 + */ + class SourceMap { + /** + * Getter for the payload used to construct the `SourceMap` instance. + */ + readonly payload: SourceMapPayload; + constructor(payload: SourceMapPayload); + /** + * Given a line offset and column offset in the generated source + * file, returns an object representing the SourceMap range in the + * original file if found, or an empty object if not. + * + * The object returned contains the following keys: + * + * The returned value represents the raw range as it appears in the + * SourceMap, based on zero-indexed offsets, _not_ 1-indexed line and + * column numbers as they appear in Error messages and CallSite + * objects. + * + * To get the corresponding 1-indexed line and column numbers from a + * lineNumber and columnNumber as they are reported by Error stacks + * and CallSite objects, use `sourceMap.findOrigin(lineNumber, columnNumber)` + * @param lineOffset The zero-indexed line number offset in the generated source + * @param columnOffset The zero-indexed column number offset in the generated source + */ + findEntry(lineOffset: number, columnOffset: number): SourceMapping; + /** + * Given a 1-indexed `lineNumber` and `columnNumber` from a call site in the generated source, + * find the corresponding call site location in the original source. + * + * If the `lineNumber` and `columnNumber` provided are not found in any source map, + * then an empty object is returned. + * @param lineNumber The 1-indexed line number of the call site in the generated source + * @param columnNumber The 1-indexed column number of the call site in the generated source + */ + findOrigin(lineNumber: number, columnNumber: number): SourceOrigin | {}; + } + interface ImportAttributes extends NodeJS.Dict { + type?: string | undefined; + } + type ModuleFormat = "builtin" | "commonjs" | "json" | "module" | "wasm"; + type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray; + interface GlobalPreloadContext { + port: MessagePort; + } + /** + * @deprecated This hook will be removed in a future version. + * Use `initialize` instead. When a loader has an `initialize` export, `globalPreload` will be ignored. + * + * Sometimes it might be necessary to run some code inside of the same global scope that the application runs in. + * This hook allows the return of a string that is run as a sloppy-mode script on startup. + * + * @param context Information to assist the preload code + * @return Code to run before application startup + */ + type GlobalPreloadHook = (context: GlobalPreloadContext) => string; + /** + * The `initialize` hook provides a way to define a custom function that runs in the hooks thread + * when the hooks module is initialized. Initialization happens when the hooks module is registered via `register`. + * + * This hook can receive data from a `register` invocation, including ports and other transferrable objects. + * The return value of `initialize` can be a `Promise`, in which case it will be awaited before the main application thread execution resumes. + */ + type InitializeHook = (data: Data) => void | Promise; + interface ResolveHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + /** + * The module importing this one, or undefined if this is the Node.js entry point + */ + parentURL: string | undefined; + } + interface ResolveFnOutput { + /** + * A hint to the load hook (it might be ignored) + */ + format?: ModuleFormat | null | undefined; + /** + * The import attributes to use when caching the module (optional; if excluded the input will be used) + */ + importAttributes?: ImportAttributes | undefined; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The absolute URL to which this input resolves + */ + url: string; + } + /** + * The `resolve` hook chain is responsible for resolving file URL for a given module specifier and parent URL, and optionally its format (such as `'module'`) as a hint to the `load` hook. + * If a format is specified, the load hook is ultimately responsible for providing the final `format` value (and it is free to ignore the hint provided by `resolve`); + * if `resolve` provides a format, a custom `load` hook is required even if only to pass the value to the Node.js default `load` hook. + * + * @param specifier The specified URL path of the module to be resolved + * @param context + * @param nextResolve The subsequent `resolve` hook in the chain, or the Node.js default `resolve` hook after the last user-supplied resolve hook + */ + type ResolveHook = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: ResolveHookContext, + ) => ResolveFnOutput | Promise, + ) => ResolveFnOutput | Promise; + interface LoadHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * The format optionally supplied by the `resolve` hook chain + */ + format: ModuleFormat; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + } + interface LoadFnOutput { + format: ModuleFormat; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The source for Node.js to evaluate + */ + source?: ModuleSource; + } + /** + * The `load` hook provides a way to define a custom method of determining how a URL should be interpreted, retrieved, and parsed. + * It is also in charge of validating the import assertion. + * + * @param url The URL/path of the module to be loaded + * @param context Metadata about the module + * @param nextLoad The subsequent `load` hook in the chain, or the Node.js default `load` hook after the last user-supplied `load` hook + */ + type LoadHook = ( + url: string, + context: LoadHookContext, + nextLoad: (url: string, context?: LoadHookContext) => LoadFnOutput | Promise, + ) => LoadFnOutput | Promise; + } + interface RegisterOptions { + parentURL: string | URL; + data?: Data | undefined; + transferList?: any[] | undefined; + } + interface Module extends NodeModule {} + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequire(path: string | URL): NodeRequire; + static builtinModules: string[]; + static isBuiltin(moduleName: string): boolean; + static Module: typeof Module; + static register( + specifier: string | URL, + parentURL?: string | URL, + options?: RegisterOptions, + ): void; + static register(specifier: string | URL, options?: RegisterOptions): void; + constructor(id: string, parent?: Module); + } + global { + interface ImportMeta { + /** + * The directory name of the current module. This is the same as the `path.dirname()` of the `import.meta.filename`. + * **Caveat:** only present on `file:` modules. + */ + dirname: string; + /** + * The full absolute path and filename of the current module, with symlinks resolved. + * This is the same as the `url.fileURLToPath()` of the `import.meta.url`. + * **Caveat:** only local modules support this property. Modules not using the `file:` protocol will not provide it. + */ + filename: string; + /** + * The absolute `file:` URL of the module. + */ + url: string; + /** + * Provides a module-relative resolution function scoped to each module, returning + * the URL string. + * + * Second `parent` parameter is only used when the `--experimental-import-meta-resolve` + * command flag enabled. + * + * @since v20.6.0 + * + * @param specifier The module specifier to resolve relative to `parent`. + * @param parent The absolute parent module URL to resolve from. + * @returns The absolute (`file:`) URL string for the resolved module. + */ + resolve(specifier: string, parent?: string | URL | undefined): string; + } + } + export = Module; +} +declare module "node:module" { + import module = require("module"); + export = module; +} diff --git a/node_modules/@types/node/net.d.ts b/node_modules/@types/node/net.d.ts new file mode 100644 index 0000000..15ed7b7 --- /dev/null +++ b/node_modules/@types/node/net.d.ts @@ -0,0 +1,999 @@ +/** + * > Stability: 2 - Stable + * + * The `node:net` module provides an asynchronous network API for creating stream-based + * TCP or `IPC` servers ({@link createServer}) and clients + * ({@link createConnection}). + * + * It can be accessed using: + * + * ```js + * const net = require('node:net'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/net.js) + */ +declare module "net" { + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import * as dns from "node:dns"; + type LookupFunction = ( + hostname: string, + options: dns.LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | dns.LookupAddress[], family?: number) => void, + ) => void; + interface AddressInfo { + address: string; + family: string; + port: number; + } + interface SocketConstructorOpts { + fd?: number | undefined; + allowHalfOpen?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + signal?: AbortSignal; + } + interface OnReadOpts { + buffer: Uint8Array | (() => Uint8Array); + /** + * This function is called for every chunk of incoming data. + * Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer. + * Return false from this function to implicitly pause() the socket. + */ + callback(bytesWritten: number, buf: Uint8Array): boolean; + } + interface ConnectOpts { + /** + * If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket. + * Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will + * still be emitted as normal and methods like pause() and resume() will also behave as expected. + */ + onread?: OnReadOpts | undefined; + } + interface TcpSocketConnectOpts extends ConnectOpts { + port: number; + host?: string | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + hints?: number | undefined; + family?: number | undefined; + lookup?: LookupFunction | undefined; + noDelay?: boolean | undefined; + keepAlive?: boolean | undefined; + keepAliveInitialDelay?: number | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamily?: boolean | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamilyAttemptTimeout?: number | undefined; + } + interface IpcSocketConnectOpts extends ConnectOpts { + path: string; + } + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + type SocketReadyState = "opening" | "open" | "readOnly" | "writeOnly" | "closed"; + /** + * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint + * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also + * an `EventEmitter`. + * + * A `net.Socket` can be created by the user and used directly to interact with + * a server. For example, it is returned by {@link createConnection}, + * so the user can use it to talk to the server. + * + * It can also be created by Node.js and passed to the user when a connection + * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use + * it to interact with the client. + * @since v0.3.4 + */ + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + /** + * Destroys the socket after all data is written. If the `finish` event was already emitted the socket is destroyed immediately. + * If the socket is still writable it implicitly calls `socket.end()`. + * @since v0.3.4 + */ + destroySoon(): void; + /** + * Sends data on the socket. The second parameter specifies the encoding in the + * case of a string. It defaults to UTF8 encoding. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. + * + * The optional `callback` parameter will be executed when the data is finally + * written out, which may not be immediately. + * + * See `Writable` stream `write()` method for more + * information. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + */ + write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean; + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => void): boolean; + /** + * Initiate a connection on a given socket. + * + * Possible signatures: + * + * * `socket.connect(options[, connectListener])` + * * `socket.connect(path[, connectListener])` for `IPC` connections. + * * `socket.connect(port[, host][, connectListener])` for TCP connections. + * * Returns: `net.Socket` The socket itself. + * + * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, + * instead of a `'connect'` event, an `'error'` event will be emitted with + * the error passed to the `'error'` listener. + * The last parameter `connectListener`, if supplied, will be added as a listener + * for the `'connect'` event **once**. + * + * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined + * behavior. + */ + connect(options: SocketConnectOpts, connectionListener?: () => void): this; + connect(port: number, host: string, connectionListener?: () => void): this; + connect(port: number, connectionListener?: () => void): this; + connect(path: string, connectionListener?: () => void): this; + /** + * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. + * @since v0.1.90 + * @return The socket itself. + */ + setEncoding(encoding?: BufferEncoding): this; + /** + * Pauses the reading of data. That is, `'data'` events will not be emitted. + * Useful to throttle back an upload. + * @return The socket itself. + */ + pause(): this; + /** + * Close the TCP connection by sending an RST packet and destroy the stream. + * If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected. + * Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. + * If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error. + * @since v18.3.0, v16.17.0 + */ + resetAndDestroy(): this; + /** + * Resumes reading after a call to `socket.pause()`. + * @return The socket itself. + */ + resume(): this; + /** + * Sets the socket to timeout after `timeout` milliseconds of inactivity on + * the socket. By default `net.Socket` do not have a timeout. + * + * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to + * end the connection. + * + * ```js + * socket.setTimeout(3000); + * socket.on('timeout', () => { + * console.log('socket timeout'); + * socket.end(); + * }); + * ``` + * + * If `timeout` is 0, then the existing idle timeout is disabled. + * + * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. + * @since v0.1.90 + * @return The socket itself. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Enable/disable the use of Nagle's algorithm. + * + * When a TCP connection is created, it will have Nagle's algorithm enabled. + * + * Nagle's algorithm delays data before it is sent via the network. It attempts + * to optimize throughput at the expense of latency. + * + * Passing `true` for `noDelay` or not passing an argument will disable Nagle's + * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's + * algorithm. + * @since v0.1.90 + * @param [noDelay=true] + * @return The socket itself. + */ + setNoDelay(noDelay?: boolean): this; + /** + * Enable/disable keep-alive functionality, and optionally set the initial + * delay before the first keepalive probe is sent on an idle socket. + * + * Set `initialDelay` (in milliseconds) to set the delay between the last + * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default + * (or previous) setting. + * + * Enabling the keep-alive functionality will set the following socket options: + * + * * `SO_KEEPALIVE=1` + * * `TCP_KEEPIDLE=initialDelay` + * * `TCP_KEEPCNT=10` + * * `TCP_KEEPINTVL=1` + * @since v0.1.92 + * @param [enable=false] + * @param [initialDelay=0] + * @return The socket itself. + */ + setKeepAlive(enable?: boolean, initialDelay?: number): this; + /** + * Returns the bound `address`, the address `family` name and `port` of the + * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + * @since v0.1.90 + */ + address(): AddressInfo | {}; + /** + * Calling `unref()` on a socket will allow the program to exit if this is the only + * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + unref(): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior). + * If the socket is `ref`ed calling `ref` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + ref(): this; + /** + * This property is only present if the family autoselection algorithm is enabled in `socket.connect(options)` + * and it is an array of the addresses that have been attempted. + * + * Each address is a string in the form of `$IP:$PORT`. + * If the connection was successful, then the last address is the one that the socket is currently connected to. + * @since v19.4.0 + */ + readonly autoSelectFamilyAttemptedAddresses: string[]; + /** + * This property shows the number of characters buffered for writing. The buffer + * may contain strings whose length after encoding is not yet known. So this number + * is only an approximation of the number of bytes in the buffer. + * + * `net.Socket` has the property that `socket.write()` always works. This is to + * help users get up and running quickly. The computer cannot always keep up + * with the amount of data that is written to a socket. The network connection + * simply might be too slow. Node.js will internally queue up the data written to a + * socket and send it out over the wire when it is possible. + * + * The consequence of this internal buffering is that memory may grow. + * Users who experience large or growing `bufferSize` should attempt to + * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. + * @since v0.3.8 + * @deprecated Since v14.6.0 - Use `writableLength` instead. + */ + readonly bufferSize: number; + /** + * The amount of received bytes. + * @since v0.5.3 + */ + readonly bytesRead: number; + /** + * The amount of bytes sent. + * @since v0.5.3 + */ + readonly bytesWritten: number; + /** + * If `true`, `socket.connect(options[, connectListener])` was + * called and has not yet finished. It will stay `true` until the socket becomes + * connected, then it is set to `false` and the `'connect'` event is emitted. Note + * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. + * @since v6.1.0 + */ + readonly connecting: boolean; + /** + * This is `true` if the socket is not connected yet, either because `.connect()`has not yet been called or because it is still in the process of connecting + * (see `socket.connecting`). + * @since v11.2.0, v10.16.0 + */ + readonly pending: boolean; + /** + * See `writable.destroyed` for further details. + */ + readonly destroyed: boolean; + /** + * The string representation of the local IP address the remote client is + * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client + * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. + * @since v0.9.6 + */ + readonly localAddress?: string; + /** + * The numeric representation of the local port. For example, `80` or `21`. + * @since v0.9.6 + */ + readonly localPort?: number; + /** + * The string representation of the local IP family. `'IPv4'` or `'IPv6'`. + * @since v18.8.0, v16.18.0 + */ + readonly localFamily?: string; + /** + * This property represents the state of the connection as a string. + * + * * If the stream is connecting `socket.readyState` is `opening`. + * * If the stream is readable and writable, it is `open`. + * * If the stream is readable and not writable, it is `readOnly`. + * * If the stream is not readable and writable, it is `writeOnly`. + * @since v0.5.0 + */ + readonly readyState: SocketReadyState; + /** + * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remoteAddress?: string | undefined; + /** + * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.11.14 + */ + readonly remoteFamily?: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remotePort?: number | undefined; + /** + * The socket timeout in milliseconds as set by `socket.setTimeout()`. + * It is `undefined` if a timeout has not been set. + * @since v10.7.0 + */ + readonly timeout?: number | undefined; + /** + * Half-closes the socket. i.e., it sends a FIN packet. It is possible the + * server will still send some data. + * + * See `writable.end()` for further details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(callback?: () => void): this; + end(buffer: Uint8Array | string, callback?: () => void): this; + end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. connectionAttempt + * 4. connectionAttemptFailed + * 5. connectionAttemptTimeout + * 6. data + * 7. drain + * 8. end + * 9. error + * 10. lookup + * 11. ready + * 12. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (hadError: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + addListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number) => void, + ): this; + addListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + addListener(event: "data", listener: (data: Buffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "timeout", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", hadError: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "connectionAttempt", ip: string, port: number, family: number): boolean; + emit(event: "connectionAttemptFailed", ip: string, port: number, family: number): boolean; + emit(event: "connectionAttemptTimeout", ip: string, port: number, family: number): boolean; + emit(event: "data", data: Buffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "ready"): boolean; + emit(event: "timeout"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (hadError: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + on(event: "connectionAttemptFailed", listener: (ip: string, port: number, family: number) => void): this; + on(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this; + on(event: "data", listener: (data: Buffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + on(event: "ready", listener: () => void): this; + on(event: "timeout", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (hadError: boolean) => void): this; + once(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + once(event: "connectionAttemptFailed", listener: (ip: string, port: number, family: number) => void): this; + once(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: Buffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + once(event: "ready", listener: () => void): this; + once(event: "timeout", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (hadError: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + prependListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependListener(event: "data", listener: (data: Buffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (hadError: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener( + event: "connectionAttempt", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener(event: "data", listener: (data: Buffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + interface ListenOptions extends Abortable { + port?: number | undefined; + host?: string | undefined; + backlog?: number | undefined; + path?: string | undefined; + exclusive?: boolean | undefined; + readableAll?: boolean | undefined; + writableAll?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + } + interface ServerOpts { + /** + * Indicates whether half-opened TCP connections are allowed. + * @default false + */ + allowHalfOpen?: boolean | undefined; + /** + * Indicates whether the socket should be paused on incoming connections. + * @default false + */ + pauseOnConnect?: boolean | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default false + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + } + interface DropArgument { + localAddress?: string; + localPort?: number; + localFamily?: string; + remoteAddress?: string; + remotePort?: number; + remoteFamily?: string; + } + /** + * This class is used to create a TCP or `IPC` server. + * @since v0.1.90 + */ + class Server extends EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); + /** + * Start a server listening for connections. A `net.Server` can be a TCP or + * an `IPC` server depending on what it listens to. + * + * Possible signatures: + * + * * `server.listen(handle[, backlog][, callback])` + * * `server.listen(options[, callback])` + * * `server.listen(path[, backlog][, callback])` for `IPC` servers + * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + * + * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` + * event. + * + * All `listen()` methods can take a `backlog` parameter to specify the maximum + * length of the queue of pending connections. The actual length will be determined + * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn` on Linux. The default value of this parameter is 511 (not 512). + * + * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for + * details). + * + * The `server.listen()` method can be called again if and only if there was an + * error during the first `server.listen()` call or `server.close()` has been + * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + * + * One of the most common errors raised when listening is `EADDRINUSE`. + * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry + * after a certain amount of time: + * + * ```js + * server.on('error', (e) => { + * if (e.code === 'EADDRINUSE') { + * console.error('Address in use, retrying...'); + * setTimeout(() => { + * server.close(); + * server.listen(PORT, HOST); + * }, 1000); + * } + * }); + * ``` + */ + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, hostname?: string, listeningListener?: () => void): this; + listen(port?: number, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, listeningListener?: () => void): this; + listen(path: string, backlog?: number, listeningListener?: () => void): this; + listen(path: string, listeningListener?: () => void): this; + listen(options: ListenOptions, listeningListener?: () => void): this; + listen(handle: any, backlog?: number, listeningListener?: () => void): this; + listen(handle: any, listeningListener?: () => void): this; + /** + * Stops the server from accepting new connections and keeps existing + * connections. This function is asynchronous, the server is finally closed + * when all connections are ended and the server emits a `'close'` event. + * The optional `callback` will be called once the `'close'` event occurs. Unlike + * that event, it will be called with an `Error` as its only argument if the server + * was not open when it was closed. + * @since v0.1.90 + * @param callback Called when the server is closed. + */ + close(callback?: (err?: Error) => void): this; + /** + * Returns the bound `address`, the address `family` name, and `port` of the server + * as reported by the operating system if listening on an IP socket + * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. + * + * For a server listening on a pipe or Unix domain socket, the name is returned + * as a string. + * + * ```js + * const server = net.createServer((socket) => { + * socket.end('goodbye\n'); + * }).on('error', (err) => { + * // Handle errors here. + * throw err; + * }); + * + * // Grab an arbitrary unused port. + * server.listen(() => { + * console.log('opened server on', server.address()); + * }); + * ``` + * + * `server.address()` returns `null` before the `'listening'` event has been + * emitted or after calling `server.close()`. + * @since v0.1.90 + */ + address(): AddressInfo | string | null; + /** + * Asynchronously get the number of concurrent connections on the server. Works + * when sockets were sent to forks. + * + * Callback should take two arguments `err` and `count`. + * @since v0.9.7 + */ + getConnections(cb: (error: Error | null, count: number) => void): void; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will _not_ let the program exit if it's the only server left (the default behavior). + * If the server is `ref`ed calling `ref()` again will have no effect. + * @since v0.9.1 + */ + ref(): this; + /** + * Calling `unref()` on a server will allow the program to exit if this is the only + * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + */ + unref(): this; + /** + * Set this property to reject connections when the server's connection count gets + * high. + * + * It is not recommended to use this option once a socket has been sent to a child + * with `child_process.fork()`. + * @since v0.2.0 + */ + maxConnections: number; + connections: number; + /** + * Indicates whether or not the server is listening for connections. + * @since v5.7.0 + */ + readonly listening: boolean; + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + * 5. drop + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "drop", listener: (data?: DropArgument) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "drop", data?: DropArgument): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "drop", listener: (data?: DropArgument) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "drop", listener: (data?: DropArgument) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "drop", listener: (data?: DropArgument) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "drop", listener: (data?: DropArgument) => void): this; + /** + * Calls {@link Server.close()} and returns a promise that fulfills when the server has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } + type IPVersion = "ipv4" | "ipv6"; + /** + * The `BlockList` object can be used with some network APIs to specify rules for + * disabling inbound or outbound access to specific IP addresses, IP ranges, or + * IP subnets. + * @since v15.0.0, v14.18.0 + */ + class BlockList { + /** + * Adds a rule to block the given IP address. + * @since v15.0.0, v14.18.0 + * @param address An IPv4 or IPv6 address. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addAddress(address: string, type?: IPVersion): void; + addAddress(address: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). + * @since v15.0.0, v14.18.0 + * @param start The starting IPv4 or IPv6 address in the range. + * @param end The ending IPv4 or IPv6 address in the range. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addRange(start: string, end: string, type?: IPVersion): void; + addRange(start: SocketAddress, end: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses specified as a subnet mask. + * @since v15.0.0, v14.18.0 + * @param net The network IPv4 or IPv6 address. + * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addSubnet(net: SocketAddress, prefix: number): void; + addSubnet(net: string, prefix: number, type?: IPVersion): void; + /** + * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. + * + * ```js + * const blockList = new net.BlockList(); + * blockList.addAddress('123.123.123.123'); + * blockList.addRange('10.0.0.1', '10.0.0.10'); + * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); + * + * console.log(blockList.check('123.123.123.123')); // Prints: true + * console.log(blockList.check('10.0.0.3')); // Prints: true + * console.log(blockList.check('222.111.111.222')); // Prints: false + * + * // IPv6 notation for IPv4 addresses works: + * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true + * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true + * ``` + * @since v15.0.0, v14.18.0 + * @param address The IP address to check + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + check(address: SocketAddress): boolean; + check(address: string, type?: IPVersion): boolean; + /** + * The list of rules added to the blocklist. + * @since v15.0.0, v14.18.0 + */ + rules: readonly string[]; + } + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + /** + * Creates a new TCP or `IPC` server. + * + * If `allowHalfOpen` is set to `true`, when the other end of the socket + * signals the end of transmission, the server will only send back the end of + * transmission when `socket.end()` is explicitly called. For example, in the + * context of TCP, when a FIN packed is received, a FIN packed is sent + * back only when `socket.end()` is explicitly called. Until then the + * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. + * + * If `pauseOnConnect` is set to `true`, then the socket associated with each + * incoming connection will be paused, and no data will be read from its handle. + * This allows connections to be passed between processes without any data being + * read by the original process. To begin reading data from a paused socket, call `socket.resume()`. + * + * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. + * + * Here is an example of a TCP echo server which listens for connections + * on port 8124: + * + * ```js + * const net = require('node:net'); + * const server = net.createServer((c) => { + * // 'connection' listener. + * console.log('client connected'); + * c.on('end', () => { + * console.log('client disconnected'); + * }); + * c.write('hello\r\n'); + * c.pipe(c); + * }); + * server.on('error', (err) => { + * throw err; + * }); + * server.listen(8124, () => { + * console.log('server bound'); + * }); + * ``` + * + * Test this by using `telnet`: + * + * ```bash + * telnet localhost 8124 + * ``` + * + * To listen on the socket `/tmp/echo.sock`: + * + * ```js + * server.listen('/tmp/echo.sock', () => { + * console.log('server bound'); + * }); + * ``` + * + * Use `nc` to connect to a Unix domain socket server: + * + * ```bash + * nc -U /tmp/echo.sock + * ``` + * @since v0.5.0 + * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. + */ + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; + /** + * Aliases to {@link createConnection}. + * + * Possible signatures: + * + * * {@link connect} + * * {@link connect} for `IPC` connections. + * * {@link connect} for TCP connections. + */ + function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; + function connect(port: number, host?: string, connectionListener?: () => void): Socket; + function connect(path: string, connectionListener?: () => void): Socket; + /** + * A factory function, which creates a new {@link Socket}, + * immediately initiates connection with `socket.connect()`, + * then returns the `net.Socket` that starts the connection. + * + * When the connection is established, a `'connect'` event will be emitted + * on the returned socket. The last parameter `connectListener`, if supplied, + * will be added as a listener for the `'connect'` event **once**. + * + * Possible signatures: + * + * * {@link createConnection} + * * {@link createConnection} for `IPC` connections. + * * {@link createConnection} for TCP connections. + * + * The {@link connect} function is an alias to this function. + */ + function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; + function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; + function createConnection(path: string, connectionListener?: () => void): Socket; + /** + * Gets the current default value of the `autoSelectFamily` option of `socket.connect(options)`. + * The initial default value is `true`, unless the command line option`--no-network-family-autoselection` is provided. + * @since v19.4.0 + */ + function getDefaultAutoSelectFamily(): boolean; + /** + * Sets the default value of the `autoSelectFamily` option of `socket.connect(options)`. + * @since v19.4.0 + */ + function setDefaultAutoSelectFamily(value: boolean): void; + /** + * Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * The initial default value is `250` or the value specified via the command line option `--network-family-autoselection-attempt-timeout`. + * @returns The current default value of the `autoSelectFamilyAttemptTimeout` option. + * @since v19.8.0, v18.8.0 + */ + function getDefaultAutoSelectFamilyAttemptTimeout(): number; + /** + * Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * @param value The new default value, which must be a positive number. If the number is less than `10`, the value `10` is used instead. The initial default value is `250` or the value specified via the command line + * option `--network-family-autoselection-attempt-timeout`. + * @since v19.8.0, v18.8.0 + */ + function setDefaultAutoSelectFamilyAttemptTimeout(value: number): void; + /** + * Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4 + * address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`. + * + * ```js + * net.isIP('::1'); // returns 6 + * net.isIP('127.0.0.1'); // returns 4 + * net.isIP('127.000.000.001'); // returns 0 + * net.isIP('127.0.0.1/24'); // returns 0 + * net.isIP('fhqwhgads'); // returns 0 + * ``` + * @since v0.3.0 + */ + function isIP(input: string): number; + /** + * Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no + * leading zeroes. Otherwise, returns `false`. + * + * ```js + * net.isIPv4('127.0.0.1'); // returns true + * net.isIPv4('127.000.000.001'); // returns false + * net.isIPv4('127.0.0.1/24'); // returns false + * net.isIPv4('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv4(input: string): boolean; + /** + * Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`. + * + * ```js + * net.isIPv6('::1'); // returns true + * net.isIPv6('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv6(input: string): boolean; + interface SocketAddressInitOptions { + /** + * The network address as either an IPv4 or IPv6 string. + * @default 127.0.0.1 + */ + address?: string | undefined; + /** + * @default `'ipv4'` + */ + family?: IPVersion | undefined; + /** + * An IPv6 flow-label used only if `family` is `'ipv6'`. + * @default 0 + */ + flowlabel?: number | undefined; + /** + * An IP port. + * @default 0 + */ + port?: number | undefined; + } + /** + * @since v15.14.0, v14.18.0 + */ + class SocketAddress { + constructor(options: SocketAddressInitOptions); + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly address: string; + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly family: IPVersion; + /** + * @since v15.14.0, v14.18.0 + */ + readonly port: number; + /** + * @since v15.14.0, v14.18.0 + */ + readonly flowlabel: number; + } +} +declare module "node:net" { + export * from "net"; +} diff --git a/node_modules/@types/node/os.d.ts b/node_modules/@types/node/os.d.ts new file mode 100644 index 0000000..d0593ff --- /dev/null +++ b/node_modules/@types/node/os.d.ts @@ -0,0 +1,495 @@ +/** + * The `node:os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * const os = require('node:os'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/os.js) + */ +declare module "os" { + interface CpuInfo { + model: string; + speed: number; + times: { + /** The number of milliseconds the CPU has spent in user mode. */ + user: number; + /** The number of milliseconds the CPU has spent in nice mode. */ + nice: number; + /** The number of milliseconds the CPU has spent in sys mode. */ + sys: number; + /** The number of milliseconds the CPU has spent in idle mode. */ + idle: number; + /** The number of milliseconds the CPU has spent in irq mode. */ + irq: number; + }; + } + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + scopeid?: undefined; + } + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T | null; + homedir: T; + } + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + /** + * Returns the host name of the operating system as a string. + * @since v0.3.3 + */ + function hostname(): string; + /** + * Returns an array containing the 1, 5, and 15 minute load averages. + * + * The load average is a measure of system activity calculated by the operating + * system and expressed as a fractional number. + * + * The load average is a Unix-specific concept. On Windows, the return value is + * always `[0, 0, 0]`. + * @since v0.3.3 + */ + function loadavg(): number[]; + /** + * Returns the system uptime in number of seconds. + * @since v0.3.3 + */ + function uptime(): number; + /** + * Returns the amount of free system memory in bytes as an integer. + * @since v0.3.3 + */ + function freemem(): number; + /** + * Returns the total amount of system memory in bytes as an integer. + * @since v0.3.3 + */ + function totalmem(): number; + /** + * Returns an array of objects containing information about each logical CPU core. + * The array will be empty if no CPU information is available, such as if the `/proc` file system is unavailable. + * + * The properties included on each object include: + * + * ```js + * [ + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 252020, + * nice: 0, + * sys: 30340, + * idle: 1070356870, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 306960, + * nice: 0, + * sys: 26980, + * idle: 1071569080, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 248450, + * nice: 0, + * sys: 21750, + * idle: 1070919370, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 256880, + * nice: 0, + * sys: 19430, + * idle: 1070905480, + * irq: 20, + * }, + * }, + * ] + * ``` + * + * `nice` values are POSIX-only. On Windows, the `nice` values of all processors + * are always 0. + * + * `os.cpus().length` should not be used to calculate the amount of parallelism + * available to an application. Use {@link availableParallelism} for this purpose. + * @since v0.3.3 + */ + function cpus(): CpuInfo[]; + /** + * Returns an estimate of the default amount of parallelism a program should use. + * Always returns a value greater than zero. + * + * This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism). + * @since v19.4.0, v18.14.0 + */ + function availableParallelism(): number; + /** + * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it + * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. + * + * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information + * about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. + * @since v0.3.3 + */ + function type(): string; + /** + * Returns the operating system as a string. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See + * [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v0.3.3 + */ + function release(): string; + /** + * Returns an object containing network interfaces that have been assigned a + * network address. + * + * Each key on the returned object identifies a network interface. The associated + * value is an array of objects that each describe an assigned network address. + * + * The properties available on the assigned network address object include: + * + * ```js + * { + * lo: [ + * { + * address: '127.0.0.1', + * netmask: '255.0.0.0', + * family: 'IPv4', + * mac: '00:00:00:00:00:00', + * internal: true, + * cidr: '127.0.0.1/8' + * }, + * { + * address: '::1', + * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', + * family: 'IPv6', + * mac: '00:00:00:00:00:00', + * scopeid: 0, + * internal: true, + * cidr: '::1/128' + * } + * ], + * eth0: [ + * { + * address: '192.168.1.108', + * netmask: '255.255.255.0', + * family: 'IPv4', + * mac: '01:02:03:0a:0b:0c', + * internal: false, + * cidr: '192.168.1.108/24' + * }, + * { + * address: 'fe80::a00:27ff:fe4e:66a1', + * netmask: 'ffff:ffff:ffff:ffff::', + * family: 'IPv6', + * mac: '01:02:03:0a:0b:0c', + * scopeid: 1, + * internal: false, + * cidr: 'fe80::a00:27ff:fe4e:66a1/64' + * } + * ] + * } + * ``` + * @since v0.6.0 + */ + function networkInterfaces(): NodeJS.Dict; + /** + * Returns the string path of the current user's home directory. + * + * On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it + * uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. + * + * On Windows, it uses the `USERPROFILE` environment variable if defined. + * Otherwise it uses the path to the profile directory of the current user. + * @since v2.3.0 + */ + function homedir(): string; + /** + * Returns information about the currently effective user. On POSIX platforms, + * this is typically a subset of the password file. The returned object includes + * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and `gid` fields are `-1`, and `shell` is `null`. + * + * The value of `homedir` returned by `os.userInfo()` is provided by the operating + * system. This differs from the result of `os.homedir()`, which queries + * environment variables for the home directory before falling back to the + * operating system response. + * + * Throws a [`SystemError`](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-systemerror) if a user has no `username` or `homedir`. + * @since v6.0.0 + */ + function userInfo(options: { encoding: "buffer" }): UserInfo; + function userInfo(options?: { encoding: BufferEncoding }): UserInfo; + type SignalConstants = { + [key in NodeJS.Signals]: number; + }; + namespace constants { + const UV_UDP_REUSEADDR: number; + namespace signals {} + const signals: SignalConstants; + namespace errno { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EDQUOT: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const EMULTIHOP: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ESTALE: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + } + namespace dlopen { + const RTLD_LAZY: number; + const RTLD_NOW: number; + const RTLD_GLOBAL: number; + const RTLD_LOCAL: number; + const RTLD_DEEPBIND: number; + } + namespace priority { + const PRIORITY_LOW: number; + const PRIORITY_BELOW_NORMAL: number; + const PRIORITY_NORMAL: number; + const PRIORITY_ABOVE_NORMAL: number; + const PRIORITY_HIGH: number; + const PRIORITY_HIGHEST: number; + } + } + const devNull: string; + /** + * The operating system-specific end-of-line marker. + * * `\n` on POSIX + * * `\r\n` on Windows + */ + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, + * and `'x64'`. + * + * The return value is equivalent to [process.arch](https://nodejs.org/docs/latest-v22.x/api/process.html#processarch). + * @since v0.5.0 + */ + function arch(): string; + /** + * Returns a string identifying the kernel version. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v13.11.0, v12.17.0 + */ + function version(): string; + /** + * Returns a string identifying the operating system platform for which + * the Node.js binary was compiled. The value is set at compile time. + * Possible values are `'aix'`, `'darwin'`, `'freebsd'`, `'linux'`, `'openbsd'`, `'sunos'`, and `'win32'`. + * + * The return value is equivalent to `process.platform`. + * + * The value `'android'` may also be returned if Node.js is built on the Android + * operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.5.0 + */ + function platform(): NodeJS.Platform; + /** + * Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`, `mips`, `mips64`, `ppc64`, `ppc64le`, `s390`, `s390x`, `i386`, `i686`, `x86_64`. + * + * On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v18.9.0, v16.18.0 + */ + function machine(): string; + /** + * Returns the operating system's default directory for temporary files as a + * string. + * @since v0.9.9 + */ + function tmpdir(): string; + /** + * Returns a string identifying the endianness of the CPU for which the Node.js + * binary was compiled. + * + * Possible values are `'BE'` for big endian and `'LE'` for little endian. + * @since v0.9.4 + */ + function endianness(): "BE" | "LE"; + /** + * Returns the scheduling priority for the process specified by `pid`. If `pid` is + * not provided or is `0`, the priority of the current process is returned. + * @since v10.10.0 + * @param [pid=0] The process ID to retrieve scheduling priority for. + */ + function getPriority(pid?: number): number; + /** + * Attempts to set the scheduling priority for the process specified by `pid`. If `pid` is not provided or is `0`, the process ID of the current process is used. + * + * The `priority` input must be an integer between `-20` (high priority) and `19` (low priority). Due to differences between Unix priority levels and Windows + * priority classes, `priority` is mapped to one of six priority constants in `os.constants.priority`. When retrieving a process priority level, this range + * mapping may cause the return value to be slightly different on Windows. To avoid + * confusion, set `priority` to one of the priority constants. + * + * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user + * privileges. Otherwise the set priority will be silently reduced to `PRIORITY_HIGH`. + * @since v10.10.0 + * @param [pid=0] The process ID to set scheduling priority for. + * @param priority The scheduling priority to assign to the process. + */ + function setPriority(priority: number): void; + function setPriority(pid: number, priority: number): void; +} +declare module "node:os" { + export * from "os"; +} diff --git a/node_modules/@types/node/package.json b/node_modules/@types/node/package.json new file mode 100644 index 0000000..f485a93 --- /dev/null +++ b/node_modules/@types/node/package.json @@ -0,0 +1,217 @@ +{ + "name": "@types/node", + "version": "22.5.5", + "description": "TypeScript definitions for node", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "license": "MIT", + "contributors": [ + { + "name": "Microsoft TypeScript", + "githubUsername": "Microsoft", + "url": "https://github.com/Microsoft" + }, + { + "name": "Alberto Schiabel", + "githubUsername": "jkomyno", + "url": "https://github.com/jkomyno" + }, + { + "name": "Alvis HT Tang", + "githubUsername": "alvis", + "url": "https://github.com/alvis" + }, + { + "name": "Andrew Makarov", + "githubUsername": "r3nya", + "url": "https://github.com/r3nya" + }, + { + "name": "Benjamin Toueg", + "githubUsername": "btoueg", + "url": "https://github.com/btoueg" + }, + { + "name": "Chigozirim C.", + "githubUsername": "smac89", + "url": "https://github.com/smac89" + }, + { + "name": "David Junger", + "githubUsername": "touffy", + "url": "https://github.com/touffy" + }, + { + "name": "Deividas Bakanas", + "githubUsername": "DeividasBakanas", + "url": "https://github.com/DeividasBakanas" + }, + { + "name": "Eugene Y. Q. Shen", + "githubUsername": "eyqs", + "url": "https://github.com/eyqs" + }, + { + "name": "Hannes Magnusson", + "githubUsername": "Hannes-Magnusson-CK", + "url": "https://github.com/Hannes-Magnusson-CK" + }, + { + "name": "Huw", + "githubUsername": "hoo29", + "url": "https://github.com/hoo29" + }, + { + "name": "Kelvin Jin", + "githubUsername": "kjin", + "url": "https://github.com/kjin" + }, + { + "name": "Klaus Meinhardt", + "githubUsername": "ajafff", + "url": "https://github.com/ajafff" + }, + { + "name": "Lishude", + "githubUsername": "islishude", + "url": "https://github.com/islishude" + }, + { + "name": "Mariusz Wiktorczyk", + "githubUsername": "mwiktorczyk", + "url": "https://github.com/mwiktorczyk" + }, + { + "name": "Mohsen Azimi", + "githubUsername": "mohsen1", + "url": "https://github.com/mohsen1" + }, + { + "name": "Nikita Galkin", + "githubUsername": "galkin", + "url": "https://github.com/galkin" + }, + { + "name": "Parambir Singh", + "githubUsername": "parambirs", + "url": "https://github.com/parambirs" + }, + { + "name": "Sebastian Silbermann", + "githubUsername": "eps1lon", + "url": "https://github.com/eps1lon" + }, + { + "name": "Thomas den Hollander", + "githubUsername": "ThomasdenH", + "url": "https://github.com/ThomasdenH" + }, + { + "name": "Wilco Bakker", + "githubUsername": "WilcoBakker", + "url": "https://github.com/WilcoBakker" + }, + { + "name": "wwwy3y3", + "githubUsername": "wwwy3y3", + "url": "https://github.com/wwwy3y3" + }, + { + "name": "Samuel Ainsworth", + "githubUsername": "samuela", + "url": "https://github.com/samuela" + }, + { + "name": "Kyle Uehlein", + "githubUsername": "kuehlein", + "url": "https://github.com/kuehlein" + }, + { + "name": "Thanik Bhongbhibhat", + "githubUsername": "bhongy", + "url": "https://github.com/bhongy" + }, + { + "name": "Marcin Kopacz", + "githubUsername": "chyzwar", + "url": "https://github.com/chyzwar" + }, + { + "name": "Trivikram Kamat", + "githubUsername": "trivikr", + "url": "https://github.com/trivikr" + }, + { + "name": "Junxiao Shi", + "githubUsername": "yoursunny", + "url": "https://github.com/yoursunny" + }, + { + "name": "Ilia Baryshnikov", + "githubUsername": "qwelias", + "url": "https://github.com/qwelias" + }, + { + "name": "ExE Boss", + "githubUsername": "ExE-Boss", + "url": "https://github.com/ExE-Boss" + }, + { + "name": "Piotr Błażejewicz", + "githubUsername": "peterblazejewicz", + "url": "https://github.com/peterblazejewicz" + }, + { + "name": "Anna Henningsen", + "githubUsername": "addaleax", + "url": "https://github.com/addaleax" + }, + { + "name": "Victor Perin", + "githubUsername": "victorperin", + "url": "https://github.com/victorperin" + }, + { + "name": "Yongsheng Zhang", + "githubUsername": "ZYSzys", + "url": "https://github.com/ZYSzys" + }, + { + "name": "NodeJS Contributors", + "githubUsername": "NodeJS", + "url": "https://github.com/NodeJS" + }, + { + "name": "Linus Unnebäck", + "githubUsername": "LinusU", + "url": "https://github.com/LinusU" + }, + { + "name": "wafuwafu13", + "githubUsername": "wafuwafu13", + "url": "https://github.com/wafuwafu13" + }, + { + "name": "Matteo Collina", + "githubUsername": "mcollina", + "url": "https://github.com/mcollina" + }, + { + "name": "Dmitry Semigradsky", + "githubUsername": "Semigradsky", + "url": "https://github.com/Semigradsky" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "dependencies": { + "undici-types": "~6.19.2" + }, + "typesPublisherContentHash": "49c6854801c6eca5f0c4debaa90673195b7385ea09dc082e76a86be2fa20430f", + "typeScriptVersion": "4.8" +} \ No newline at end of file diff --git a/node_modules/@types/node/path.d.ts b/node_modules/@types/node/path.d.ts new file mode 100644 index 0000000..e66781f --- /dev/null +++ b/node_modules/@types/node/path.d.ts @@ -0,0 +1,200 @@ +declare module "path/posix" { + import path = require("path"); + export = path; +} +declare module "path/win32" { + import path = require("path"); + export = path; +} +/** + * The `node:path` module provides utilities for working with file and directory + * paths. It can be accessed using: + * + * ```js + * const path = require('node:path'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/path.js) + */ +declare module "path" { + namespace path { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string | undefined; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string | undefined; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string | undefined; + /** + * The file extension (if any) such as '.html' + */ + ext?: string | undefined; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string | undefined; + } + interface PlatformPath { + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param path string path to normalize. + * @throws {TypeError} if `path` is not a string. + */ + normalize(path: string): string; + /** + * Join all arguments together and normalize the resulting path. + * + * @param paths paths to join. + * @throws {TypeError} if any of the path segments is not a string. + */ + join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param paths A sequence of paths or path segments. + * @throws {TypeError} if any of the arguments is not a string. + */ + resolve(...paths: string[]): string; + /** + * The `path.matchesGlob()` method determines if `path` matches the `pattern`. + * @param path The path to glob-match against. + * @param pattern The glob to check the path against. + * @returns Whether or not the `path` matched the `pattern`. + * @throws {TypeError} if `path` or `pattern` are not strings. + * @since v22.5.0 + */ + matchesGlob(path: string, pattern: string): boolean; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * If the given {path} is a zero-length string, `false` will be returned. + * + * @param path path to test. + * @throws {TypeError} if `path` is not a string. + */ + isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to} based on the current working directory. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @throws {TypeError} if either `from` or `to` is not a string. + */ + relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + dirname(path: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param path the path to evaluate. + * @param suffix optionally, an extension to remove from the result. + * @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string. + */ + basename(path: string, suffix?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + extname(path: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + readonly sep: "\\" | "/"; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + readonly delimiter: ";" | ":"; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param path path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + parse(path: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathObject path to evaluate. + */ + format(pathObject: FormatInputPathObject): string; + /** + * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. + * If path is not a string, path will be returned without modifications. + * This method is meaningful only on Windows system. + * On POSIX systems, the method is non-operational and always returns path without modifications. + */ + toNamespacedPath(path: string): string; + /** + * Posix specific pathing. + * Same as parent object on posix. + */ + readonly posix: PlatformPath; + /** + * Windows specific pathing. + * Same as parent object on windows + */ + readonly win32: PlatformPath; + } + } + const path: path.PlatformPath; + export = path; +} +declare module "node:path" { + import path = require("path"); + export = path; +} +declare module "node:path/posix" { + import path = require("path/posix"); + export = path; +} +declare module "node:path/win32" { + import path = require("path/win32"); + export = path; +} diff --git a/node_modules/@types/node/perf_hooks.d.ts b/node_modules/@types/node/perf_hooks.d.ts new file mode 100644 index 0000000..6092bd4 --- /dev/null +++ b/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,941 @@ +/** + * This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for + * Node.js-specific performance measurements. + * + * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): + * + * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) + * * [Performance Timeline](https://w3c.github.io/performance-timeline/) + * * [User Timing](https://www.w3.org/TR/user-timing/) + * * [Resource Timing](https://www.w3.org/TR/resource-timing-2/) + * + * ```js + * const { PerformanceObserver, performance } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((items) => { + * console.log(items.getEntries()[0].duration); + * performance.clearMarks(); + * }); + * obs.observe({ type: 'measure' }); + * performance.measure('Start to Now'); + * + * performance.mark('A'); + * doSomeLongRunningProcess(() => { + * performance.measure('A to Now', 'A'); + * + * performance.mark('B'); + * performance.measure('A to B', 'A', 'B'); + * }); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/perf_hooks.js) + */ +declare module "perf_hooks" { + import { AsyncResource } from "node:async_hooks"; + type EntryType = + | "dns" // Node.js only + | "function" // Node.js only + | "gc" // Node.js only + | "http2" // Node.js only + | "http" // Node.js only + | "mark" // available on the Web + | "measure" // available on the Web + | "net" // Node.js only + | "node" // Node.js only + | "resource"; // available on the Web + interface NodeGCPerformanceDetail { + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.kind` property identifies + * the type of garbage collection operation that occurred. + * See perf_hooks.constants for valid values. + */ + readonly kind?: number | undefined; + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` + * property contains additional information about garbage collection operation. + * See perf_hooks.constants for valid values. + */ + readonly flags?: number | undefined; + } + /** + * The constructor of this class is not exposed to users directly. + * @since v8.5.0 + */ + class PerformanceEntry { + protected constructor(); + /** + * The total number of milliseconds elapsed for this entry. This value will not + * be meaningful for all Performance Entry types. + * @since v8.5.0 + */ + readonly duration: number; + /** + * The name of the performance entry. + * @since v8.5.0 + */ + readonly name: string; + /** + * The high resolution millisecond timestamp marking the starting time of the + * Performance Entry. + * @since v8.5.0 + */ + readonly startTime: number; + /** + * The type of the performance entry. It may be one of: + * + * * `'node'` (Node.js only) + * * `'mark'` (available on the Web) + * * `'measure'` (available on the Web) + * * `'gc'` (Node.js only) + * * `'function'` (Node.js only) + * * `'http2'` (Node.js only) + * * `'http'` (Node.js only) + * @since v8.5.0 + */ + readonly entryType: EntryType; + /** + * Additional detail specific to the `entryType`. + * @since v16.0.0 + */ + readonly detail?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. + toJSON(): any; + } + /** + * Exposes marks created via the `Performance.mark()` method. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMark extends PerformanceEntry { + readonly duration: 0; + readonly entryType: "mark"; + } + /** + * Exposes measures created via the `Performance.measure()` method. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMeasure extends PerformanceEntry { + readonly entryType: "measure"; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Provides timing details for Node.js itself. The constructor of this class + * is not exposed to users. + * @since v8.5.0 + */ + class PerformanceNodeTiming extends PerformanceEntry { + readonly entryType: "node"; + /** + * The high resolution millisecond timestamp at which the Node.js process + * completed bootstrapping. If bootstrapping has not yet finished, the property + * has the value of -1. + * @since v8.5.0 + */ + readonly bootstrapComplete: number; + /** + * The high resolution millisecond timestamp at which the Node.js environment was + * initialized. + * @since v8.5.0 + */ + readonly environment: number; + /** + * The high resolution millisecond timestamp of the amount of time the event loop + * has been idle within the event loop's event provider (e.g. `epoll_wait`). This + * does not take CPU usage into consideration. If the event loop has not yet + * started (e.g., in the first tick of the main script), the property has the + * value of 0. + * @since v14.10.0, v12.19.0 + */ + readonly idleTime: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * exited. If the event loop has not yet exited, the property has the value of -1\. + * It can only have a value of not -1 in a handler of the `'exit'` event. + * @since v8.5.0 + */ + readonly loopExit: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * started. If the event loop has not yet started (e.g., in the first tick of the + * main script), the property has the value of -1. + * @since v8.5.0 + */ + readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + * @since v8.5.0 + */ + readonly nodeStart: number; + /** + * The high resolution millisecond timestamp at which the V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + /** + * @param utilization1 The result of a previous call to `eventLoopUtilization()`. + * @param utilization2 The result of a previous call to `eventLoopUtilization()` prior to `utilization1`. + */ + type EventLoopUtilityFunction = ( + utilization1?: EventLoopUtilization, + utilization2?: EventLoopUtilization, + ) => EventLoopUtilization; + interface MarkOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * An optional timestamp to be used as the mark time. + * @default `performance.now()` + */ + startTime?: number | undefined; + } + interface MeasureOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * Duration between start and end times. + */ + duration?: number | undefined; + /** + * Timestamp to be used as the end time, or a string identifying a previously recorded mark. + */ + end?: number | string | undefined; + /** + * Timestamp to be used as the start time, or a string identifying a previously recorded mark. + */ + start?: number | string | undefined; + } + interface TimerifyOptions { + /** + * A histogram object created using `perf_hooks.createHistogram()` that will record runtime + * durations in nanoseconds. + */ + histogram?: RecordableHistogram | undefined; + } + interface Performance { + /** + * If `name` is not provided, removes all `PerformanceMark` objects from the Performance Timeline. + * If `name` is provided, removes only the named mark. + * @since v8.5.0 + */ + clearMarks(name?: string): void; + /** + * If `name` is not provided, removes all `PerformanceMeasure` objects from the Performance Timeline. + * If `name` is provided, removes only the named measure. + * @since v16.7.0 + */ + clearMeasures(name?: string): void; + /** + * If `name` is not provided, removes all `PerformanceResourceTiming` objects from the Resource Timeline. + * If `name` is provided, removes only the named resource. + * @since v18.2.0, v16.17.0 + */ + clearResourceTimings(name?: string): void; + /** + * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. + * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). + * No other CPU idle time is taken into consideration. + */ + eventLoopUtilization: EventLoopUtilityFunction; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. + * If you are only interested in performance entries of certain types or that have certain names, see + * `performance.getEntriesByType()` and `performance.getEntriesByName()`. + * @since v16.7.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.name` is equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to `type`. + * @param name + * @param type + * @since v16.7.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.entryType` is equal to `type`. + * @param type + * @since v16.7.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + /** + * Creates a new `PerformanceMark` entry in the Performance Timeline. + * A `PerformanceMark` is a subclass of `PerformanceEntry` whose `performanceEntry.entryType` is always `'mark'`, + * and whose `performanceEntry.duration` is always `0`. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * + * The created `PerformanceMark` entry is put in the global Performance Timeline and can be queried with + * `performance.getEntries`, `performance.getEntriesByName`, and `performance.getEntriesByType`. When the observation is + * performed, the entries should be cleared from the global Performance Timeline manually with `performance.clearMarks`. + * @param name + */ + mark(name: string, options?: MarkOptions): PerformanceMark; + /** + * Creates a new `PerformanceResourceTiming` entry in the Resource Timeline. + * A `PerformanceResourceTiming` is a subclass of `PerformanceEntry` whose `performanceEntry.entryType` is always `'resource'`. + * Performance resources are used to mark moments in the Resource Timeline. + * @param timingInfo [Fetch Timing Info](https://fetch.spec.whatwg.org/#fetch-timing-info) + * @param requestedUrl The resource url + * @param initiatorType The initiator name, e.g: 'fetch' + * @param global + * @param cacheMode The cache mode must be an empty string ('') or 'local' + * @param bodyInfo [Fetch Response Body Info](https://fetch.spec.whatwg.org/#response-body-info) + * @param responseStatus The response's status code + * @param deliveryType The delivery type. Default: ''. + * @since v18.2.0, v16.17.0 + */ + markResourceTiming( + timingInfo: object, + requestedUrl: string, + initiatorType: string, + global: object, + cacheMode: "" | "local", + bodyInfo: object, + responseStatus: number, + deliveryType?: string, + ): PerformanceResourceTiming; + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + * @return The PerformanceMeasure entry that was created + */ + measure(name: string, startMark?: string, endMark?: string): PerformanceMeasure; + measure(name: string, options: MeasureOptions): PerformanceMeasure; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * An instance of the `PerformanceNodeTiming` class that provides performance metrics for specific Node.js operational milestones. + * @since v8.5.0 + */ + readonly nodeTiming: PerformanceNodeTiming; + /** + * Returns the current high resolution millisecond timestamp, where 0 represents the start of the current `node` process. + * @since v8.5.0 + */ + now(): number; + /** + * Sets the global performance resource timing buffer size to the specified number of "resource" type performance entry objects. + * + * By default the max buffer size is set to 250. + * @since v18.8.0 + */ + setResourceTimingBufferSize(maxSize: number): void; + /** + * The [`timeOrigin`](https://w3c.github.io/hr-time/#dom-performance-timeorigin) specifies the high resolution millisecond timestamp + * at which the current `node` process began, measured in Unix time. + * @since v8.5.0 + */ + readonly timeOrigin: number; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Wraps a function within a new function that measures the running time of the wrapped function. + * A `PerformanceObserver` must be subscribed to the `'function'` event type in order for the timing details to be accessed. + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * function someFunction() { + * console.log('hello world'); + * } + * + * const wrapped = performance.timerify(someFunction); + * + * const obs = new PerformanceObserver((list) => { + * console.log(list.getEntries()[0].duration); + * + * performance.clearMarks(); + * performance.clearMeasures(); + * obs.disconnect(); + * }); + * obs.observe({ entryTypes: ['function'] }); + * + * // A performance timeline entry will be created + * wrapped(); + * ``` + * + * If the wrapped function returns a promise, a finally handler will be attached to the promise and the duration will be reported + * once the finally handler is invoked. + * @param fn + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + /** + * An object which is JSON representation of the performance object. It is similar to + * [`window.performance.toJSON`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/toJSON) in browsers. + * @since v16.1.0 + */ + toJSON(): any; + } + class PerformanceObserverEntryList { + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime`. + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0, + * * detail: null + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is + * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ entryTypes: ['mark', 'measure'] }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType` is equal to `type`. + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0, + * * detail: null + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + } + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + /** + * @since v8.5.0 + */ + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + /** + * Disconnects the `PerformanceObserver` instance from all notifications. + * @since v8.5.0 + */ + disconnect(): void; + /** + * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes` or `options.type`: + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((list, observer) => { + * // Called once asynchronously. `list` contains three items. + * }); + * obs.observe({ type: 'mark' }); + * + * for (let n = 0; n < 3; n++) + * performance.mark(`test${n}`); + * ``` + * @since v8.5.0 + */ + observe( + options: + | { + entryTypes: readonly EntryType[]; + buffered?: boolean | undefined; + } + | { + type: EntryType; + buffered?: boolean | undefined; + }, + ): void; + } + /** + * Provides detailed network timing data regarding the loading of an application's resources. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceResourceTiming extends PerformanceEntry { + readonly entryType: "resource"; + protected constructor(); + /** + * The high resolution millisecond timestamp at immediately before dispatching the `fetch` + * request. If the resource is not intercepted by a worker the property will always return 0. + * @since v18.2.0, v16.17.0 + */ + readonly workerStart: number; + /** + * The high resolution millisecond timestamp that represents the start time of the fetch which + * initiates the redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectStart: number; + /** + * The high resolution millisecond timestamp that will be created immediately after receiving + * the last byte of the response of the last redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectEnd: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts to fetch the resource. + * @since v18.2.0, v16.17.0 + */ + readonly fetchStart: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts the domain name lookup + * for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after the Node.js finished + * the domain name lookup for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts to + * establish the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js finishes + * establishing the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts the + * handshake process to secure the current connection. + * @since v18.2.0, v16.17.0 + */ + readonly secureConnectionStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js receives the + * first byte of the response from the server. + * @since v18.2.0, v16.17.0 + */ + readonly requestStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js receives the + * last byte of the resource or immediately before the transport connection is closed, whichever comes first. + * @since v18.2.0, v16.17.0 + */ + readonly responseEnd: number; + /** + * A number representing the size (in octets) of the fetched resource. The size includes the response header + * fields plus the response payload body. + * @since v18.2.0, v16.17.0 + */ + readonly transferSize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the payload body, before + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly encodedBodySize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the message body, after + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly decodedBodySize: number; + /** + * Returns a `object` that is the JSON representation of the `PerformanceResourceTiming` object + * @since v18.2.0, v16.17.0 + */ + toJSON(): any; + } + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + const NODE_PERFORMANCE_GC_FLAGS_NO: number; + const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; + const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; + const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; + const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; + } + const performance: Performance; + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number | undefined; + } + interface Histogram { + /** + * The number of samples recorded by the histogram. + * @since v17.4.0, v16.14.0 + */ + readonly count: number; + /** + * The number of samples recorded by the histogram. + * v17.4.0, v16.14.0 + */ + readonly countBigInt: bigint; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event + * loop delay threshold. + * @since v11.10.0 + */ + readonly exceeds: number; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold. + * @since v17.4.0, v16.14.0 + */ + readonly exceedsBigInt: bigint; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The maximum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly maxBigInt: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The minimum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly minBigInt: bigint; + /** + * Returns the value at the given percentile. + * @since v11.10.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentile(percentile: number): number; + /** + * Returns the value at the given percentile. + * @since v17.4.0, v16.14.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentileBigInt(percentile: number): bigint; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v17.4.0, v16.14.0 + */ + readonly percentilesBigInt: Map; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + } + interface IntervalHistogram extends Histogram { + /** + * Enables the update interval timer. Returns `true` if the timer was + * started, `false` if it was already started. + * @since v11.10.0 + */ + enable(): boolean; + /** + * Disables the update interval timer. Returns `true` if the timer was + * stopped, `false` if it was already stopped. + * @since v11.10.0 + */ + disable(): boolean; + } + interface RecordableHistogram extends Histogram { + /** + * @since v15.9.0, v14.18.0 + * @param val The amount to record in the histogram. + */ + record(val: number | bigint): void; + /** + * Calculates the amount of time (in nanoseconds) that has passed since the + * previous call to `recordDelta()` and records that amount in the histogram. + * @since v15.9.0, v14.18.0 + */ + recordDelta(): void; + /** + * Adds the values from `other` to this histogram. + * @since v17.4.0, v16.14.0 + */ + add(other: RecordableHistogram): void; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Creates an `IntervalHistogram` object that samples and reports the event loop + * delay over time. The delays will be reported in nanoseconds. + * + * Using a timer to detect approximate event loop delay works because the + * execution of timers is tied specifically to the lifecycle of the libuv + * event loop. That is, a delay in the loop will cause a delay in the execution + * of the timer, and those delays are specifically what this API is intended to + * detect. + * + * ```js + * const { monitorEventLoopDelay } = require('node:perf_hooks'); + * const h = monitorEventLoopDelay({ resolution: 20 }); + * h.enable(); + * // Do something. + * h.disable(); + * console.log(h.min); + * console.log(h.max); + * console.log(h.mean); + * console.log(h.stddev); + * console.log(h.percentiles); + * console.log(h.percentile(50)); + * console.log(h.percentile(99)); + * ``` + * @since v11.10.0 + */ + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + interface CreateHistogramOptions { + /** + * The minimum recordable value. Must be an integer value greater than 0. + * @default 1 + */ + min?: number | bigint | undefined; + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + max?: number | bigint | undefined; + /** + * The number of accuracy digits. Must be a number between 1 and 5. + * @default 3 + */ + figures?: number | undefined; + } + /** + * Returns a `RecordableHistogram`. + * @since v15.9.0, v14.18.0 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; + import { + performance as _performance, + PerformanceEntry as _PerformanceEntry, + PerformanceMark as _PerformanceMark, + PerformanceMeasure as _PerformanceMeasure, + PerformanceObserver as _PerformanceObserver, + PerformanceObserverEntryList as _PerformanceObserverEntryList, + PerformanceResourceTiming as _PerformanceResourceTiming, + } from "perf_hooks"; + global { + /** + * `PerformanceEntry` is a global reference for `require('node:perf_hooks').PerformanceEntry` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performanceentry + * @since v19.0.0 + */ + var PerformanceEntry: typeof globalThis extends { + onmessage: any; + PerformanceEntry: infer T; + } ? T + : typeof _PerformanceEntry; + /** + * `PerformanceMark` is a global reference for `require('node:perf_hooks').PerformanceMark` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performancemark + * @since v19.0.0 + */ + var PerformanceMark: typeof globalThis extends { + onmessage: any; + PerformanceMark: infer T; + } ? T + : typeof _PerformanceMark; + /** + * `PerformanceMeasure` is a global reference for `require('node:perf_hooks').PerformanceMeasure` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performancemeasure + * @since v19.0.0 + */ + var PerformanceMeasure: typeof globalThis extends { + onmessage: any; + PerformanceMeasure: infer T; + } ? T + : typeof _PerformanceMeasure; + /** + * `PerformanceObserver` is a global reference for `require('node:perf_hooks').PerformanceObserver` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performanceobserver + * @since v19.0.0 + */ + var PerformanceObserver: typeof globalThis extends { + onmessage: any; + PerformanceObserver: infer T; + } ? T + : typeof _PerformanceObserver; + /** + * `PerformanceObserverEntryList` is a global reference for `require('node:perf_hooks').PerformanceObserverEntryList` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performanceobserverentrylist + * @since v19.0.0 + */ + var PerformanceObserverEntryList: typeof globalThis extends { + onmessage: any; + PerformanceObserverEntryList: infer T; + } ? T + : typeof _PerformanceObserverEntryList; + /** + * `PerformanceResourceTiming` is a global reference for `require('node:perf_hooks').PerformanceResourceTiming` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performanceresourcetiming + * @since v19.0.0 + */ + var PerformanceResourceTiming: typeof globalThis extends { + onmessage: any; + PerformanceResourceTiming: infer T; + } ? T + : typeof _PerformanceResourceTiming; + /** + * `performance` is a global reference for `require('node:perf_hooks').performance` + * @see https://nodejs.org/docs/latest-v22.x/api/globals.html#performance + * @since v16.0.0 + */ + var performance: typeof globalThis extends { + onmessage: any; + performance: infer T; + } ? T + : typeof _performance; + } +} +declare module "node:perf_hooks" { + export * from "perf_hooks"; +} diff --git a/node_modules/@types/node/process.d.ts b/node_modules/@types/node/process.d.ts new file mode 100644 index 0000000..e7fd20b --- /dev/null +++ b/node_modules/@types/node/process.d.ts @@ -0,0 +1,1912 @@ +declare module "process" { + import * as tty from "node:tty"; + import { Worker } from "node:worker_threads"; + + interface BuiltInModule { + "assert": typeof import("assert"); + "node:assert": typeof import("node:assert"); + "assert/strict": typeof import("assert/strict"); + "node:assert/strict": typeof import("node:assert/strict"); + "async_hooks": typeof import("async_hooks"); + "node:async_hooks": typeof import("node:async_hooks"); + "buffer": typeof import("buffer"); + "node:buffer": typeof import("node:buffer"); + "child_process": typeof import("child_process"); + "node:child_process": typeof import("node:child_process"); + "cluster": typeof import("cluster"); + "node:cluster": typeof import("node:cluster"); + "console": typeof import("console"); + "node:console": typeof import("node:console"); + "constants": typeof import("constants"); + "node:constants": typeof import("node:constants"); + "crypto": typeof import("crypto"); + "node:crypto": typeof import("node:crypto"); + "dgram": typeof import("dgram"); + "node:dgram": typeof import("node:dgram"); + "diagnostics_channel": typeof import("diagnostics_channel"); + "node:diagnostics_channel": typeof import("node:diagnostics_channel"); + "dns": typeof import("dns"); + "node:dns": typeof import("node:dns"); + "dns/promises": typeof import("dns/promises"); + "node:dns/promises": typeof import("node:dns/promises"); + "domain": typeof import("domain"); + "node:domain": typeof import("node:domain"); + "events": typeof import("events"); + "node:events": typeof import("node:events"); + "fs": typeof import("fs"); + "node:fs": typeof import("node:fs"); + "fs/promises": typeof import("fs/promises"); + "node:fs/promises": typeof import("node:fs/promises"); + "http": typeof import("http"); + "node:http": typeof import("node:http"); + "http2": typeof import("http2"); + "node:http2": typeof import("node:http2"); + "https": typeof import("https"); + "node:https": typeof import("node:https"); + "inspector": typeof import("inspector"); + "node:inspector": typeof import("node:inspector"); + "inspector/promises": typeof import("inspector/promises"); + "node:inspector/promises": typeof import("node:inspector/promises"); + "module": typeof import("module"); + "node:module": typeof import("node:module"); + "net": typeof import("net"); + "node:net": typeof import("node:net"); + "os": typeof import("os"); + "node:os": typeof import("node:os"); + "path": typeof import("path"); + "node:path": typeof import("node:path"); + "path/posix": typeof import("path/posix"); + "node:path/posix": typeof import("node:path/posix"); + "path/win32": typeof import("path/win32"); + "node:path/win32": typeof import("node:path/win32"); + "perf_hooks": typeof import("perf_hooks"); + "node:perf_hooks": typeof import("node:perf_hooks"); + "process": typeof import("process"); + "node:process": typeof import("node:process"); + "punycode": typeof import("punycode"); + "node:punycode": typeof import("node:punycode"); + "querystring": typeof import("querystring"); + "node:querystring": typeof import("node:querystring"); + "readline": typeof import("readline"); + "node:readline": typeof import("node:readline"); + "readline/promises": typeof import("readline/promises"); + "node:readline/promises": typeof import("node:readline/promises"); + "repl": typeof import("repl"); + "node:repl": typeof import("node:repl"); + "node:sea": typeof import("node:sea"); + "node:sqlite": typeof import("node:sqlite"); + "stream": typeof import("stream"); + "node:stream": typeof import("node:stream"); + "stream/consumers": typeof import("stream/consumers"); + "node:stream/consumers": typeof import("node:stream/consumers"); + "stream/promises": typeof import("stream/promises"); + "node:stream/promises": typeof import("node:stream/promises"); + "stream/web": typeof import("stream/web"); + "node:stream/web": typeof import("node:stream/web"); + "string_decoder": typeof import("string_decoder"); + "node:string_decoder": typeof import("node:string_decoder"); + "node:test": typeof import("node:test"); + "node:test/reporters": typeof import("node:test/reporters"); + "timers": typeof import("timers"); + "node:timers": typeof import("node:timers"); + "timers/promises": typeof import("timers/promises"); + "node:timers/promises": typeof import("node:timers/promises"); + "tls": typeof import("tls"); + "node:tls": typeof import("node:tls"); + "trace_events": typeof import("trace_events"); + "node:trace_events": typeof import("node:trace_events"); + "tty": typeof import("tty"); + "node:tty": typeof import("node:tty"); + "url": typeof import("url"); + "node:url": typeof import("node:url"); + "util": typeof import("util"); + "node:util": typeof import("node:util"); + "sys": typeof import("util"); + "node:sys": typeof import("node:util"); + "util/types": typeof import("util/types"); + "node:util/types": typeof import("node:util/types"); + "v8": typeof import("v8"); + "node:v8": typeof import("node:v8"); + "vm": typeof import("vm"); + "node:vm": typeof import("node:vm"); + "wasi": typeof import("wasi"); + "node:wasi": typeof import("node:wasi"); + "worker_threads": typeof import("worker_threads"); + "node:worker_threads": typeof import("node:worker_threads"); + "zlib": typeof import("zlib"); + "node:zlib": typeof import("node:zlib"); + } + global { + var process: NodeJS.Process; + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } + interface MemoryUsage { + /** + * Resident Set Size, is the amount of space occupied in the main memory device (that is a subset of the total allocated memory) for the + * process, including all C++ and JavaScript objects and code. + */ + rss: number; + /** + * Refers to V8's memory usage. + */ + heapTotal: number; + /** + * Refers to V8's memory usage. + */ + heapUsed: number; + external: number; + /** + * Refers to memory allocated for `ArrayBuffer`s and `SharedArrayBuffer`s, including all Node.js Buffers. This is also included + * in the external value. When Node.js is used as an embedded library, this value may be `0` because allocations for `ArrayBuffer`s + * may not be tracked in that case. + */ + arrayBuffers: number; + } + interface CpuUsage { + user: number; + system: number; + } + interface ProcessRelease { + name: string; + sourceUrl?: string | undefined; + headersUrl?: string | undefined; + libUrl?: string | undefined; + lts?: string | undefined; + } + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + type Platform = + | "aix" + | "android" + | "darwin" + | "freebsd" + | "haiku" + | "linux" + | "openbsd" + | "sunos" + | "win32" + | "cygwin" + | "netbsd"; + type Architecture = + | "arm" + | "arm64" + | "ia32" + | "loong64" + | "mips" + | "mipsel" + | "ppc" + | "ppc64" + | "riscv64" + | "s390" + | "s390x" + | "x64"; + type Signals = + | "SIGABRT" + | "SIGALRM" + | "SIGBUS" + | "SIGCHLD" + | "SIGCONT" + | "SIGFPE" + | "SIGHUP" + | "SIGILL" + | "SIGINT" + | "SIGIO" + | "SIGIOT" + | "SIGKILL" + | "SIGPIPE" + | "SIGPOLL" + | "SIGPROF" + | "SIGPWR" + | "SIGQUIT" + | "SIGSEGV" + | "SIGSTKFLT" + | "SIGSTOP" + | "SIGSYS" + | "SIGTERM" + | "SIGTRAP" + | "SIGTSTP" + | "SIGTTIN" + | "SIGTTOU" + | "SIGUNUSED" + | "SIGURG" + | "SIGUSR1" + | "SIGUSR2" + | "SIGVTALRM" + | "SIGWINCH" + | "SIGXCPU" + | "SIGXFSZ" + | "SIGBREAK" + | "SIGLOST" + | "SIGINFO"; + type UncaughtExceptionOrigin = "uncaughtException" | "unhandledRejection"; + type MultipleResolveType = "resolve" | "reject"; + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void; + /** + * Most of the time the unhandledRejection will be an Error, but this should not be relied upon + * as *anything* can be thrown/rejected, it is therefore unsafe to assume that the value is an Error. + */ + type UnhandledRejectionListener = (reason: unknown, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: unknown, sendHandle: unknown) => void; + type SignalsListener = (signal: Signals) => void; + type MultipleResolveListener = ( + type: MultipleResolveType, + promise: Promise, + value: unknown, + ) => void; + type WorkerListener = (worker: Worker) => void; + interface Socket extends ReadWriteStream { + isTTY?: true | undefined; + } + // Alias for compatibility + interface ProcessEnv extends Dict { + /** + * Can be used to change the default timezone at runtime + */ + TZ?: string; + } + interface HRTime { + (time?: [number, number]): [number, number]; + /** + * The `bigint` version of the `{@link hrtime()}` method returning the current high-resolution real time in nanoseconds as a `bigint`. + * + * Unlike `{@link hrtime()}`, it does not support an additional time argument since the difference can just be computed directly by subtraction of the two `bigint`s. + * ```js + * import { hrtime } from 'node:process'; + * + * const start = hrtime.bigint(); + * // 191051479007711n + * + * setTimeout(() => { + * const end = hrtime.bigint(); + * // 191052633396993n + * + * console.log(`Benchmark took ${end - start} nanoseconds`); + * // Benchmark took 1154389282 nanoseconds + * }, 1000); + * ``` + */ + bigint(): bigint; + } + interface ProcessPermission { + /** + * Verifies that the process is able to access the given scope and reference. + * If no reference is provided, a global scope is assumed, for instance, `process.permission.has('fs.read')` + * will check if the process has ALL file system read permissions. + * + * The reference has a meaning based on the provided scope. For example, the reference when the scope is File System means files and folders. + * + * The available scopes are: + * + * * `fs` - All File System + * * `fs.read` - File System read operations + * * `fs.write` - File System write operations + * * `child` - Child process spawning operations + * * `worker` - Worker thread spawning operation + * + * ```js + * // Check if the process has permission to read the README file + * process.permission.has('fs.read', './README.md'); + * // Check if the process has read permission operations + * process.permission.has('fs.read'); + * ``` + * @since v20.0.0 + */ + has(scope: string, reference?: string): boolean; + } + interface ProcessReport { + /** + * Write reports in a compact format, single-line JSON, more easily consumable by log processing systems + * than the default multi-line format designed for human consumption. + * @since v13.12.0, v12.17.0 + */ + compact: boolean; + /** + * Directory where the report is written. + * The default value is the empty string, indicating that reports are written to the current + * working directory of the Node.js process. + */ + directory: string; + /** + * Filename where the report is written. If set to the empty string, the output filename will be comprised + * of a timestamp, PID, and sequence number. The default value is the empty string. + */ + filename: string; + /** + * Returns a JavaScript Object representation of a diagnostic report for the running process. + * The report's JavaScript stack trace is taken from `err`, if present. + */ + getReport(err?: Error): object; + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @default false + */ + reportOnSignal: boolean; + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from `err`, if present. + * + * If the value of filename is set to `'stdout'` or `'stderr'`, the report is written + * to the stdout or stderr of the process respectively. + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param err A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string, err?: Error): string; + writeReport(err?: Error): string; + } + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string | undefined; + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string | undefined; + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function | undefined; + /** + * Additional text to include with the error. + */ + detail?: string | undefined; + } + interface ProcessConfig { + readonly target_defaults: { + readonly cflags: any[]; + readonly default_configuration: string; + readonly defines: string[]; + readonly include_dirs: string[]; + readonly libraries: string[]; + }; + readonly variables: { + readonly clang: number; + readonly host_arch: string; + readonly node_install_npm: boolean; + readonly node_install_waf: boolean; + readonly node_prefix: string; + readonly node_shared_openssl: boolean; + readonly node_shared_v8: boolean; + readonly node_shared_zlib: boolean; + readonly node_use_dtrace: boolean; + readonly node_use_etw: boolean; + readonly node_use_openssl: boolean; + readonly target_arch: string; + readonly v8_no_strict_aliasing: number; + readonly v8_use_snapshot: boolean; + readonly visibility: string; + }; + } + interface Process extends EventEmitter { + /** + * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is + * a `Writable` stream. + * + * For example, to copy `process.stdin` to `process.stdout`: + * + * ```js + * import { stdin, stdout } from 'node:process'; + * + * stdin.pipe(stdout); + * ``` + * + * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is + * a `Writable` stream. + * + * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stderr: WriteStream & { + fd: 2; + }; + /** + * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is + * a `Readable` stream. + * + * For details of how to read from `stdin` see `readable.read()`. + * + * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that + * is compatible with scripts written for Node.js prior to v0.10\. + * For more information see `Stream compatibility`. + * + * In "old" streams mode the `stdin` stream is paused by default, so one + * must call `process.stdin.resume()` to read from it. Note also that calling `process.stdin.resume()` itself would switch stream to "old" mode. + */ + stdin: ReadStream & { + fd: 0; + }; + /** + * The `process.argv` property returns an array containing the command-line + * arguments passed when the Node.js process was launched. The first element will + * be {@link execPath}. See `process.argv0` if access to the original value + * of `argv[0]` is needed. The second element will be the path to the JavaScript + * file being executed. The remaining elements will be any additional command-line + * arguments. + * + * For example, assuming the following script for `process-args.js`: + * + * ```js + * import { argv } from 'node:process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```bash + * node process-args.js one two=three four + * ``` + * + * Would generate the output: + * + * ```text + * 0: /usr/local/bin/node + * 1: /Users/mjr/work/node/process-args.js + * 2: one + * 3: two=three + * 4: four + * ``` + * @since v0.1.27 + */ + argv: string[]; + /** + * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. + * + * ```console + * $ bash -c 'exec -a customArgv0 ./node' + * > process.argv[0] + * '/Volumes/code/external/node/out/Release/node' + * > process.argv0 + * 'customArgv0' + * ``` + * @since v6.4.0 + */ + argv0: string; + /** + * The `process.execArgv` property returns the set of Node.js-specific command-line + * options passed when the Node.js process was launched. These options do not + * appear in the array returned by the {@link argv} property, and do not + * include the Node.js executable, the name of the script, or any options following + * the script name. These options are useful in order to spawn child processes with + * the same execution environment as the parent. + * + * ```bash + * node --icu-data-dir=./foo --require ./bar.js script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ["--icu-data-dir=./foo", "--require", "./bar.js"] + * ``` + * + * And `process.argv`: + * + * ```js + * ['/usr/local/bin/node', 'script.js', '--version'] + * ``` + * + * Refer to `Worker constructor` for the detailed behavior of worker + * threads with this property. + * @since v0.7.7 + */ + execArgv: string[]; + /** + * The `process.execPath` property returns the absolute pathname of the executable + * that started the Node.js process. Symbolic links, if any, are resolved. + * + * ```js + * '/usr/local/bin/node' + * ``` + * @since v0.1.100 + */ + execPath: string; + /** + * The `process.abort()` method causes the Node.js process to exit immediately and + * generate a core file. + * + * This feature is not available in `Worker` threads. + * @since v0.7.0 + */ + abort(): never; + /** + * The `process.chdir()` method changes the current working directory of the + * Node.js process or throws an exception if doing so fails (for instance, if + * the specified `directory` does not exist). + * + * ```js + * import { chdir, cwd } from 'node:process'; + * + * console.log(`Starting directory: ${cwd()}`); + * try { + * chdir('/tmp'); + * console.log(`New directory: ${cwd()}`); + * } catch (err) { + * console.error(`chdir: ${err}`); + * } + * ``` + * + * This feature is not available in `Worker` threads. + * @since v0.1.17 + */ + chdir(directory: string): void; + /** + * The `process.cwd()` method returns the current working directory of the Node.js + * process. + * + * ```js + * import { cwd } from 'node:process'; + * + * console.log(`Current directory: ${cwd()}`); + * ``` + * @since v0.1.8 + */ + cwd(): string; + /** + * The port used by the Node.js debugger when enabled. + * + * ```js + * import process from 'node:process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * The `process.dlopen()` method allows dynamically loading shared objects. It is primarily used by `require()` to load C++ Addons, and + * should not be used directly, except in special cases. In other words, `require()` should be preferred over `process.dlopen()` + * unless there are specific reasons such as custom dlopen flags or loading from ES modules. + * + * The `flags` argument is an integer that allows to specify dlopen behavior. See the `[os.constants.dlopen](https://nodejs.org/docs/latest-v22.x/api/os.html#dlopen-constants)` + * documentation for details. + * + * An important requirement when calling `process.dlopen()` is that the `module` instance must be passed. Functions exported by the C++ Addon + * are then accessible via `module.exports`. + * + * The example below shows how to load a C++ Addon, named `local.node`, that exports a `foo` function. All the symbols are loaded before the call returns, by passing the `RTLD_NOW` constant. + * In this example the constant is assumed to be available. + * + * ```js + * import { dlopen } from 'node:process'; + * import { constants } from 'node:os'; + * import { fileURLToPath } from 'node:url'; + * + * const module = { exports: {} }; + * dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)), + * constants.dlopen.RTLD_NOW); + * module.exports.foo(); + * ``` + */ + dlopen(module: object, filename: string, flags?: number): void; + /** + * The `process.emitWarning()` method can be used to emit custom or application + * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string. + * emitWarning('Something happened!'); + * // Emits: (node: 56338) Warning: Something happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string and a type. + * emitWarning('Something Happened!', 'CustomWarning'); + * // Emits: (node:56338) CustomWarning: Something Happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * emitWarning('Something happened!', 'CustomWarning', 'WARN001'); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ```js + * + * In each of the previous examples, an `Error` object is generated internally by `process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'node:process'; + * + * process.on('warning', (warning) => { + * console.warn(warning.name); // 'Warning' + * console.warn(warning.message); // 'Something happened!' + * console.warn(warning.code); // 'MY_WARNING' + * console.warn(warning.stack); // Stack trace + * console.warn(warning.detail); // 'This is some additional information' + * }); + * ``` + * + * If `warning` is passed as an `Error` object, it will be passed through to the `'warning'` event handler + * unmodified (and the optional `type`, `code` and `ctor` arguments will be ignored): + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using an Error object. + * const myWarning = new Error('Something happened!'); + * // Use the Error name property to specify the type name + * myWarning.name = 'CustomWarning'; + * myWarning.code = 'WARN001'; + * + * emitWarning(myWarning); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ``` + * + * A `TypeError` is thrown if `warning` is anything other than a string or `Error` object. + * + * While process warnings use `Error` objects, the process warning mechanism is not a replacement for normal error handling mechanisms. + * + * The following additional handling is implemented if the warning `type` is `'DeprecationWarning'`: + * * If the `--throw-deprecation` command-line flag is used, the deprecation warning is thrown as an exception rather than being emitted as an event. + * * If the `--no-deprecation` command-line flag is used, the deprecation warning is suppressed. + * * If the `--trace-deprecation` command-line flag is used, the deprecation warning is printed to `stderr` along with the full stack trace. + * @since v8.0.0 + * @param warning The warning to emit. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + /** + * The `process.env` property returns an object containing the user environment. + * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). + * + * An example of this object looks like: + * + * ```js + * { + * TERM: 'xterm-256color', + * SHELL: '/usr/local/bin/bash', + * USER: 'maciej', + * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', + * PWD: '/Users/maciej', + * EDITOR: 'vim', + * SHLVL: '1', + * HOME: '/Users/maciej', + * LOGNAME: 'maciej', + * _: '/usr/local/bin/node' + * } + * ``` + * + * It is possible to modify this object, but such modifications will not be + * reflected outside the Node.js process, or (unless explicitly requested) + * to other `Worker` threads. + * In other words, the following example would not work: + * + * ```bash + * node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'node:process'; + * + * env.foo = 'bar'; + * console.log(env.foo); + * ``` + * + * Assigning a property on `process.env` will implicitly convert the value + * to a string. **This behavior is deprecated.** Future versions of Node.js may + * throw an error when the value is not a string, number, or boolean. + * + * ```js + * import { env } from 'node:process'; + * + * env.test = null; + * console.log(env.test); + * // => 'null' + * env.test = undefined; + * console.log(env.test); + * // => 'undefined' + * ``` + * + * Use `delete` to delete a property from `process.env`. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * delete env.TEST; + * console.log(env.TEST); + * // => undefined + * ``` + * + * On Windows operating systems, environment variables are case-insensitive. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * console.log(env.test); + * // => 1 + * ``` + * + * Unless explicitly specified when creating a `Worker` instance, + * each `Worker` thread has its own copy of `process.env`, based on its + * parent thread's `process.env`, or whatever was specified as the `env` option + * to the `Worker` constructor. Changes to `process.env` will not be visible + * across `Worker` threads, and only the main thread can make changes that + * are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner + * unlike the main thread. + * @since v0.1.27 + */ + env: ProcessEnv; + /** + * The `process.exit()` method instructs Node.js to terminate the process + * synchronously with an exit status of `code`. If `code` is omitted, exit uses + * either the 'success' code `0` or the value of `process.exitCode` if it has been + * set. Node.js will not terminate until all the `'exit'` event listeners are + * called. + * + * To exit with a 'failure' code: + * + * ```js + * import { exit } from 'node:process'; + * + * exit(1); + * ``` + * + * The shell that executed Node.js should see the exit code as `1`. + * + * Calling `process.exit()` will force the process to exit as quickly as possible + * even if there are still asynchronous operations pending that have not yet + * completed fully, including I/O operations to `process.stdout` and `process.stderr`. + * + * In most situations, it is not actually necessary to call `process.exit()` explicitly. The Node.js process will exit on its own _if there is no additional_ + * _work pending_ in the event loop. The `process.exitCode` property can be set to + * tell the process which exit code to use when the process exits gracefully. + * + * For instance, the following example illustrates a _misuse_ of the `process.exit()` method that could lead to data printed to stdout being + * truncated and lost: + * + * ```js + * import { exit } from 'node:process'; + * + * // This is an example of what *not* to do: + * if (someConditionNotMet()) { + * printUsageToStdout(); + * exit(1); + * } + * ``` + * + * The reason this is problematic is because writes to `process.stdout` in Node.js + * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js + * event loop. Calling `process.exit()`, however, forces the process to exit _before_ those additional writes to `stdout` can be performed. + * + * Rather than calling `process.exit()` directly, the code _should_ set the `process.exitCode` and allow the process to exit naturally by avoiding + * scheduling any additional work for the event loop: + * + * ```js + * import process from 'node:process'; + * + * // How to properly set the exit code while letting + * // the process exit gracefully. + * if (someConditionNotMet()) { + * printUsageToStdout(); + * process.exitCode = 1; + * } + * ``` + * + * If it is necessary to terminate the Node.js process due to an error condition, + * throwing an _uncaught_ error and allowing the process to terminate accordingly + * is safer than calling `process.exit()`. + * + * In `Worker` threads, this function stops the current thread rather + * than the current process. + * @since v0.1.13 + * @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed. + */ + exit(code?: number | string | null | undefined): never; + /** + * A number which will be the process exit code, when the process either + * exits gracefully, or is exited via {@link exit} without specifying + * a code. + * + * Specifying a code to {@link exit} will override any + * previous setting of `process.exitCode`. + * @default undefined + * @since v0.11.8 + */ + exitCode?: number | string | number | undefined; + finalization: { + /** + * This function registers a callback to be called when the process emits the `exit` event if the `ref` object was not garbage collected. + * If the object `ref` was garbage collected before the `exit` event is emitted, the callback will be removed from the finalization registry, and it will not be called on process exit. + * + * Inside the callback you can release the resources allocated by the `ref` object. + * Be aware that all limitations applied to the `beforeExit` event are also applied to the callback function, + * this means that there is a possibility that the callback will not be called under special circumstances. + * + * The idea of ​​this function is to help you free up resources when the starts process exiting, but also let the object be garbage collected if it is no longer being used. + * @param ref The reference to the resource that is being tracked. + * @param callback The callback function to be called when the resource is finalized. + * @since v22.5.0 + * @experimental + */ + register(ref: T, callback: (ref: T, event: "exit") => void): void; + /** + * This function behaves exactly like the `register`, except that the callback will be called when the process emits the `beforeExit` event if `ref` object was not garbage collected. + * + * Be aware that all limitations applied to the `beforeExit` event are also applied to the callback function, this means that there is a possibility that the callback will not be called under special circumstances. + * @param ref The reference to the resource that is being tracked. + * @param callback The callback function to be called when the resource is finalized. + * @since v22.5.0 + * @experimental + */ + registerBeforeExit(ref: T, callback: (ref: T, event: "beforeExit") => void): void; + /** + * This function remove the register of the object from the finalization registry, so the callback will not be called anymore. + * @param ref The reference to the resource that was registered previously. + * @since v22.5.0 + * @experimental + */ + unregister(ref: object): void; + }; + /** + * The `process.getActiveResourcesInfo()` method returns an array of strings containing + * the types of the active resources that are currently keeping the event loop alive. + * + * ```js + * import { getActiveResourcesInfo } from 'node:process'; + * import { setTimeout } from 'node:timers'; + + * console.log('Before:', getActiveResourcesInfo()); + * setTimeout(() => {}, 1000); + * console.log('After:', getActiveResourcesInfo()); + * // Prints: + * // Before: [ 'TTYWrap', 'TTYWrap', 'TTYWrap' ] + * // After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ] + * ``` + * @since v17.3.0, v16.14.0 + */ + getActiveResourcesInfo(): string[]; + /** + * Provides a way to load built-in modules in a globally available function. + * @param id ID of the built-in module being requested. + */ + getBuiltinModule(id: ID): BuiltInModule[ID]; + getBuiltinModule(id: string): object | undefined; + /** + * The `process.getgid()` method returns the numerical group identity of the + * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid) { + * console.log(`Current gid: ${process.getgid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.31 + */ + getgid?: () => number; + /** + * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a + * numeric ID or a group name + * string. If a group name is specified, this method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid && process.setgid) { + * console.log(`Current gid: ${process.getgid()}`); + * try { + * process.setgid(501); + * console.log(`New gid: ${process.getgid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.31 + * @param id The group name or ID + */ + setgid?: (id: number | string) => void; + /** + * The `process.getuid()` method returns the numeric user identity of the process. + * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid) { + * console.log(`Current uid: ${process.getuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.28 + */ + getuid?: () => number; + /** + * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a + * numeric ID or a username string. + * If a username is specified, the method blocks while resolving the associated + * numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid && process.setuid) { + * console.log(`Current uid: ${process.getuid()}`); + * try { + * process.setuid(501); + * console.log(`New uid: ${process.getuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.28 + */ + setuid?: (id: number | string) => void; + /** + * The `process.geteuid()` method returns the numerical effective user identity of + * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + geteuid?: () => number; + /** + * The `process.seteuid()` method sets the effective user identity of the process. + * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username + * string. If a username is specified, the method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid && process.seteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * try { + * process.seteuid(501); + * console.log(`New uid: ${process.geteuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A user name or ID + */ + seteuid?: (id: number | string) => void; + /** + * The `process.getegid()` method returns the numerical effective group identity + * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid) { + * console.log(`Current gid: ${process.getegid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + getegid?: () => number; + /** + * The `process.setegid()` method sets the effective group identity of the process. + * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group + * name string. If a group name is specified, this method blocks while resolving + * the associated a numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid && process.setegid) { + * console.log(`Current gid: ${process.getegid()}`); + * try { + * process.setegid(501); + * console.log(`New gid: ${process.getegid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A group name or ID + */ + setegid?: (id: number | string) => void; + /** + * The `process.getgroups()` method returns an array with the supplementary group + * IDs. POSIX leaves it unspecified if the effective group ID is included but + * Node.js ensures it always is. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups) { + * console.log(process.getgroups()); // [ 16, 21, 297 ] + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.9.4 + */ + getgroups?: () => number[]; + /** + * The `process.setgroups()` method sets the supplementary group IDs for the + * Node.js process. This is a privileged operation that requires the Node.js + * process to have `root` or the `CAP_SETGID` capability. + * + * The `groups` array can contain numeric group IDs, group names, or both. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups && process.setgroups) { + * try { + * process.setgroups([501]); + * console.log(process.getgroups()); // new groups + * } catch (err) { + * console.log(`Failed to set groups: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.9.4 + */ + setgroups?: (groups: ReadonlyArray) => void; + /** + * The `process.setUncaughtExceptionCaptureCallback()` function sets a function + * that will be invoked when an uncaught exception occurs, which will receive the + * exception value itself as its first argument. + * + * If such a function is set, the `'uncaughtException'` event will + * not be emitted. If `--abort-on-uncaught-exception` was passed from the + * command line or set through `v8.setFlagsFromString()`, the process will + * not abort. Actions configured to take place on exceptions such as report + * generations will be affected too + * + * To unset the capture function, `process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * method with a non-`null` argument while another capture function is set will + * throw an error. + * + * Using this function is mutually exclusive with using the deprecated `domain` built-in module. + * @since v9.3.0 + */ + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + /** + * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. + * @since v9.3.0 + */ + hasUncaughtExceptionCaptureCallback(): boolean; + /** + * The `process.sourceMapsEnabled` property returns whether the [Source Map v3](https://sourcemaps.info/spec.html) support for stack traces is enabled. + * @since v20.7.0 + * @experimental + */ + readonly sourceMapsEnabled: boolean; + /** + * This function enables or disables the [Source Map v3](https://sourcemaps.info/spec.html) support for + * stack traces. + * + * It provides same features as launching Node.js process with commandline options `--enable-source-maps`. + * + * Only source maps in JavaScript files that are loaded after source maps has been + * enabled will be parsed and loaded. + * @since v16.6.0, v14.18.0 + * @experimental + */ + setSourceMapsEnabled(value: boolean): void; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'node:process'; + * + * console.log(`Version: ${version}`); + * // Version: v14.8.0 + * ``` + * + * To get the version string without the prepended _v_, use`process.versions.node`. + * @since v0.1.3 + */ + readonly version: string; + /** + * The `process.versions` property returns an object listing the version strings of + * Node.js and its dependencies. `process.versions.modules` indicates the current + * ABI version, which is increased whenever a C++ API changes. Node.js will refuse + * to load modules that were compiled against a different module ABI version. + * + * ```js + * import { versions } from 'node:process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '20.2.0', + * acorn: '8.8.2', + * ada: '2.4.0', + * ares: '1.19.0', + * base64: '0.5.0', + * brotli: '1.0.9', + * cjs_module_lexer: '1.2.2', + * cldr: '43.0', + * icu: '73.1', + * llhttp: '8.1.0', + * modules: '115', + * napi: '8', + * nghttp2: '1.52.0', + * nghttp3: '0.7.0', + * ngtcp2: '0.8.1', + * openssl: '3.0.8+quic', + * simdutf: '3.2.9', + * tz: '2023c', + * undici: '5.22.0', + * unicode: '15.0', + * uv: '1.44.2', + * uvwasi: '0.0.16', + * v8: '11.3.244.8-node.9', + * zlib: '1.2.13' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns a frozen `Object` containing the + * JavaScript representation of the configure options used to compile the current + * Node.js executable. This is the same as the `config.gypi` file that was produced + * when running the `./configure` script. + * + * An example of the possible output looks like: + * + * ```js + * { + * target_defaults: + * { cflags: [], + * default_configuration: 'Release', + * defines: [], + * include_dirs: [], + * libraries: [] }, + * variables: + * { + * host_arch: 'x64', + * napi_build_version: 5, + * node_install_npm: 'true', + * node_prefix: '', + * node_shared_cares: 'false', + * node_shared_http_parser: 'false', + * node_shared_libuv: 'false', + * node_shared_zlib: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * @since v0.7.7 + */ + readonly config: ProcessConfig; + /** + * The `process.kill()` method sends the `signal` to the process identified by`pid`. + * + * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. + * + * This method will throw an error if the target `pid` does not exist. As a special + * case, a signal of `0` can be used to test for the existence of a process. + * Windows platforms will throw an error if the `pid` is used to kill a process + * group. + * + * Even though the name of this function is `process.kill()`, it is really just a + * signal sender, like the `kill` system call. The signal sent may do something + * other than kill the target process. + * + * ```js + * import process, { kill } from 'node:process'; + * + * process.on('SIGHUP', () => { + * console.log('Got SIGHUP signal.'); + * }); + * + * setTimeout(() => { + * console.log('Exiting.'); + * process.exit(0); + * }, 100); + * + * kill(process.pid, 'SIGHUP'); + * ``` + * + * When `SIGUSR1` is received by a Node.js process, Node.js will start the + * debugger. See `Signal Events`. + * @since v0.0.6 + * @param pid A process ID + * @param [signal='SIGTERM'] The signal to send, either as a string or number. + */ + kill(pid: number, signal?: string | number): true; + /** + * Loads the environment configuration from a `.env` file into `process.env`. If + * the file is not found, error will be thrown. + * + * To load a specific .env file by specifying its path, use the following code: + * + * ```js + * import { loadEnvFile } from 'node:process'; + * + * loadEnvFile('./development.env') + * ``` + * @since v20.12.0 + * @param path The path to the .env file + */ + loadEnvFile(path?: string | URL | Buffer): void; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'node:process'; + * + * console.log(`This process is pid ${pid}`); + * ``` + * @since v0.1.15 + */ + readonly pid: number; + /** + * The `process.ppid` property returns the PID of the parent of the + * current process. + * + * ```js + * import { ppid } from 'node:process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * The `process.title` property returns the current process title (i.e. returns + * the current value of `ps`). Assigning a new value to `process.title` modifies + * the current value of `ps`. + * + * When a new value is assigned, different platforms will impose different maximum + * length restrictions on the title. Usually such restrictions are quite limited. + * For instance, on Linux and macOS, `process.title` is limited to the size of the + * binary name plus the length of the command-line arguments because setting the `process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ` memory but that was potentially insecure and confusing in some (rather obscure) + * cases. + * + * Assigning a value to `process.title` might not result in an accurate label + * within process manager applications such as macOS Activity Monitor or Windows + * Services Manager. + * @since v0.1.104 + */ + title: string; + /** + * The operating system CPU architecture for which the Node.js binary was compiled. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, and `'x64'`. + * + * ```js + * import { arch } from 'node:process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: Architecture; + /** + * The `process.platform` property returns a string identifying the operating + * system platform for which the Node.js binary was compiled. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from 'node:process'; + * + * console.log(`This platform is ${platform}`); + * ``` + * + * The value `'android'` may also be returned if the Node.js is built on the + * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.1.16 + */ + readonly platform: Platform; + /** + * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at + * runtime, `require.main` may still refer to the original main module in + * modules that were required before the change occurred. Generally, it's + * safe to assume that the two refer to the same module. + * + * As with `require.main`, `process.mainModule` will be `undefined` if there + * is no entry script. + * @since v0.1.17 + * @deprecated Since v14.0.0 - Use `main` instead. + */ + mainModule?: Module | undefined; + memoryUsage: MemoryUsageFn; + /** + * Gets the amount of memory available to the process (in bytes) based on + * limits imposed by the OS. If there is no such constraint, or the constraint + * is unknown, `0` is returned. + * + * See [`uv_get_constrained_memory`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory) for more + * information. + * @since v19.6.0, v18.15.0 + * @experimental + */ + constrainedMemory(): number; + /** + * Gets the amount of free memory that is still available to the process (in bytes). + * See [`uv_get_available_memory`](https://nodejs.org/docs/latest-v22.x/api/process.html#processavailablememory) for more information. + * @experimental + * @since v20.13.0 + */ + availableMemory(): number; + /** + * The `process.cpuUsage()` method returns the user and system CPU time usage of + * the current process, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). These values measure time + * spent in user and system code respectively, and may end up being greater than + * actual elapsed time if multiple CPU cores are performing work for this process. + * + * The result of a previous call to `process.cpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * + * ```js + * import { cpuUsage } from 'node:process'; + * + * const startUsage = cpuUsage(); + * // { user: 38579, system: 6986 } + * + * // spin the CPU for 500 milliseconds + * const now = Date.now(); + * while (Date.now() - now < 500); + * + * console.log(cpuUsage(startUsage)); + * // { user: 514883, system: 11226 } + * ``` + * @since v6.1.0 + * @param previousValue A previous return value from calling `process.cpuUsage()` + */ + cpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * `process.nextTick()` adds `callback` to the "next tick queue". This queue is + * fully drained after the current operation on the JavaScript stack runs to + * completion and before the event loop is allowed to continue. It's possible to + * create an infinite loop if one were to recursively call `process.nextTick()`. + * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. + * + * ```js + * import { nextTick } from 'node:process'; + * + * console.log('start'); + * nextTick(() => { + * console.log('nextTick callback'); + * }); + * console.log('scheduled'); + * // Output: + * // start + * // scheduled + * // nextTick callback + * ``` + * + * This is important when developing APIs in order to give users the opportunity + * to assign event handlers _after_ an object has been constructed but before any + * I/O has occurred: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function MyThing(options) { + * this.setupOptions(options); + * + * nextTick(() => { + * this.startDoingStuff(); + * }); + * } + * + * const thing = new MyThing(); + * thing.getReadyForStuff(); + * + * // thing.startDoingStuff() gets called now, not before. + * ``` + * + * It is very important for APIs to be either 100% synchronous or 100% + * asynchronous. Consider this example: + * + * ```js + * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! + * function maybeSync(arg, cb) { + * if (arg) { + * cb(); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * + * This API is hazardous because in the following case: + * + * ```js + * const maybeTrue = Math.random() > 0.5; + * + * maybeSync(maybeTrue, () => { + * foo(); + * }); + * + * bar(); + * ``` + * + * It is not clear whether `foo()` or `bar()` will be called first. + * + * The following approach is much better: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function definitelyAsync(arg, cb) { + * if (arg) { + * nextTick(cb); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * @since v0.1.26 + * @param args Additional arguments to pass when invoking the `callback` + */ + nextTick(callback: Function, ...args: any[]): void; + /** + * This API is available through the [--experimental-permission](https://nodejs.org/api/cli.html#--experimental-permission) flag. + * + * `process.permission` is an object whose methods are used to manage permissions for the current process. + * Additional documentation is available in the [Permission Model](https://nodejs.org/api/permissions.html#permission-model). + * @since v20.0.0 + */ + permission: ProcessPermission; + /** + * The `process.release` property returns an `Object` containing metadata related + * to the current release, including URLs for the source tarball and headers-only + * tarball. + * + * `process.release` contains the following properties: + * + * ```js + * { + * name: 'node', + * lts: 'Hydrogen', + * sourceUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib' + * } + * ``` + * + * In custom builds from non-release versions of the source tree, only the `name` property may be present. The additional properties should not be + * relied upon to exist. + * @since v3.0.0 + */ + readonly release: ProcessRelease; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; + /** + * `process.umask()` returns the Node.js process's file mode creation mask. Child + * processes inherit the mask from the parent process. + * @since v0.1.19 + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential + * security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: string | number): number; + /** + * The `process.uptime()` method returns the number of seconds the current Node.js + * process has been running. + * + * The return value includes fractions of a second. Use `Math.floor()` to get whole + * seconds. + * @since v0.5.0 + */ + uptime(): number; + hrtime: HRTime; + /** + * If the Node.js process was spawned with an IPC channel, the process.channel property is a reference to the IPC channel. + * If no IPC channel exists, this property is undefined. + * @since v7.1.0 + */ + channel?: { + /** + * This method makes the IPC channel keep the event loop of the process running if .unref() has been called before. + * @since v7.1.0 + */ + ref(): void; + /** + * This method makes the IPC channel not keep the event loop of the process running, and lets it finish even while the channel is open. + * @since v7.1.0 + */ + unref(): void; + }; + /** + * If Node.js is spawned with an IPC channel, the `process.send()` method can be + * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. + * + * If Node.js was not spawned with an IPC channel, `process.send` will be `undefined`. + * + * The message goes through serialization and parsing. The resulting message might + * not be the same as what is originally sent. + * @since v0.5.9 + * @param options used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send?( + message: any, + sendHandle?: any, + options?: { + keepOpen?: boolean | undefined; + }, + callback?: (error: Error | null) => void, + ): boolean; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the + * IPC channel to the parent process, allowing the child process to exit gracefully + * once there are no other connections keeping it alive. + * + * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. + * + * If the Node.js process was not spawned with an IPC channel, `process.disconnect()` will be `undefined`. + * @since v0.7.2 + */ + disconnect(): void; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return `true` so long as the IPC + * channel is connected and will return `false` after `process.disconnect()` is called. + * + * Once `process.connected` is `false`, it is no longer possible to send messages + * over the IPC channel using `process.send()`. + * @since v0.7.2 + */ + connected: boolean; + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. + * + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides `Set.prototype.has` to recognize several different possible flag + * representations. `process.allowedNodeEnvironmentFlags.has()` will + * return `true` in the following cases: + * + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g., `inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags passed through to V8 (as listed in `--v8-options`) may replace + * one or more _non-leading_ dashes for an underscore, or vice-versa; + * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, + * etc. + * * Flags may contain one or more equals (`=`) characters; all + * characters after and including the first equals will be ignored; + * e.g., `--stack-trace-limit=100`. + * * Flags _must_ be allowable within `NODE_OPTIONS`. + * + * When iterating over `process.allowedNodeEnvironmentFlags`, flags will + * appear only _once_; each will begin with one or more dashes. Flags + * passed through to V8 will contain underscores instead of non-leading + * dashes: + * + * ```js + * import { allowedNodeEnvironmentFlags } from 'node:process'; + * + * allowedNodeEnvironmentFlags.forEach((flag) => { + * // -r + * // --inspect-brk + * // --abort_on_uncaught_exception + * // ... + * }); + * ``` + * + * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail + * silently. + * + * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will + * contain what _would have_ been allowable. + * @since v10.10.0 + */ + allowedNodeEnvironmentFlags: ReadonlySet; + /** + * `process.report` is an object whose methods are used to generate diagnostic reports for the current process. + * Additional documentation is available in the [report documentation](https://nodejs.org/docs/latest-v22.x/api/report.html). + * @since v11.8.0 + */ + report: ProcessReport; + /** + * ```js + * import { resourceUsage } from 'node:process'; + * + * console.log(resourceUsage()); + * /* + * Will output: + * { + * userCPUTime: 82872, + * systemCPUTime: 4143, + * maxRSS: 33164, + * sharedMemorySize: 0, + * unsharedDataSize: 0, + * unsharedStackSize: 0, + * minorPageFault: 2469, + * majorPageFault: 0, + * swappedOut: 0, + * fsRead: 0, + * fsWrite: 8, + * ipcSent: 0, + * ipcReceived: 0, + * signalsCount: 0, + * voluntaryContextSwitches: 79, + * involuntaryContextSwitches: 1 + * } + * + * ``` + * @since v12.6.0 + * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. + */ + resourceUsage(): ResourceUsage; + /** + * The initial value of `process.throwDeprecation` indicates whether the `--throw-deprecation` flag is set on the current Node.js process. `process.throwDeprecation` + * is mutable, so whether or not deprecation warnings result in errors may be altered at runtime. See the documentation for the 'warning' event and the emitWarning() + * method for more information. + * + * ```bash + * $ node --throw-deprecation -p "process.throwDeprecation" + * true + * $ node -p "process.throwDeprecation" + * undefined + * $ node + * > process.emitWarning('test', 'DeprecationWarning'); + * undefined + * > (node:26598) DeprecationWarning: test + * > process.throwDeprecation = true; + * true + * > process.emitWarning('test', 'DeprecationWarning'); + * Thrown: + * [DeprecationWarning: test] { name: 'DeprecationWarning' } + * ``` + * @since v0.9.12 + */ + throwDeprecation: boolean; + /** + * The `process.traceDeprecation` property indicates whether the `--trace-deprecation` flag is set on the current Node.js process. See the + * documentation for the `'warning' event` and the `emitWarning() method` for more information about this + * flag's behavior. + * @since v0.8.0 + */ + traceDeprecation: boolean; + /* EventEmitter */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + addListener(event: "worker", listener: WorkerListener): this; + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "uncaughtExceptionMonitor", error: Error): boolean; + emit(event: "unhandledRejection", reason: unknown, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: unknown, sendHandle: unknown): this; + emit(event: Signals, signal?: Signals): boolean; + emit( + event: "multipleResolves", + type: MultipleResolveType, + promise: Promise, + value: unknown, + ): this; + emit(event: "worker", listener: WorkerListener): this; + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + on(event: "worker", listener: WorkerListener): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + once(event: "worker", listener: WorkerListener): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependListener(event: "worker", listener: WorkerListener): this; + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependOnceListener(event: "worker", listener: WorkerListener): this; + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + listeners(event: "worker"): WorkerListener[]; + } + } + } + export = process; +} +declare module "node:process" { + import process = require("process"); + export = process; +} diff --git a/node_modules/@types/node/punycode.d.ts b/node_modules/@types/node/punycode.d.ts new file mode 100644 index 0000000..e788577 --- /dev/null +++ b/node_modules/@types/node/punycode.d.ts @@ -0,0 +1,117 @@ +/** + * **The version of the punycode module bundled in Node.js is being deprecated. **In a future major version of Node.js this module will be removed. Users + * currently depending on the `punycode` module should switch to using the + * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL + * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. + * + * The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It + * can be accessed using: + * + * ```js + * const punycode = require('punycode'); + * ``` + * + * [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is + * primarily intended for use in Internationalized Domain Names. Because host + * names in URLs are limited to ASCII characters only, Domain Names that contain + * non-ASCII characters must be converted into ASCII using the Punycode scheme. + * For instance, the Japanese character that translates into the English word, `'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent + * to `'example.com'`) is represented by Punycode as the ASCII string `'xn--fsq.com'`. + * + * The `punycode` module provides a simple implementation of the Punycode standard. + * + * The `punycode` module is a third-party dependency used by Node.js and + * made available to developers as a convenience. Fixes or other modifications to + * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. + * @deprecated Since v7.0.0 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/punycode.js) + */ +declare module "punycode" { + /** + * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only + * characters to the equivalent string of Unicode codepoints. + * + * ```js + * punycode.decode('maana-pta'); // 'mañana' + * punycode.decode('--dqo34k'); // '☃-⌘' + * ``` + * @since v0.5.1 + */ + function decode(string: string): string; + /** + * The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. + * + * ```js + * punycode.encode('mañana'); // 'maana-pta' + * punycode.encode('☃-⌘'); // '--dqo34k' + * ``` + * @since v0.5.1 + */ + function encode(string: string): string; + /** + * The `punycode.toUnicode()` method converts a string representing a domain name + * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be + * converted. + * + * ```js + * // decode domain names + * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + * punycode.toUnicode('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toUnicode(domain: string): string; + /** + * The `punycode.toASCII()` method converts a Unicode string representing an + * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the + * domain name will be converted. Calling `punycode.toASCII()` on a string that + * already only contains ASCII characters will have no effect. + * + * ```js + * // encode domain names + * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' + * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' + * punycode.toASCII('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toASCII(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: readonly number[]): string; + } + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} +declare module "node:punycode" { + export * from "punycode"; +} diff --git a/node_modules/@types/node/querystring.d.ts b/node_modules/@types/node/querystring.d.ts new file mode 100644 index 0000000..cb919ca --- /dev/null +++ b/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,153 @@ +/** + * The `node:querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * const querystring = require('node:querystring'); + * ``` + * + * `querystring` is more performant than `URLSearchParams` but is not a + * standardized API. Use `URLSearchParams` when performance is not critical or + * when compatibility with browser code is desirable. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/querystring.js) + */ +declare module "querystring" { + interface StringifyOptions { + /** + * The function to use when converting URL-unsafe characters to percent-encoding in the query string. + * @default `querystring.escape()` + */ + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + /** + * Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations. + * @default 1000 + */ + maxKeys?: number | undefined; + /** + * The function to use when decoding percent-encoded characters in the query string. + * @default `querystring.unescape()` + */ + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends + NodeJS.Dict< + | string + | number + | boolean + | readonly string[] + | readonly number[] + | readonly boolean[] + | null + > + {} + /** + * The `querystring.stringify()` method produces a URL query string from a + * given `obj` by iterating through the object's "own properties". + * + * It serializes the following types of values passed in `obj`: [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | + * [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to + * empty strings. + * + * ```js + * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); + * // Returns 'foo=bar&baz=qux&baz=quux&corge=' + * + * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); + * // Returns 'foo:bar;baz:qux' + * ``` + * + * By default, characters requiring percent-encoding within the query string will + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative `encodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkEncodeURIComponent function already exists, + * + * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + * { encodeURIComponent: gbkEncodeURIComponent }); + * ``` + * @since v0.1.25 + * @param obj The object to serialize into a URL query string + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + /** + * The `querystring.parse()` method parses a URL query string (`str`) into a + * collection of key and value pairs. + * + * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + * + * ```json + * { + * "foo": "bar", + * "abc": ["xyz", "123"] + * } + * ``` + * + * The object returned by the `querystring.parse()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * By default, percent-encoded characters within the query string will be assumed + * to use UTF-8 encoding. If an alternative character encoding is used, then an + * alternative `decodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkDecodeURIComponent function already exists... + * + * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, + * { decodeURIComponent: gbkDecodeURIComponent }); + * ``` + * @since v0.1.25 + * @param str The URL query string to parse + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] The substring used to delimit keys and values in the query string. + */ + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + /** + * The `querystring.escape()` method performs URL percent-encoding on the given `str` in a manner that is optimized for the specific requirements of URL + * query strings. + * + * The `querystring.escape()` method is used by `querystring.stringify()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement percent-encoding implementation if + * necessary by assigning `querystring.escape` to an alternative function. + * @since v0.1.25 + */ + function escape(str: string): string; + /** + * The `querystring.unescape()` method performs decoding of URL percent-encoded + * characters on the given `str`. + * + * The `querystring.unescape()` method is used by `querystring.parse()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement decoding implementation if + * necessary by assigning `querystring.unescape` to an alternative function. + * + * By default, the `querystring.unescape()` method will attempt to use the + * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, + * a safer equivalent that does not throw on malformed URLs will be used. + * @since v0.1.25 + */ + function unescape(str: string): string; +} +declare module "node:querystring" { + export * from "querystring"; +} diff --git a/node_modules/@types/node/readline.d.ts b/node_modules/@types/node/readline.d.ts new file mode 100644 index 0000000..b40c61f --- /dev/null +++ b/node_modules/@types/node/readline.d.ts @@ -0,0 +1,540 @@ +/** + * The `node:readline` module provides an interface for reading data from a [Readable](https://nodejs.org/docs/latest-v22.x/api/stream.html#readable-streams) stream + * (such as [`process.stdin`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdin)) one line at a time. + * + * To use the promise-based APIs: + * + * ```js + * import * as readline from 'node:readline/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as readline from 'node:readline'; + * ``` + * + * The following simple example illustrates the basic use of the `node:readline` module. + * + * ```js + * import * as readline from 'node:readline/promises'; + * import { stdin as input, stdout as output } from 'node:process'; + * + * const rl = readline.createInterface({ input, output }); + * + * const answer = await rl.question('What do you think of Node.js? '); + * + * console.log(`Thank you for your valuable feedback: ${answer}`); + * + * rl.close(); + * ``` + * + * Once this code is invoked, the Node.js application will not terminate until the `readline.Interface` is closed because the interface waits for data to be + * received on the `input` stream. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/readline.js) + */ +declare module "readline" { + import { Abortable, EventEmitter } from "node:events"; + import * as promises from "node:readline/promises"; + export { promises }; + export interface Key { + sequence?: string | undefined; + name?: string | undefined; + ctrl?: boolean | undefined; + meta?: boolean | undefined; + shift?: boolean | undefined; + } + /** + * Instances of the `readline.Interface` class are constructed using the `readline.createInterface()` method. Every instance is associated with a + * single `input` [Readable](https://nodejs.org/docs/latest-v22.x/api/stream.html#readable-streams) stream and a single `output` [Writable](https://nodejs.org/docs/latest-v22.x/api/stream.html#writable-streams) stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v0.1.104 + */ + export class Interface extends EventEmitter { + readonly terminal: boolean; + /** + * The current input data being processed by node. + * + * This can be used when collecting input from a TTY stream to retrieve the + * current value that has been processed thus far, prior to the `line` event + * being emitted. Once the `line` event has been emitted, this property will + * be an empty string. + * + * Be aware that modifying the value during the instance runtime may have + * unintended consequences if `rl.cursor` is not also controlled. + * + * **If not using a TTY stream for input, use the `'line'` event.** + * + * One possible use case would be as follows: + * + * ```js + * const values = ['lorem ipsum', 'dolor sit amet']; + * const rl = readline.createInterface(process.stdin); + * const showResults = debounce(() => { + * console.log( + * '\n', + * values.filter((val) => val.startsWith(rl.line)).join(' '), + * ); + * }, 300); + * process.stdin.on('keypress', (c, k) => { + * showResults(); + * }); + * ``` + * @since v0.1.98 + */ + readonly line: string; + /** + * The cursor position relative to `rl.line`. + * + * This will track where the current cursor lands in the input string, when + * reading input from a TTY stream. The position of cursor determines the + * portion of the input string that will be modified as input is processed, + * as well as the column where the terminal caret will be rendered. + * @since v0.1.98 + */ + readonly cursor: number; + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor(options: ReadLineOptions); + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.0, v14.17.0 + * @return the current prompt string + */ + getPrompt(): string; + /** + * The `rl.setPrompt()` method sets the prompt that will be written to `output` whenever `rl.prompt()` is called. + * @since v0.1.98 + */ + setPrompt(prompt: string): void; + /** + * The `rl.prompt()` method writes the `Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * location at which to provide input. + * + * When called, `rl.prompt()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the prompt is not written. + * @since v0.1.98 + * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. + */ + prompt(preserveCursor?: boolean): void; + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * The `callback` function passed to `rl.question()` does not follow the typical + * pattern of accepting an `Error` object or `null` as the first argument. + * The `callback` is called with the provided answer as the only argument. + * + * An error will be thrown if calling `rl.question()` after `rl.close()`. + * + * Example usage: + * + * ```js + * rl.question('What is your favorite food? ', (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * ``` + * + * Using an `AbortController` to cancel a question. + * + * ```js + * const ac = new AbortController(); + * const signal = ac.signal; + * + * rl.question('What is your favorite food? ', { signal }, (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * setTimeout(() => ac.abort(), 10000); + * ``` + * @since v0.3.3 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @param callback A callback function that is invoked with the user's input in response to the `query`. + */ + question(query: string, callback: (answer: string) => void): void; + question(query: string, options: Abortable, callback: (answer: string) => void): void; + /** + * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed + * later if necessary. + * + * Calling `rl.pause()` does not immediately pause other events (including `'line'`) from being emitted by the `Interface` instance. + * @since v0.3.4 + */ + pause(): this; + /** + * The `rl.resume()` method resumes the `input` stream if it has been paused. + * @since v0.3.4 + */ + resume(): this; + /** + * The `rl.close()` method closes the `Interface` instance and + * relinquishes control over the `input` and `output` streams. When called, + * the `'close'` event will be emitted. + * + * Calling `rl.close()` does not immediately stop other events (including `'line'`) + * from being emitted by the `Interface` instance. + * @since v0.1.98 + */ + close(): void; + /** + * The `rl.write()` method will write either `data` or a key sequence identified + * by `key` to the `output`. The `key` argument is supported only if `output` is + * a `TTY` text terminal. See `TTY keybindings` for a list of key + * combinations. + * + * If `key` is specified, `data` is ignored. + * + * When called, `rl.write()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `data` and `key` are not written. + * + * ```js + * rl.write('Delete this!'); + * // Simulate Ctrl+U to delete the line written previously + * rl.write(null, { ctrl: true, name: 'u' }); + * ``` + * + * The `rl.write()` method will write the data to the `readline` `Interface`'s `input` _as if it were provided by the user_. + * @since v0.1.98 + */ + write(data: string | Buffer, key?: Key): void; + write(data: undefined | null | string | Buffer, key: Key): void; + /** + * Returns the real position of the cursor in relation to the input + * prompt + string. Long input (wrapping) strings, as well as multiple + * line prompts are included in the calculations. + * @since v13.5.0, v12.16.0 + */ + getCursorPos(): CursorPos; + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + * 8. history + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "history", listener: (history: string[]) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "history", history: string[]): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "history", listener: (history: string[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "history", listener: (history: string[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "history", listener: (history: string[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "history", listener: (history: string[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + export type ReadLine = Interface; // type forwarded for backwards compatibility + export type Completer = (line: string) => CompleterResult; + export type AsyncCompleter = ( + line: string, + callback: (err?: null | Error, result?: CompleterResult) => void, + ) => void; + export type CompleterResult = [string[], string]; + export interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream | undefined; + completer?: Completer | AsyncCompleter | undefined; + terminal?: boolean | undefined; + /** + * Initial list of history lines. This option makes sense + * only if `terminal` is set to `true` by the user or by an internal `output` + * check, otherwise the history caching mechanism is not initialized at all. + * @default [] + */ + history?: string[] | undefined; + historySize?: number | undefined; + prompt?: string | undefined; + crlfDelay?: number | undefined; + /** + * If `true`, when a new input line added + * to the history list duplicates an older one, this removes the older line + * from the list. + * @default false + */ + removeHistoryDuplicates?: boolean | undefined; + escapeCodeTimeout?: number | undefined; + tabSize?: number | undefined; + } + /** + * The `readline.createInterface()` method creates a new `readline.Interface` instance. + * + * ```js + * const readline = require('node:readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readline.Interface` instance is created, the most common case is to + * listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * + * When creating a `readline.Interface` using `stdin` as input, the program + * will not terminate until it receives an [EOF character](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without + * waiting for user input, call `process.stdin.unref()`. + * @since v0.1.98 + */ + export function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + export function createInterface(options: ReadLineOptions): Interface; + /** + * The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. + * + * Optionally, `interface` specifies a `readline.Interface` instance for which + * autocompletion is disabled when copy-pasted input is detected. + * + * If the `stream` is a `TTY`, then it must be in raw mode. + * + * This is automatically called by any readline instance on its `input` if the `input` is a terminal. Closing the `readline` instance does not stop + * the `input` from emitting `'keypress'` events. + * + * ```js + * readline.emitKeypressEvents(process.stdin); + * if (process.stdin.isTTY) + * process.stdin.setRawMode(true); + * ``` + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * const readline = require('node:readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ', + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * const fs = require('node:fs'); + * const readline = require('node:readline'); + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity, + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * const fs = require('node:fs'); + * const readline = require('node:readline'); + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await` flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * const { once } = require('node:events'); + * const { createReadStream } = require('node:fs'); + * const { createInterface } = require('node:readline'); + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + */ + export function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + export type Direction = -1 | 0 | 1; + export interface CursorPos { + rows: number; + cols: number; + } + /** + * The `readline.clearLine()` method clears current line of given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) stream + * in a specified direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; + /** + * The `readline.clearScreenDown()` method clears the given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) stream from + * the current position of the cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; + /** + * The `readline.cursorTo()` method moves cursor to the specified position in a + * given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; + /** + * The `readline.moveCursor()` method moves the cursor _relative_ to its current + * position in a given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module "node:readline" { + export * from "readline"; +} diff --git a/node_modules/@types/node/readline/promises.d.ts b/node_modules/@types/node/readline/promises.d.ts new file mode 100644 index 0000000..f2826bb --- /dev/null +++ b/node_modules/@types/node/readline/promises.d.ts @@ -0,0 +1,150 @@ +/** + * @since v17.0.0 + * @experimental + */ +declare module "readline/promises" { + import { AsyncCompleter, Completer, Direction, Interface as _Interface, ReadLineOptions } from "node:readline"; + import { Abortable } from "node:events"; + /** + * Instances of the `readlinePromises.Interface` class are constructed using the `readlinePromises.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v17.0.0 + */ + class Interface extends _Interface { + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * If the question is called after `rl.close()`, it returns a rejected promise. + * + * Example usage: + * + * ```js + * const answer = await rl.question('What is your favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * Using an `AbortSignal` to cancel a question. + * + * ```js + * const signal = AbortSignal.timeout(10_000); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * const answer = await rl.question('What is your favorite food? ', { signal }); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * @since v17.0.0 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @return A promise that is fulfilled with the user's input in response to the `query`. + */ + question(query: string): Promise; + question(query: string, options: Abortable): Promise; + } + /** + * @since v17.0.0 + */ + class Readline { + /** + * @param stream A TTY stream. + */ + constructor( + stream: NodeJS.WritableStream, + options?: { + autoCommit?: boolean; + }, + ); + /** + * The `rl.clearLine()` method adds to the internal list of pending action an + * action that clears current line of the associated `stream` in a specified + * direction identified by `dir`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearLine(dir: Direction): this; + /** + * The `rl.clearScreenDown()` method adds to the internal list of pending action an + * action that clears the associated stream from the current position of the + * cursor down. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearScreenDown(): this; + /** + * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. + * @since v17.0.0 + */ + commit(): Promise; + /** + * The `rl.cursorTo()` method adds to the internal list of pending action an action + * that moves cursor to the specified position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + cursorTo(x: number, y?: number): this; + /** + * The `rl.moveCursor()` method adds to the internal list of pending action an + * action that moves the cursor _relative_ to its current position in the + * associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + moveCursor(dx: number, dy: number): this; + /** + * The `rl.rollback` methods clears the internal list of pending actions without + * sending it to the associated `stream`. + * @since v17.0.0 + * @return this + */ + rollback(): this; + } + /** + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. + * + * ```js + * const readlinePromises = require('node:readline/promises'); + * const rl = readlinePromises.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readlinePromises.Interface` instance is created, the most common case + * is to listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * @since v17.0.0 + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; +} +declare module "node:readline/promises" { + export * from "readline/promises"; +} diff --git a/node_modules/@types/node/repl.d.ts b/node_modules/@types/node/repl.d.ts new file mode 100644 index 0000000..c2b340c --- /dev/null +++ b/node_modules/@types/node/repl.d.ts @@ -0,0 +1,430 @@ +/** + * The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation + * that is available both as a standalone program or includible in other + * applications. It can be accessed using: + * + * ```js + * const repl = require('node:repl'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/repl.js) + */ +declare module "repl" { + import { AsyncCompleter, Completer, Interface } from "node:readline"; + import { Context } from "node:vm"; + import { InspectOptions } from "node:util"; + interface ReplOptions { + /** + * The input prompt to display. + * @default "> " + */ + prompt?: string | undefined; + /** + * The `Readable` stream from which REPL input will be read. + * @default process.stdin + */ + input?: NodeJS.ReadableStream | undefined; + /** + * The `Writable` stream to which REPL output will be written. + * @default process.stdout + */ + output?: NodeJS.WritableStream | undefined; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean | undefined; + /** + * The function to be used when evaluating each given line of input. + * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + eval?: REPLEval | undefined; + /** + * Defines if the repl prints output previews or not. + * @default `true` Always `false` in case `terminal` is falsy. + */ + preview?: boolean | undefined; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * @default the REPL instance's `terminal` value + */ + useColors?: boolean | undefined; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * @default false + */ + useGlobal?: boolean | undefined; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * @default false + */ + ignoreUndefined?: boolean | undefined; + /** + * The function to invoke to format the output of each command before writing to `output`. + * @default a wrapper for `util.inspect` + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter | undefined; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * @default false + */ + breakEvalOnSigint?: boolean | undefined; + } + type REPLEval = ( + this: REPLServer, + evalCmd: string, + context: Context, + file: string, + cb: (err: Error | null, result: any) => void, + ) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { + options: InspectOptions; + }; + type REPLCommandAction = (this: REPLServer, text: string) => void; + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string | undefined; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + /** + * Instances of `repl.REPLServer` are created using the {@link start} method + * or directly using the JavaScript `new` keyword. + * + * ```js + * const repl = require('node:repl'); + * + * const options = { useColors: true }; + * + * const firstInstance = repl.start(options); + * const secondInstance = new repl.REPLServer(options); + * ``` + * @since v0.1.91 + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * @deprecated since v14.3.0 - Use `input` instead. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * @deprecated since v14.3.0 - Use `output` instead. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly input: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly output: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: NodeJS.ReadOnlyDict; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + /** + * The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands + * to the REPL instance. Such commands are invoked by typing a `.` followed by the `keyword`. The `cmd` is either a `Function` or an `Object` with the following + * properties: + * + * The following example shows two new commands added to the REPL instance: + * + * ```js + * const repl = require('node:repl'); + * + * const replServer = repl.start({ prompt: '> ' }); + * replServer.defineCommand('sayhello', { + * help: 'Say hello', + * action(name) { + * this.clearBufferedCommand(); + * console.log(`Hello, ${name}!`); + * this.displayPrompt(); + * }, + * }); + * replServer.defineCommand('saybye', function saybye() { + * console.log('Goodbye!'); + * this.close(); + * }); + * ``` + * + * The new commands can then be used from within the REPL instance: + * + * ```console + * > .sayhello Node.js User + * Hello, Node.js User! + * > .saybye + * Goodbye! + * ``` + * @since v0.3.0 + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * The `replServer.displayPrompt()` method readies the REPL instance for input + * from the user, printing the configured `prompt` to a new line in the `output` and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the + * 'prompt'. + * + * When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. + * + * The `replServer.displayPrompt` method is primarily intended to be called from + * within the action function for commands registered using the `replServer.defineCommand()` method. + * @since v0.1.91 + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * The `replServer.clearBufferedCommand()` method clears any command that has been + * buffered but not yet executed. This method is primarily intended to be + * called from within the action function for commands registered using the `replServer.defineCommand()` method. + * @since v9.0.0 + */ + clearBufferedCommand(): void; + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command-line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @since v11.10.0 + * @param historyPath the path to the history file + * @param callback called when history writes are ready or upon error + */ + setupHistory(path: string, callback: (err: Error | null, repl: this) => void): void; + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: (context: Context) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: Context): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: (context: Context) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: (context: Context) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: (context: Context) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: (context: Context) => void): this; + } + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + const REPL_MODE_SLOPPY: unique symbol; + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + const REPL_MODE_STRICT: unique symbol; + /** + * The `repl.start()` method creates and starts a {@link REPLServer} instance. + * + * If `options` is a string, then it specifies the input prompt: + * + * ```js + * const repl = require('node:repl'); + * + * // a Unix style prompt + * repl.start('$ '); + * ``` + * @since v0.1.91 + */ + function start(options?: string | ReplOptions): REPLServer; + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + constructor(err: Error); + } +} +declare module "node:repl" { + export * from "repl"; +} diff --git a/node_modules/@types/node/sea.d.ts b/node_modules/@types/node/sea.d.ts new file mode 100644 index 0000000..0bedc62 --- /dev/null +++ b/node_modules/@types/node/sea.d.ts @@ -0,0 +1,153 @@ +/** + * This feature allows the distribution of a Node.js application conveniently to a + * system that does not have Node.js installed. + * + * Node.js supports the creation of [single executable applications](https://github.com/nodejs/single-executable) by allowing + * the injection of a blob prepared by Node.js, which can contain a bundled script, + * into the `node` binary. During start up, the program checks if anything has been + * injected. If the blob is found, it executes the script in the blob. Otherwise + * Node.js operates as it normally does. + * + * The single executable application feature currently only supports running a + * single embedded script using the `CommonJS` module system. + * + * Users can create a single executable application from their bundled script + * with the `node` binary itself and any tool which can inject resources into the + * binary. + * + * Here are the steps for creating a single executable application using one such + * tool, [postject](https://github.com/nodejs/postject): + * + * 1. Create a JavaScript file: + * ```bash + * echo 'console.log(`Hello, ${process.argv[2]}!`);' > hello.js + * ``` + * 2. Create a configuration file building a blob that can be injected into the + * single executable application (see `Generating single executable preparation blobs` for details): + * ```bash + * echo '{ "main": "hello.js", "output": "sea-prep.blob" }' > sea-config.json + * ``` + * 3. Generate the blob to be injected: + * ```bash + * node --experimental-sea-config sea-config.json + * ``` + * 4. Create a copy of the `node` executable and name it according to your needs: + * * On systems other than Windows: + * ```bash + * cp $(command -v node) hello + * ``` + * * On Windows: + * ```text + * node -e "require('fs').copyFileSync(process.execPath, 'hello.exe')" + * ``` + * The `.exe` extension is necessary. + * 5. Remove the signature of the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --remove-signature hello + * ``` + * * On Windows (optional): + * [signtool](https://learn.microsoft.com/en-us/windows/win32/seccrypto/signtool) can be used from the installed [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/). + * If this step is + * skipped, ignore any signature-related warning from postject. + * ```powershell + * signtool remove /s hello.exe + * ``` + * 6. Inject the blob into the copied binary by running `postject` with + * the following options: + * * `hello` / `hello.exe` \- The name of the copy of the `node` executable + * created in step 4. + * * `NODE_SEA_BLOB` \- The name of the resource / note / section in the binary + * where the contents of the blob will be stored. + * * `sea-prep.blob` \- The name of the blob created in step 1. + * * `--sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2` \- The [fuse](https://www.electronjs.org/docs/latest/tutorial/fuses) used by the Node.js project to detect if a file has been + * injected. + * * `--macho-segment-name NODE_SEA` (only needed on macOS) - The name of the + * segment in the binary where the contents of the blob will be + * stored. + * To summarize, here is the required command for each platform: + * * On Linux: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - PowerShell: + * ```powershell + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ` + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - Command Prompt: + * ```text + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ^ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On macOS: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \ + * --macho-segment-name NODE_SEA + * ``` + * 7. Sign the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --sign - hello + * ``` + * * On Windows (optional): + * A certificate needs to be present for this to work. However, the unsigned + * binary would still be runnable. + * ```powershell + * signtool sign /fd SHA256 hello.exe + * ``` + * 8. Run the binary: + * * On systems other than Windows + * ```console + * $ ./hello world + * Hello, world! + * ``` + * * On Windows + * ```console + * $ .\hello.exe world + * Hello, world! + * ``` + * @since v19.7.0, v18.16.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v22.x/src/node_sea.cc) + */ +declare module "node:sea" { + type AssetKey = string; + /** + * @since v20.12.0 + * @return Whether this script is running inside a single-executable application. + */ + function isSea(): boolean; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAsset(key: AssetKey): ArrayBuffer; + function getAsset(key: AssetKey, encoding: string): string; + /** + * Similar to `sea.getAsset()`, but returns the result in a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob). + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAssetAsBlob(key: AssetKey, options?: { + type: string; + }): Blob; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * + * Unlike `sea.getRawAsset()` or `sea.getAssetAsBlob()`, this method does not + * return a copy. Instead, it returns the raw asset bundled inside the executable. + * + * For now, users should avoid writing to the returned array buffer. If the + * injected section is not marked as writable or not aligned properly, + * writes to the returned array buffer is likely to result in a crash. + * @since v20.12.0 + */ + function getRawAsset(key: AssetKey): string | ArrayBuffer; +} diff --git a/node_modules/@types/node/sqlite.d.ts b/node_modules/@types/node/sqlite.d.ts new file mode 100644 index 0000000..006a25b --- /dev/null +++ b/node_modules/@types/node/sqlite.d.ts @@ -0,0 +1,213 @@ +/** + * The `node:sqlite` module facilitates working with SQLite databases. + * To access it: + * + * ```js + * import sqlite from 'node:sqlite'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import sqlite from 'sqlite'; + * ``` + * + * The following example shows the basic usage of the `node:sqlite` module to open + * an in-memory database, write data to the database, and then read the data back. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * const database = new DatabaseSync(':memory:'); + * + * // Execute SQL statements from strings. + * database.exec(` + * CREATE TABLE data( + * key INTEGER PRIMARY KEY, + * value TEXT + * ) STRICT + * `); + * // Create a prepared statement to insert data into the database. + * const insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)'); + * // Execute the prepared statement with bound values. + * insert.run(1, 'hello'); + * insert.run(2, 'world'); + * // Create a prepared statement to read data from the database. + * const query = database.prepare('SELECT * FROM data ORDER BY key'); + * // Execute the prepared statement and log the result set. + * console.log(query.all()); + * // Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ] + * ``` + * @since v22.5.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/sqlite.js) + */ +declare module "node:sqlite" { + interface DatabaseSyncOptions { + /** + * If `true`, the database is opened by the constructor. + * When this value is `false`, the database must be opened via the `open()` method. + */ + open?: boolean | undefined; + } + /** + * This class represents a single [connection](https://www.sqlite.org/c3ref/sqlite3.html) to a SQLite database. All APIs + * exposed by this class execute synchronously. + * @since v22.5.0 + */ + class DatabaseSync { + /** + * Constructs a new `DatabaseSync` instance. + * @param location The location of the database. + * A SQLite database can be stored in a file or completely [in memory](https://www.sqlite.org/inmemorydb.html). + * To use a file-backed database, the location should be a file path. + * To use an in-memory database, the location should be the special name `':memory:'`. + * @param options Configuration options for the database connection. + */ + constructor(location: string, options?: DatabaseSyncOptions); + /** + * Closes the database connection. An exception is thrown if the database is not + * open. This method is a wrapper around [`sqlite3_close_v2()`](https://www.sqlite.org/c3ref/close.html). + * @since v22.5.0 + */ + close(): void; + /** + * This method allows one or more SQL statements to be executed without returning + * any results. This method is useful when executing SQL statements read from a + * file. This method is a wrapper around [`sqlite3_exec()`](https://www.sqlite.org/c3ref/exec.html). + * @since v22.5.0 + * @param sql A SQL string to execute. + */ + exec(sql: string): void; + /** + * Opens the database specified in the `location` argument of the `DatabaseSync`constructor. This method should only be used when the database is not opened via + * the constructor. An exception is thrown if the database is already open. + * @since v22.5.0 + */ + open(): void; + /** + * Compiles a SQL statement into a [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This method is a wrapper + * around [`sqlite3_prepare_v2()`](https://www.sqlite.org/c3ref/prepare.html). + * @since v22.5.0 + * @param sql A SQL string to compile to a prepared statement. + * @return The prepared statement. + */ + prepare(sql: string): StatementSync; + } + type SupportedValueType = null | number | bigint | string | Uint8Array; + interface StatementResultingChanges { + /** + * The number of rows modified, inserted, or deleted by the most recently completed `INSERT`, `UPDATE`, or `DELETE` statement. + * This field is either a number or a `BigInt` depending on the prepared statement's configuration. + * This property is the result of [`sqlite3_changes64()`](https://www.sqlite.org/c3ref/changes.html). + */ + changes: number | bigint; + /** + * The most recently inserted rowid. + * This field is either a number or a `BigInt` depending on the prepared statement's configuration. + * This property is the result of [`sqlite3_last_insert_rowid()`](https://www.sqlite.org/c3ref/last_insert_rowid.html). + */ + lastInsertRowid: number | bigint; + } + /** + * This class represents a single [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This class cannot be + * instantiated via its constructor. Instead, instances are created via the`database.prepare()` method. All APIs exposed by this class execute + * synchronously. + * + * A prepared statement is an efficient binary representation of the SQL used to + * create it. Prepared statements are parameterizable, and can be invoked multiple + * times with different bound values. Parameters also offer protection against [SQL injection](https://en.wikipedia.org/wiki/SQL_injection) attacks. For these reasons, prepared statements are + * preferred + * over hand-crafted SQL strings when handling user input. + * @since v22.5.0 + */ + class StatementSync { + private constructor(); + /** + * This method executes a prepared statement and returns all results as an array of + * objects. If the prepared statement does not return any results, this method + * returns an empty array. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using + * the values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @return An array of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of + * the row. + */ + all(...anonymousParameters: SupportedValueType[]): unknown[]; + all( + namedParameters: Record, + ...anonymousParameters: SupportedValueType[] + ): unknown[]; + /** + * This method returns the source SQL of the prepared statement with parameter + * placeholders replaced by values. This method is a wrapper around [`sqlite3_expanded_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html). + * @since v22.5.0 + * @return The source SQL expanded to include parameter values. + */ + expandedSQL(): string; + /** + * This method executes a prepared statement and returns the first result as an + * object. If the prepared statement does not return any results, this method + * returns `undefined`. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the + * values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @return An object corresponding to the first row returned by executing the prepared statement. The keys and values of the object correspond to the column names and values of the row. If no + * rows were returned from the database then this method returns `undefined`. + */ + get(...anonymousParameters: SupportedValueType[]): unknown; + get(namedParameters: Record, ...anonymousParameters: SupportedValueType[]): unknown; + /** + * This method executes a prepared statement and returns an object summarizing the + * resulting changes. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the + * values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + */ + run(...anonymousParameters: SupportedValueType[]): StatementResultingChanges; + run( + namedParameters: Record, + ...anonymousParameters: SupportedValueType[] + ): StatementResultingChanges; + /** + * The names of SQLite parameters begin with a prefix character. By default,`node:sqlite` requires that this prefix character is present when binding + * parameters. However, with the exception of dollar sign character, these + * prefix characters also require extra quoting when used in object keys. + * + * To improve ergonomics, this method can be used to also allow bare named + * parameters, which do not require the prefix character in JavaScript code. There + * are several caveats to be aware of when enabling bare named parameters: + * + * * The prefix character is still required in SQL. + * * The prefix character is still allowed in JavaScript. In fact, prefixed names + * will have slightly better binding performance. + * * Using ambiguous named parameters, such as `$k` and `@k`, in the same prepared + * statement will result in an exception as it cannot be determined how to bind + * a bare name. + * @since v22.5.0 + * @param enabled Enables or disables support for binding named parameters without the prefix character. + */ + setAllowBareNamedParameters(enabled: boolean): void; + /** + * When reading from the database, SQLite `INTEGER`s are mapped to JavaScript + * numbers by default. However, SQLite `INTEGER`s can store values larger than + * JavaScript numbers are capable of representing. In such cases, this method can + * be used to read `INTEGER` data using JavaScript `BigInt`s. This method has no + * impact on database write operations where numbers and `BigInt`s are both + * supported at all times. + * @since v22.5.0 + * @param enabled Enables or disables the use of `BigInt`s when reading `INTEGER` fields from the database. + */ + setReadBigInts(enabled: boolean): void; + /** + * This method returns the source SQL of the prepared statement. This method is a + * wrapper around [`sqlite3_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html). + * @since v22.5.0 + * @return The source SQL used to create this prepared statement. + */ + sourceSQL(): string; + } +} diff --git a/node_modules/@types/node/stream.d.ts b/node_modules/@types/node/stream.d.ts new file mode 100644 index 0000000..a5f6ede --- /dev/null +++ b/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1707 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `node:stream` module provides an API for implementing the stream interface. + * + * There are many stream objects provided by Node.js. For instance, a [request to an HTTP server](https://nodejs.org/docs/latest-v22.x/api/http.html#class-httpincomingmessage) + * and [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of [`EventEmitter`](https://nodejs.org/docs/latest-v22.x/api/events.html#class-eventemitter). + * + * To access the `node:stream` module: + * + * ```js + * const stream = require('node:stream'); + * ``` + * + * The `node:stream` module is useful for creating new types of stream instances. + * It is usually not necessary to use the `node:stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/stream.js) + */ +declare module "stream" { + import { Abortable, EventEmitter } from "node:events"; + import { Blob as NodeBlob } from "node:buffer"; + import * as streamPromises from "node:stream/promises"; + import * as streamConsumers from "node:stream/consumers"; + import * as streamWeb from "node:stream/web"; + + type ComposeFnParam = (source: any) => void; + + class internal extends EventEmitter { + pipe( + destination: T, + options?: { + end?: boolean | undefined; + }, + ): T; + compose( + stream: T | ComposeFnParam | Iterable | AsyncIterable, + options?: { signal: AbortSignal }, + ): T; + } + import Stream = internal.Stream; + import Readable = internal.Readable; + import ReadableOptions = internal.ReadableOptions; + interface ArrayOptions { + /** + * The maximum concurrent invocations of `fn` to call on the stream at once. + * @default 1 + */ + concurrency?: number; + /** Allows destroying the stream if the signal is aborted. */ + signal?: AbortSignal; + } + class ReadableBase extends Stream implements NodeJS.ReadableStream { + /** + * A utility method for creating Readable Streams out of iterators. + * @since v12.3.0, v10.17.0 + * @param iterable Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed. + * @param options Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + * @experimental + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call {@link read}, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + * @since v11.4.0 + */ + readable: boolean; + /** + * Returns whether `'data'` has been emitted. + * @since v16.7.0, v14.18.0 + * @experimental + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding` property can be set using the {@link setEncoding} method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when [`'end'`](https://nodejs.org/docs/latest-v22.x/api/stream.html#event-end) event is emitted. + * @since v12.9.0 + */ + readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the [Three states](https://nodejs.org/docs/latest-v22.x/api/stream.html#three-states) section. + * @since v9.4.0 + */ + readonly readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + * @since v9.3.0 + */ + readonly readableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be read. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + * @since v12.3.0 + */ + readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + constructor(opts?: ReadableOptions); + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + /** + * The `readable.read()` method reads data out of the internal buffer and + * returns it. If no data is available to be read, `null` is returned. By default, + * the data is returned as a `Buffer` object unless an encoding has been + * specified using the `readable.setEncoding()` method or the stream is operating + * in object mode. + * + * The optional `size` argument specifies a specific number of bytes to read. If + * `size` bytes are not available to be read, `null` will be returned _unless_ the + * stream has ended, in which case all of the data remaining in the internal buffer + * will be returned. + * + * If the `size` argument is not specified, all of the data contained in the + * internal buffer will be returned. + * + * The `size` argument must be less than or equal to 1 GiB. + * + * The `readable.read()` method should only be called on `Readable` streams + * operating in paused mode. In flowing mode, `readable.read()` is called + * automatically until the internal buffer is fully drained. + * + * ```js + * const readable = getReadableStreamSomehow(); + * + * // 'readable' may be triggered multiple times as data is buffered in + * readable.on('readable', () => { + * let chunk; + * console.log('Stream is readable (new data received in buffer)'); + * // Use a loop to make sure we read all currently available data + * while (null !== (chunk = readable.read())) { + * console.log(`Read ${chunk.length} bytes of data...`); + * } + * }); + * + * // 'end' will be triggered once when there is no more data available + * readable.on('end', () => { + * console.log('Reached end of stream.'); + * }); + * ``` + * + * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks + * are not concatenated. A `while` loop is necessary to consume all data + * currently in the buffer. When reading a large file `.read()` may return `null`, + * having consumed all buffered content so far, but there is still more data to + * come not yet buffered. In this case a new `'readable'` event will be emitted + * when there is more data in the buffer. Finally the `'end'` event will be + * emitted when there is no more data to come. + * + * Therefore to read a file's whole contents from a `readable`, it is necessary + * to collect chunks across multiple `'readable'` events: + * + * ```js + * const chunks = []; + * + * readable.on('readable', () => { + * let chunk; + * while (null !== (chunk = readable.read())) { + * chunks.push(chunk); + * } + * }); + * + * readable.on('end', () => { + * const content = chunks.join(''); + * }); + * ``` + * + * A `Readable` stream in object mode will always return a single item from + * a call to `readable.read(size)`, regardless of the value of the `size` argument. + * + * If the `readable.read()` method returns a chunk of data, a `'data'` event will + * also be emitted. + * + * Calling {@link read} after the `'end'` event has + * been emitted will return `null`. No runtime error will be raised. + * @since v0.9.4 + * @param size Optional argument to specify how much data to read. + */ + read(size?: number): any; + /** + * The `readable.setEncoding()` method sets the character encoding for + * data read from the `Readable` stream. + * + * By default, no encoding is assigned and stream data will be returned as `Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer` objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling `readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * string format. + * + * The `Readable` stream will properly handle multi-byte characters delivered + * through the stream that would otherwise become improperly decoded if simply + * pulled from the stream as `Buffer` objects. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.setEncoding('utf8'); + * readable.on('data', (chunk) => { + * assert.equal(typeof chunk, 'string'); + * console.log('Got %d characters of string data:', chunk.length); + * }); + * ``` + * @since v0.9.4 + * @param encoding The encoding to use. + */ + setEncoding(encoding: BufferEncoding): this; + /** + * The `readable.pause()` method will cause a stream in flowing mode to stop + * emitting `'data'` events, switching out of flowing mode. Any data that + * becomes available will remain in the internal buffer. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.on('data', (chunk) => { + * console.log(`Received ${chunk.length} bytes of data.`); + * readable.pause(); + * console.log('There will be no additional data for 1 second.'); + * setTimeout(() => { + * console.log('Now data will start flowing again.'); + * readable.resume(); + * }, 1000); + * }); + * ``` + * + * The `readable.pause()` method has no effect if there is a `'readable'` event listener. + * @since v0.9.4 + */ + pause(): this; + /** + * The `readable.resume()` method causes an explicitly paused `Readable` stream to + * resume emitting `'data'` events, switching the stream into flowing mode. + * + * The `readable.resume()` method can be used to fully consume the data from a + * stream without actually processing any of that data: + * + * ```js + * getReadableStreamSomehow() + * .resume() + * .on('end', () => { + * console.log('Reached the end, but did not read anything.'); + * }); + * ``` + * + * The `readable.resume()` method has no effect if there is a `'readable'` event listener. + * @since v0.9.4 + */ + resume(): this; + /** + * The `readable.isPaused()` method returns the current operating state of the `Readable`. + * This is used primarily by the mechanism that underlies the `readable.pipe()` method. + * In most typical cases, there will be no reason to use this method directly. + * + * ```js + * const readable = new stream.Readable(); + * + * readable.isPaused(); // === false + * readable.pause(); + * readable.isPaused(); // === true + * readable.resume(); + * readable.isPaused(); // === false + * ``` + * @since v0.11.14 + */ + isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * const fs = require('node:fs'); + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @since v0.9.4 + * @param destination Optional specific stream to unpipe + */ + unpipe(destination?: NodeJS.WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * const { StringDecoder } = require('node:string_decoder'); + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.includes('\n\n')) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * return; + * } + * // Still reading the header. + * header += str; + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @since v0.9.11 + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must + * be a {string}, {Buffer}, {TypedArray}, {DataView} or `null`. For object mode streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ + unshift(chunk: any, encoding?: BufferEncoding): void; + /** + * Prior to Node.js 0.10, streams did not implement the entire `node:stream` module API as it is currently defined. (See `Compatibility` for more + * information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the `readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * const { OldReader } = require('./old-api-module.js'); + * const { Readable } = require('node:stream'); + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @since v0.9.4 + * @param stream An "old style" readable stream + */ + wrap(stream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + /** + * The iterator created by this method gives users the option to cancel the destruction + * of the stream if the `for await...of` loop is exited by `return`, `break`, or `throw`, + * or if the iterator should destroy the stream if the stream emitted an error during iteration. + * @since v16.3.0 + * @param options.destroyOnReturn When set to `false`, calling `return` on the async iterator, + * or exiting a `for await...of` iteration using a `break`, `return`, or `throw` will not destroy the stream. + * **Default: `true`**. + */ + iterator(options?: { destroyOnReturn?: boolean }): AsyncIterableIterator; + /** + * This method allows mapping over the stream. The *fn* function will be called for every chunk in the stream. + * If the *fn* function returns a promise - that promise will be `await`ed before being passed to the result stream. + * @since v17.4.0, v16.14.0 + * @param fn a function to map over every chunk in the stream. Async or not. + * @returns a stream mapped with the function *fn*. + */ + map(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method allows filtering the stream. For each chunk in the stream the *fn* function will be called + * and if it returns a truthy value, the chunk will be passed to the result stream. + * If the *fn* function returns a promise - that promise will be `await`ed. + * @since v17.4.0, v16.14.0 + * @param fn a function to filter chunks from the stream. Async or not. + * @returns a stream filtered with the predicate *fn*. + */ + filter( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Readable; + /** + * This method allows iterating a stream. For each chunk in the stream the *fn* function will be called. + * If the *fn* function returns a promise - that promise will be `await`ed. + * + * This method is different from `for await...of` loops in that it can optionally process chunks concurrently. + * In addition, a `forEach` iteration can only be stopped by having passed a `signal` option + * and aborting the related AbortController while `for await...of` can be stopped with `break` or `return`. + * In either case the stream will be destroyed. + * + * This method is different from listening to the `'data'` event in that it uses the `readable` event + * in the underlying machinary and can limit the number of concurrent *fn* calls. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise for when the stream has finished. + */ + forEach( + fn: (data: any, options?: Pick) => void | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method allows easily obtaining the contents of a stream. + * + * As this method reads the entire stream into memory, it negates the benefits of streams. It's intended + * for interoperability and convenience, not as the primary way to consume streams. + * @since v17.5.0 + * @returns a promise containing an array with the contents of the stream. + */ + toArray(options?: Pick): Promise; + /** + * This method is similar to `Array.prototype.some` and calls *fn* on each chunk in the stream + * until the awaited return value is `true` (or any truthy value). Once an *fn* call on a chunk + * `await`ed return value is truthy, the stream is destroyed and the promise is fulfilled with `true`. + * If none of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `false`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for at least one of the chunks. + */ + some( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.find` and calls *fn* on each chunk in the stream + * to find a chunk with a truthy value for *fn*. Once an *fn* call's awaited return value is truthy, + * the stream is destroyed and the promise is fulfilled with value for which *fn* returned a truthy value. + * If all of the *fn* calls on the chunks return a falsy value, the promise is fulfilled with `undefined`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to the first chunk for which *fn* evaluated with a truthy value, + * or `undefined` if no element was found. + */ + find( + fn: (data: any, options?: Pick) => data is T, + options?: ArrayOptions, + ): Promise; + find( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.every` and calls *fn* on each chunk in the stream + * to check if all awaited return values are truthy value for *fn*. Once an *fn* call on a chunk + * `await`ed return value is falsy, the stream is destroyed and the promise is fulfilled with `false`. + * If all of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `true`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for every one of the chunks. + */ + every( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method returns a new stream by applying the given callback to each chunk of the stream + * and then flattening the result. + * + * It is possible to return a stream or another iterable or async iterable from *fn* and the result streams + * will be merged (flattened) into the returned stream. + * @since v17.5.0 + * @param fn a function to map over every chunk in the stream. May be async. May be a stream or generator. + * @returns a stream flat-mapped with the function *fn*. + */ + flatMap(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method returns a new stream with the first *limit* chunks dropped from the start. + * @since v17.5.0 + * @param limit the number of chunks to drop from the readable. + * @returns a stream with *limit* chunks dropped from the start. + */ + drop(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with the first *limit* chunks. + * @since v17.5.0 + * @param limit the number of chunks to take from the readable. + * @returns a stream with *limit* chunks taken. + */ + take(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with chunks of the underlying stream paired with a counter + * in the form `[index, chunk]`. The first index value is `0` and it increases by 1 for each chunk produced. + * @since v17.5.0 + * @returns a stream of indexed pairs. + */ + asIndexedPairs(options?: Pick): Readable; + /** + * This method calls *fn* on each chunk of the stream in order, passing it the result from the calculation + * on the previous element. It returns a promise for the final value of the reduction. + * + * If no *initial* value is supplied the first chunk of the stream is used as the initial value. + * If the stream is empty, the promise is rejected with a `TypeError` with the `ERR_INVALID_ARGS` code property. + * + * The reducer function iterates the stream element-by-element which means that there is no *concurrency* parameter + * or parallelism. To perform a reduce concurrently, you can extract the async function to `readable.map` method. + * @since v17.5.0 + * @param fn a reducer function to call over every chunk in the stream. Async or not. + * @param initial the initial value to use in the reduction. + * @returns a promise for the final value of the reduction. + */ + reduce( + fn: (previous: any, data: any, options?: Pick) => T, + initial?: undefined, + options?: Pick, + ): Promise; + reduce( + fn: (previous: T, data: any, options?: Pick) => T, + initial: T, + options?: Pick, + ): Promise; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()` will be ignored. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, but instead implement `readable._destroy()`. + * @since v8.0.0 + * @param error Error which will be passed as payload in `'error'` event + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. error + * 5. pause + * 6. readable + * 7. resume + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "pause"): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + /** + * Calls `readable.destroy()` with an `AbortError` and returns a promise that fulfills when the stream is finished. + * @since v20.4.0 + */ + [Symbol.asyncDispose](): Promise; + } + import WritableOptions = internal.WritableOptions; + class WritableBase extends Stream implements NodeJS.WritableStream { + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored, or ended. + * @since v11.4.0 + */ + readonly writable: boolean; + /** + * Is `true` after `writable.end()` has been called. This property + * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. + * @since v12.9.0 + */ + readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + * @since v12.6.0 + */ + readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + * @since v9.3.0 + */ + readonly writableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be written. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + * @since v12.3.0 + */ + readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + * @since v13.2.0, v12.16.0 + */ + readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + /** + * Is `true` if the stream's buffer has been full and stream will emit `'drain'`. + * @since v15.2.0, v14.17.0 + */ + readonly writableNeedDrain: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + _construct?(callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + /** + * The `writable.write()` method writes some data to the stream, and calls the + * supplied `callback` once the data has been fully handled. If an error + * occurs, the `callback` will be called with the error as its + * first argument. The `callback` is called asynchronously and before `'error'` is + * emitted. + * + * The return value is `true` if the internal buffer is less than the `highWaterMark` configured when the stream was created after admitting `chunk`. + * If `false` is returned, further attempts to write data to the stream should + * stop until the `'drain'` event is emitted. + * + * While a stream is not draining, calls to `write()` will buffer `chunk`, and + * return false. Once all currently buffered chunks are drained (accepted for + * delivery by the operating system), the `'drain'` event will be emitted. + * Once `write()` returns false, do not write more chunks + * until the `'drain'` event is emitted. While calling `write()` on a stream that + * is not draining is allowed, Node.js will buffer all written chunks until + * maximum memory usage occurs, at which point it will abort unconditionally. + * Even before it aborts, high memory usage will cause poor garbage collector + * performance and high RSS (which is not typically released back to the system, + * even after the memory is no longer required). Since TCP sockets may never + * drain if the remote peer does not read the data, writing a socket that is + * not draining may lead to a remotely exploitable vulnerability. + * + * Writing data while the stream is not draining is particularly + * problematic for a `Transform`, because the `Transform` streams are paused + * by default until they are piped or a `'data'` or `'readable'` event handler + * is added. + * + * If the data to be written can be generated or fetched on demand, it is + * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is + * possible to respect backpressure and avoid memory issues using the `'drain'` event: + * + * ```js + * function write(data, cb) { + * if (!stream.write(data)) { + * stream.once('drain', cb); + * } else { + * process.nextTick(cb); + * } + * } + * + * // Wait for cb to be called before doing any other write. + * write('hello', () => { + * console.log('Write completed, do more writes now.'); + * }); + * ``` + * + * A `Writable` stream in object mode will always ignore the `encoding` argument. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param [encoding='utf8'] The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @since v0.11.15 + * @param encoding The new default encoding + */ + setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * const fs = require('node:fs'); + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param callback Callback for when the stream is finished. + */ + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()` buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing `writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + * @since v0.11.2 + */ + cork(): void; + /** + * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. + * + * When using `writable.cork()` and `writable.uncork()` to manage the buffering + * of writes to a stream, defer calls to `writable.uncork()` using `process.nextTick()`. Doing so allows batching of all `writable.write()` calls that occur within a given Node.js event + * loop phase. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.write('data '); + * process.nextTick(() => stream.uncork()); + * ``` + * + * If the `writable.cork()` method is called multiple times on a stream, the + * same number of calls to `writable.uncork()` must be called to flush the buffered + * data. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.cork(); + * stream.write('data '); + * process.nextTick(() => { + * stream.uncork(); + * // The data will not be flushed until uncork() is called a second time. + * stream.uncork(); + * }); + * ``` + * + * See also: `writable.cork()`. + * @since v0.11.2 + */ + uncork(): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the writable + * stream has ended and subsequent calls to `write()` or `end()` will result in + * an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to `write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * Use `end()` instead of destroy if data should flush before close, or wait for + * the `'drain'` event before destroying the stream. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, + * but instead implement `writable._destroy()`. + * @since v8.0.0 + * @param error Optional, an error to emit with `'error'` event. + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + namespace internal { + class Stream extends internal { + constructor(opts?: ReadableOptions); + } + interface StreamOptions extends Abortable { + emitClose?: boolean | undefined; + highWaterMark?: number | undefined; + objectMode?: boolean | undefined; + construct?(this: T, callback: (error?: Error | null) => void): void; + destroy?(this: T, error: Error | null, callback: (error?: Error | null) => void): void; + autoDestroy?: boolean | undefined; + } + interface ReadableOptions extends StreamOptions { + encoding?: BufferEncoding | undefined; + read?(this: Readable, size: number): void; + } + /** + * @since v0.9.4 + */ + class Readable extends ReadableBase { + /** + * A utility method for creating a `Readable` from a web `ReadableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + readableStream: streamWeb.ReadableStream, + options?: Pick, + ): Readable; + /** + * A utility method for creating a web `ReadableStream` from a `Readable`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamReadable: Readable): streamWeb.ReadableStream; + } + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean | undefined; + defaultEncoding?: BufferEncoding | undefined; + write?( + this: Writable, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void; + writev?( + this: Writable, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Writable, callback: (error?: Error | null) => void): void; + } + /** + * @since v0.9.4 + */ + class Writable extends WritableBase { + /** + * A utility method for creating a `Writable` from a web `WritableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + writableStream: streamWeb.WritableStream, + options?: Pick, + ): Writable; + /** + * A utility method for creating a web `WritableStream` from a `Writable`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamWritable: Writable): streamWeb.WritableStream; + } + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean | undefined; + readableObjectMode?: boolean | undefined; + writableObjectMode?: boolean | undefined; + readableHighWaterMark?: number | undefined; + writableHighWaterMark?: number | undefined; + writableCorked?: number | undefined; + construct?(this: Duplex, callback: (error?: Error | null) => void): void; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Duplex, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error?: Error | null) => void): void; + } + /** + * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Duplex` streams include: + * + * * `TCP sockets` + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Duplex extends ReadableBase implements WritableBase { + readonly writable: boolean; + readonly writableEnded: boolean; + readonly writableFinished: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + readonly writableObjectMode: boolean; + readonly writableCorked: number; + readonly writableNeedDrain: boolean; + readonly closed: boolean; + readonly errored: Error | null; + /** + * If `false` then the stream will automatically end the writable side when the + * readable side ends. Set initially by the `allowHalfOpen` constructor option, + * which defaults to `true`. + * + * This can be changed manually to change the half-open behavior of an existing + * `Duplex` stream instance, but must be changed before the `'end'` event is emitted. + * @since v0.9.4 + */ + allowHalfOpen: boolean; + constructor(opts?: DuplexOptions); + /** + * A utility method for creating duplex streams. + * + * - `Stream` converts writable stream into writable `Duplex` and readable stream + * to `Duplex`. + * - `Blob` converts into readable `Duplex`. + * - `string` converts into readable `Duplex`. + * - `ArrayBuffer` converts into readable `Duplex`. + * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. + * - `AsyncGeneratorFunction` converts into a readable/writable transform + * `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + * `null`. + * - `AsyncFunction` converts into a writable `Duplex`. Must return + * either `null` or `undefined` + * - `Object ({ writable, readable })` converts `readable` and + * `writable` into `Stream` and then combines them into `Duplex` where the + * `Duplex` will write to the `writable` and read from the `readable`. + * - `Promise` converts into readable `Duplex`. Value `null` is ignored. + * + * @since v16.8.0 + */ + static from( + src: + | Stream + | NodeBlob + | ArrayBuffer + | string + | Iterable + | AsyncIterable + | AsyncGeneratorFunction + | Promise + | Object, + ): Duplex; + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: BufferEncoding): this; + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding?: BufferEncoding, cb?: () => void): this; + cork(): void; + uncork(): void; + /** + * A utility method for creating a web `ReadableStream` and `WritableStream` from a `Duplex`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamDuplex: Duplex): { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }; + /** + * A utility method for creating a `Duplex` from a web `ReadableStream` and `WritableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + duplexStream: { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }, + options?: Pick< + DuplexOptions, + "allowHalfOpen" | "decodeStrings" | "encoding" | "highWaterMark" | "objectMode" | "signal" + >, + ): Duplex; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. drain + * 4. end + * 5. error + * 6. finish + * 7. pause + * 8. pipe + * 9. readable + * 10. resume + * 11. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pause"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pause", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pause", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + construct?(this: Transform, callback: (error?: Error | null) => void): void; + read?(this: Transform, size: number): void; + write?( + this: Transform, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void; + writev?( + this: Transform, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error?: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + flush?(this: Transform, callback: TransformCallback): void; + } + /** + * Transform streams are `Duplex` streams where the output is in some way + * related to the input. Like all `Duplex` streams, `Transform` streams + * implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Transform` streams include: + * + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + /** + * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is + * primarily for examples and testing, but there are some use cases where `stream.PassThrough` is useful as a building block for novel sorts of streams. + */ + class PassThrough extends Transform {} + /** + * A stream to attach a signal to. + * + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed `AbortSignal` will behave the same way as calling `.destroy(new AbortError())` on the + * stream, and `controller.error(new AbortError())` for webstreams. + * + * ```js + * const fs = require('node:fs'); + * + * const controller = new AbortController(); + * const read = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * // Later, abort the operation closing the stream + * controller.abort(); + * ``` + * + * Or using an `AbortSignal` with a readable stream as an async iterable: + * + * ```js + * const controller = new AbortController(); + * setTimeout(() => controller.abort(), 10_000); // set a timeout + * const stream = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * (async () => { + * try { + * for await (const chunk of stream) { + * await process(chunk); + * } + * } catch (e) { + * if (e.name === 'AbortError') { + * // The operation was cancelled + * } else { + * throw e; + * } + * } + * })(); + * ``` + * + * Or using an `AbortSignal` with a ReadableStream: + * + * ```js + * const controller = new AbortController(); + * const rs = new ReadableStream({ + * start(controller) { + * controller.enqueue('hello'); + * controller.enqueue('world'); + * controller.close(); + * }, + * }); + * + * addAbortSignal(controller.signal, rs); + * + * finished(rs, (err) => { + * if (err) { + * if (err.name === 'AbortError') { + * // The operation was cancelled + * } + * } + * }); + * + * const reader = rs.getReader(); + * + * reader.read().then(({ value, done }) => { + * console.log(value); // hello + * console.log(done); // false + * controller.abort(); + * }); + * ``` + * @since v15.4.0 + * @param signal A signal representing possible cancellation + * @param stream A stream to attach a signal to. + */ + function addAbortSignal(signal: AbortSignal, stream: T): T; + /** + * Returns the default highWaterMark used by streams. + * Defaults to `65536` (64 KiB), or `16` for `objectMode`. + * @since v19.9.0 + */ + function getDefaultHighWaterMark(objectMode: boolean): number; + /** + * Sets the default highWaterMark used by streams. + * @since v19.9.0 + * @param value highWaterMark value + */ + function setDefaultHighWaterMark(objectMode: boolean, value: number): void; + interface FinishedOptions extends Abortable { + error?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + /** + * A readable and/or writable stream/webstream. + * + * A function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * const { finished } = require('node:stream'); + * const fs = require('node:fs'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * finished(rs, (err) => { + * if (err) { + * console.error('Stream failed.', err); + * } else { + * console.log('Stream is done reading.'); + * } + * }); + * + * rs.resume(); // Drain the stream. + * ``` + * + * Especially useful in error handling scenarios where a stream is destroyed + * prematurely (like an aborted HTTP request), and will not emit `'end'` or `'finish'`. + * + * The `finished` API provides [`promise version`](https://nodejs.org/docs/latest-v22.x/api/stream.html#streamfinishedstream-options). + * + * `stream.finished()` leaves dangling event listeners (in particular `'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * invoked. The reason for this is so that unexpected `'error'` events (due to + * incorrect stream implementations) do not cause unexpected crashes. + * If this is unwanted behavior then the returned cleanup function needs to be + * invoked in the callback: + * + * ```js + * const cleanup = finished(rs, (err) => { + * cleanup(); + * // ... + * }); + * ``` + * @since v10.0.0 + * @param stream A readable and/or writable stream. + * @param callback A callback function that takes an optional error argument. + * @returns A cleanup function which removes all registered listeners. + */ + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options: FinishedOptions, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + namespace finished { + function __promisify__( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + } + type PipelineSourceFunction = () => Iterable | AsyncIterable; + type PipelineSource = Iterable | AsyncIterable | NodeJS.ReadableStream | PipelineSourceFunction; + type PipelineTransform, U> = + | NodeJS.ReadWriteStream + | (( + source: S extends (...args: any[]) => Iterable | AsyncIterable ? AsyncIterable + : S, + ) => AsyncIterable); + type PipelineTransformSource = PipelineSource | PipelineTransform; + type PipelineDestinationIterableFunction = (source: AsyncIterable) => AsyncIterable; + type PipelineDestinationPromiseFunction = (source: AsyncIterable) => Promise

; + type PipelineDestination, P> = S extends + PipelineTransformSource ? + | NodeJS.WritableStream + | PipelineDestinationIterableFunction + | PipelineDestinationPromiseFunction + : never; + type PipelineCallback> = S extends + PipelineDestinationPromiseFunction ? (err: NodeJS.ErrnoException | null, value: P) => void + : (err: NodeJS.ErrnoException | null) => void; + type PipelinePromise> = S extends + PipelineDestinationPromiseFunction ? Promise

: Promise; + interface PipelineOptions { + signal?: AbortSignal | undefined; + end?: boolean | undefined; + } + /** + * A module method to pipe between streams and generators forwarding errors and + * properly cleaning up and provide a callback when the pipeline is complete. + * + * ```js + * const { pipeline } = require('node:stream'); + * const fs = require('node:fs'); + * const zlib = require('node:zlib'); + * + * // Use the pipeline API to easily pipe a series of streams + * // together and get notified when the pipeline is fully done. + * + * // A pipeline to gzip a potentially huge tar file efficiently: + * + * pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * (err) => { + * if (err) { + * console.error('Pipeline failed.', err); + * } else { + * console.log('Pipeline succeeded.'); + * } + * }, + * ); + * ``` + * + * The `pipeline` API provides a [`promise version`](https://nodejs.org/docs/latest-v22.x/api/stream.html#streampipelinesource-transforms-destination-options). + * + * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * + * * `Readable` streams which have emitted `'end'` or `'close'`. + * * `Writable` streams which have emitted `'finish'` or `'close'`. + * + * `stream.pipeline()` leaves dangling event listeners on the streams + * after the `callback` has been invoked. In the case of reuse of streams after + * failure, this can cause event listener leaks and swallowed errors. If the last + * stream is readable, dangling event listeners will be removed so that the last + * stream can be consumed later. + * + * `stream.pipeline()` closes all the streams when an error is raised. + * The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior + * once it would destroy the socket without sending the expected response. + * See the example below: + * + * ```js + * const fs = require('node:fs'); + * const http = require('node:http'); + * const { pipeline } = require('node:stream'); + * + * const server = http.createServer((req, res) => { + * const fileStream = fs.createReadStream('./fileNotExist.txt'); + * pipeline(fileStream, res, (err) => { + * if (err) { + * console.log(err); // No such file + * // this message can't be sent once `pipeline` already destroyed the socket + * return res.end('error!!!'); + * } + * }); + * }); + * ``` + * @since v10.0.0 + * @param callback Called when the pipeline is fully done. + */ + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline( + streams: ReadonlyArray, + callback: (err: NodeJS.ErrnoException | null) => void, + ): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array< + NodeJS.ReadWriteStream | NodeJS.WritableStream | ((err: NodeJS.ErrnoException | null) => void) + > + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; + } + interface Pipe { + close(): void; + hasRef(): boolean; + ref(): void; + unref(): void; + } + /** + * Returns whether the stream has encountered an error. + * @since v17.3.0, v16.14.0 + * @experimental + */ + function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; + /** + * Returns whether the stream is readable. + * @since v17.4.0, v16.14.0 + * @experimental + */ + function isReadable(stream: Readable | NodeJS.ReadableStream): boolean; + const promises: typeof streamPromises; + const consumers: typeof streamConsumers; + } + export = internal; +} +declare module "node:stream" { + import stream = require("stream"); + export = stream; +} diff --git a/node_modules/@types/node/stream/consumers.d.ts b/node_modules/@types/node/stream/consumers.d.ts new file mode 100644 index 0000000..5ad9cba --- /dev/null +++ b/node_modules/@types/node/stream/consumers.d.ts @@ -0,0 +1,12 @@ +declare module "stream/consumers" { + import { Blob as NodeBlob } from "node:buffer"; + import { Readable } from "node:stream"; + function buffer(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function text(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function arrayBuffer(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function blob(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function json(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; +} +declare module "node:stream/consumers" { + export * from "stream/consumers"; +} diff --git a/node_modules/@types/node/stream/promises.d.ts b/node_modules/@types/node/stream/promises.d.ts new file mode 100644 index 0000000..6eac5b7 --- /dev/null +++ b/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,83 @@ +declare module "stream/promises" { + import { + FinishedOptions, + PipelineDestination, + PipelineOptions, + PipelinePromise, + PipelineSource, + PipelineTransform, + } from "node:stream"; + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; +} +declare module "node:stream/promises" { + export * from "stream/promises"; +} diff --git a/node_modules/@types/node/stream/web.d.ts b/node_modules/@types/node/stream/web.d.ts new file mode 100644 index 0000000..35e2a31 --- /dev/null +++ b/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,606 @@ +type _ByteLengthQueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ByteLengthQueuingStrategy; +type _CompressionStream = typeof globalThis extends { onmessage: any; ReportingObserver: any } ? {} + : import("stream/web").CompressionStream; +type _CountQueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").CountQueuingStrategy; +type _DecompressionStream = typeof globalThis extends { onmessage: any; ReportingObserver: any } ? {} + : import("stream/web").DecompressionStream; +type _ReadableByteStreamController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableByteStreamController; +type _ReadableStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStream; +type _ReadableStreamBYOBReader = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamBYOBReader; +type _ReadableStreamBYOBRequest = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamBYOBRequest; +type _ReadableStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamDefaultController; +type _ReadableStreamDefaultReader = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamDefaultReader; +type _TextDecoderStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TextDecoderStream; +type _TextEncoderStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TextEncoderStream; +type _TransformStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TransformStream; +type _TransformStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TransformStreamDefaultController; +type _WritableStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStream; +type _WritableStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStreamDefaultController; +type _WritableStreamDefaultWriter = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStreamDefaultWriter; + +declare module "stream/web" { + // stub module, pending copy&paste from .d.ts or manual impl + // copy from lib.dom.d.ts + interface ReadableWritablePair { + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream + * through a transform stream (or any other { writable, readable } + * pair). It simply pipes the stream into the writable side of the + * supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + */ + writable: WritableStream; + } + interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. + * The way in which the piping process behaves under various error + * conditions can be customized with a number of passed options. It + * returns a promise that fulfills when the piping process completes + * successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate + * as follows: + * + * An error in this source readable stream will abort destination, + * unless preventAbort is truthy. The returned promise will be rejected + * with the source's error, or with any error that occurs during + * aborting the destination. + * + * An error in destination will cancel this source readable stream, + * unless preventCancel is truthy. The returned promise will be rejected + * with the destination's error, or with any error that occurs during + * canceling the source. + * + * When this source readable stream closes, destination will be closed, + * unless preventClose is truthy. The returned promise will be fulfilled + * once this process completes, unless an error is encountered while + * closing the destination, in which case it will be rejected with that + * error. + * + * If destination starts out closed or closing, this source readable + * stream will be canceled, unless preventCancel is true. The returned + * promise will be rejected with an error indicating piping to a closed + * stream failed, or with any error that occurs during canceling the + * source. + * + * The signal option can be set to an AbortSignal to allow aborting an + * ongoing pipe operation via the corresponding AbortController. In this + * case, this source readable stream will be canceled, and destination + * aborted, unless the respective options preventCancel or preventAbort + * are set. + */ + preventClose?: boolean; + signal?: AbortSignal; + } + interface ReadableStreamGenericReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + } + type ReadableStreamController = ReadableStreamDefaultController; + interface ReadableStreamReadValueResult { + done: false; + value: T; + } + interface ReadableStreamReadDoneResult { + done: true; + value?: T; + } + type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; + interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; + } + interface UnderlyingSinkAbortCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSinkCloseCallback { + (): void | PromiseLike; + } + interface UnderlyingSinkStartCallback { + (controller: WritableStreamDefaultController): any; + } + interface UnderlyingSinkWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; + } + interface UnderlyingSourceCancelCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSourcePullCallback { + (controller: ReadableStreamController): void | PromiseLike; + } + interface UnderlyingSourceStartCallback { + (controller: ReadableStreamController): any; + } + interface TransformerFlushCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerStartCallback { + (controller: TransformStreamDefaultController): any; + } + interface TransformerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; + } + interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: "bytes"; + } + interface UnderlyingSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback; + start?: UnderlyingSourceStartCallback; + type?: undefined; + } + interface UnderlyingSink { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined; + write?: UnderlyingSinkWriteCallback; + } + interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; + } + /** This Streams API interface represents a readable stream of byte data. */ + interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; + getReader(): ReadableStreamDefaultReader; + getReader(options?: ReadableStreamGetReaderOptions): ReadableStreamReader; + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; + values(options?: { preventCancel?: boolean }): AsyncIterableIterator; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + const ReadableStream: { + prototype: ReadableStream; + from(iterable: Iterable | AsyncIterable): ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + }; + type ReadableStreamReaderMode = "byob"; + interface ReadableStreamGetReaderOptions { + /** + * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode?: ReadableStreamReaderMode; + } + type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ + interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read(view: T): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + } + const ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new(stream: ReadableStream): ReadableStreamDefaultReader; + }; + const ReadableStreamBYOBReader: { + prototype: ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; + }; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ + interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + readonly view: ArrayBufferView | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBufferView): void; + } + const ReadableStreamBYOBRequest: { + prototype: ReadableStreamBYOBRequest; + new(): ReadableStreamBYOBRequest; + }; + interface ReadableByteStreamController { + readonly byobRequest: undefined; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; + } + const ReadableByteStreamController: { + prototype: ReadableByteStreamController; + new(): ReadableByteStreamController; + }; + interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(e?: any): void; + } + const ReadableStreamDefaultController: { + prototype: ReadableStreamDefaultController; + new(): ReadableStreamDefaultController; + }; + interface Transformer { + flush?: TransformerFlushCallback; + readableType?: undefined; + start?: TransformerStartCallback; + transform?: TransformerTransformCallback; + writableType?: undefined; + } + interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const TransformStream: { + prototype: TransformStream; + new( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ): TransformStream; + }; + interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk?: O): void; + error(reason?: any): void; + terminate(): void; + } + const TransformStreamDefaultController: { + prototype: TransformStreamDefaultController; + new(): TransformStreamDefaultController; + }; + /** + * This Streams API interface provides a standard abstraction for writing + * streaming data to a destination, known as a sink. This object comes with + * built-in back pressure and queuing. + */ + interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + close(): Promise; + getWriter(): WritableStreamDefaultWriter; + } + const WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; + }; + /** + * This Streams API interface is the object returned by + * WritableStream.getWriter() and once created locks the < writer to the + * WritableStream ensuring that no other streams can write to the underlying + * sink. + */ + interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: W): Promise; + } + const WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(stream: WritableStream): WritableStreamDefaultWriter; + }; + /** + * This Streams API interface represents a controller allowing control of a + * WritableStream's state. When constructing a WritableStream, the + * underlying sink is given a corresponding WritableStreamDefaultController + * instance to manipulate. + */ + interface WritableStreamDefaultController { + error(e?: any): void; + } + const WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; + }; + interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySize; + } + interface QueuingStrategySize { + (chunk?: T): number; + } + interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water + * mark. + * + * Note that the provided high water mark will not be validated ahead of + * time. Instead, if it is negative, NaN, or not a number, the resulting + * ByteLengthQueuingStrategy will cause the corresponding stream + * constructor to throw. + */ + highWaterMark: number; + } + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface ByteLengthQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(init: QueuingStrategyInit): ByteLengthQueuingStrategy; + }; + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface CountQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(init: QueuingStrategyInit): CountQueuingStrategy; + }; + interface TextEncoderStream { + /** Returns "utf-8". */ + readonly encoding: "utf-8"; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextEncoderStream: { + prototype: TextEncoderStream; + new(): TextEncoderStream; + }; + interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + type BufferSource = ArrayBufferView | ArrayBuffer; + interface TextDecoderStream { + /** Returns encoding's name, lower cased. */ + readonly encoding: string; + /** Returns `true` if error mode is "fatal", and `false` otherwise. */ + readonly fatal: boolean; + /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */ + readonly ignoreBOM: boolean; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextDecoderStream: { + prototype: TextDecoderStream; + new(encoding?: string, options?: TextDecoderOptions): TextDecoderStream; + }; + interface CompressionStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const CompressionStream: { + prototype: CompressionStream; + new(format: "deflate" | "deflate-raw" | "gzip"): CompressionStream; + }; + interface DecompressionStream { + readonly writable: WritableStream; + readonly readable: ReadableStream; + } + const DecompressionStream: { + prototype: DecompressionStream; + new(format: "deflate" | "deflate-raw" | "gzip"): DecompressionStream; + }; + + global { + interface ByteLengthQueuingStrategy extends _ByteLengthQueuingStrategy {} + /** + * `ByteLengthQueuingStrategy` class is a global reference for `require('stream/web').ByteLengthQueuingStrategy`. + * https://nodejs.org/api/globals.html#class-bytelengthqueuingstrategy + * @since v18.0.0 + */ + var ByteLengthQueuingStrategy: typeof globalThis extends { onmessage: any; ByteLengthQueuingStrategy: infer T } + ? T + : typeof import("stream/web").ByteLengthQueuingStrategy; + + interface CompressionStream extends _CompressionStream {} + /** + * `CompressionStream` class is a global reference for `require('stream/web').CompressionStream`. + * https://nodejs.org/api/globals.html#class-compressionstream + * @since v18.0.0 + */ + var CompressionStream: typeof globalThis extends { + onmessage: any; + // CompressionStream, DecompressionStream and ReportingObserver was introduced in the same commit. + // If ReportingObserver check is removed, the type here will form a circular reference in TS5.0+lib.dom.d.ts + ReportingObserver: any; + CompressionStream: infer T; + } ? T + // TS 4.8, 4.9, 5.0 + : typeof globalThis extends { onmessage: any; TransformStream: { prototype: infer T } } ? { + prototype: T; + new(format: "deflate" | "deflate-raw" | "gzip"): T; + } + : typeof import("stream/web").CompressionStream; + + interface CountQueuingStrategy extends _CountQueuingStrategy {} + /** + * `CountQueuingStrategy` class is a global reference for `require('stream/web').CountQueuingStrategy`. + * https://nodejs.org/api/globals.html#class-countqueuingstrategy + * @since v18.0.0 + */ + var CountQueuingStrategy: typeof globalThis extends { onmessage: any; CountQueuingStrategy: infer T } ? T + : typeof import("stream/web").CountQueuingStrategy; + + interface DecompressionStream extends _DecompressionStream {} + /** + * `DecompressionStream` class is a global reference for `require('stream/web').DecompressionStream`. + * https://nodejs.org/api/globals.html#class-decompressionstream + * @since v18.0.0 + */ + var DecompressionStream: typeof globalThis extends { + onmessage: any; + // CompressionStream, DecompressionStream and ReportingObserver was introduced in the same commit. + // If ReportingObserver check is removed, the type here will form a circular reference in TS5.0+lib.dom.d.ts + ReportingObserver: any; + DecompressionStream: infer T extends object; + } ? T + // TS 4.8, 4.9, 5.0 + : typeof globalThis extends { onmessage: any; TransformStream: { prototype: infer T } } ? { + prototype: T; + new(format: "deflate" | "deflate-raw" | "gzip"): T; + } + : typeof import("stream/web").DecompressionStream; + + interface ReadableByteStreamController extends _ReadableByteStreamController {} + /** + * `ReadableByteStreamController` class is a global reference for `require('stream/web').ReadableByteStreamController`. + * https://nodejs.org/api/globals.html#class-readablebytestreamcontroller + * @since v18.0.0 + */ + var ReadableByteStreamController: typeof globalThis extends + { onmessage: any; ReadableByteStreamController: infer T } ? T + : typeof import("stream/web").ReadableByteStreamController; + + interface ReadableStream extends _ReadableStream {} + /** + * `ReadableStream` class is a global reference for `require('stream/web').ReadableStream`. + * https://nodejs.org/api/globals.html#class-readablestream + * @since v18.0.0 + */ + var ReadableStream: typeof globalThis extends { onmessage: any; ReadableStream: infer T } ? T + : typeof import("stream/web").ReadableStream; + + interface ReadableStreamBYOBReader extends _ReadableStreamBYOBReader {} + /** + * `ReadableStreamBYOBReader` class is a global reference for `require('stream/web').ReadableStreamBYOBReader`. + * https://nodejs.org/api/globals.html#class-readablestreambyobreader + * @since v18.0.0 + */ + var ReadableStreamBYOBReader: typeof globalThis extends { onmessage: any; ReadableStreamBYOBReader: infer T } + ? T + : typeof import("stream/web").ReadableStreamBYOBReader; + + interface ReadableStreamBYOBRequest extends _ReadableStreamBYOBRequest {} + /** + * `ReadableStreamBYOBRequest` class is a global reference for `require('stream/web').ReadableStreamBYOBRequest`. + * https://nodejs.org/api/globals.html#class-readablestreambyobrequest + * @since v18.0.0 + */ + var ReadableStreamBYOBRequest: typeof globalThis extends { onmessage: any; ReadableStreamBYOBRequest: infer T } + ? T + : typeof import("stream/web").ReadableStreamBYOBRequest; + + interface ReadableStreamDefaultController extends _ReadableStreamDefaultController {} + /** + * `ReadableStreamDefaultController` class is a global reference for `require('stream/web').ReadableStreamDefaultController`. + * https://nodejs.org/api/globals.html#class-readablestreamdefaultcontroller + * @since v18.0.0 + */ + var ReadableStreamDefaultController: typeof globalThis extends + { onmessage: any; ReadableStreamDefaultController: infer T } ? T + : typeof import("stream/web").ReadableStreamDefaultController; + + interface ReadableStreamDefaultReader extends _ReadableStreamDefaultReader {} + /** + * `ReadableStreamDefaultReader` class is a global reference for `require('stream/web').ReadableStreamDefaultReader`. + * https://nodejs.org/api/globals.html#class-readablestreamdefaultreader + * @since v18.0.0 + */ + var ReadableStreamDefaultReader: typeof globalThis extends + { onmessage: any; ReadableStreamDefaultReader: infer T } ? T + : typeof import("stream/web").ReadableStreamDefaultReader; + + interface TextDecoderStream extends _TextDecoderStream {} + /** + * `TextDecoderStream` class is a global reference for `require('stream/web').TextDecoderStream`. + * https://nodejs.org/api/globals.html#class-textdecoderstream + * @since v18.0.0 + */ + var TextDecoderStream: typeof globalThis extends { onmessage: any; TextDecoderStream: infer T } ? T + : typeof import("stream/web").TextDecoderStream; + + interface TextEncoderStream extends _TextEncoderStream {} + /** + * `TextEncoderStream` class is a global reference for `require('stream/web').TextEncoderStream`. + * https://nodejs.org/api/globals.html#class-textencoderstream + * @since v18.0.0 + */ + var TextEncoderStream: typeof globalThis extends { onmessage: any; TextEncoderStream: infer T } ? T + : typeof import("stream/web").TextEncoderStream; + + interface TransformStream extends _TransformStream {} + /** + * `TransformStream` class is a global reference for `require('stream/web').TransformStream`. + * https://nodejs.org/api/globals.html#class-transformstream + * @since v18.0.0 + */ + var TransformStream: typeof globalThis extends { onmessage: any; TransformStream: infer T } ? T + : typeof import("stream/web").TransformStream; + + interface TransformStreamDefaultController extends _TransformStreamDefaultController {} + /** + * `TransformStreamDefaultController` class is a global reference for `require('stream/web').TransformStreamDefaultController`. + * https://nodejs.org/api/globals.html#class-transformstreamdefaultcontroller + * @since v18.0.0 + */ + var TransformStreamDefaultController: typeof globalThis extends + { onmessage: any; TransformStreamDefaultController: infer T } ? T + : typeof import("stream/web").TransformStreamDefaultController; + + interface WritableStream extends _WritableStream {} + /** + * `WritableStream` class is a global reference for `require('stream/web').WritableStream`. + * https://nodejs.org/api/globals.html#class-writablestream + * @since v18.0.0 + */ + var WritableStream: typeof globalThis extends { onmessage: any; WritableStream: infer T } ? T + : typeof import("stream/web").WritableStream; + + interface WritableStreamDefaultController extends _WritableStreamDefaultController {} + /** + * `WritableStreamDefaultController` class is a global reference for `require('stream/web').WritableStreamDefaultController`. + * https://nodejs.org/api/globals.html#class-writablestreamdefaultcontroller + * @since v18.0.0 + */ + var WritableStreamDefaultController: typeof globalThis extends + { onmessage: any; WritableStreamDefaultController: infer T } ? T + : typeof import("stream/web").WritableStreamDefaultController; + + interface WritableStreamDefaultWriter extends _WritableStreamDefaultWriter {} + /** + * `WritableStreamDefaultWriter` class is a global reference for `require('stream/web').WritableStreamDefaultWriter`. + * https://nodejs.org/api/globals.html#class-writablestreamdefaultwriter + * @since v18.0.0 + */ + var WritableStreamDefaultWriter: typeof globalThis extends + { onmessage: any; WritableStreamDefaultWriter: infer T } ? T + : typeof import("stream/web").WritableStreamDefaultWriter; + } +} +declare module "node:stream/web" { + export * from "stream/web"; +} diff --git a/node_modules/@types/node/string_decoder.d.ts b/node_modules/@types/node/string_decoder.d.ts new file mode 100644 index 0000000..31f68ac --- /dev/null +++ b/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `node:string_decoder` module provides an API for decoding `Buffer` objects + * into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 + * characters. It can be accessed using: + * + * ```js + * const { StringDecoder } = require('node:string_decoder'); + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * const { StringDecoder } = require('node:string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); // Prints: ¢ + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); // Prints: € + * ``` + * + * When a `Buffer` instance is written to the `StringDecoder` instance, an + * internal buffer is used to ensure that the decoded string does not contain + * any incomplete multibyte characters. These are held in the buffer until the + * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. + * + * In the following example, the three UTF-8 encoded bytes of the European Euro + * symbol (`€`) are written over three separate operations: + * + * ```js + * const { StringDecoder } = require('node:string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); // Prints: € + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/string_decoder.js) + */ +declare module "string_decoder" { + class StringDecoder { + constructor(encoding?: BufferEncoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at + * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the + * returned string and stored in an internal buffer for the next call to `stringDecoder.write()` or `stringDecoder.end()`. + * @since v0.1.99 + * @param buffer The bytes to decode. + */ + write(buffer: string | Buffer | NodeJS.ArrayBufferView): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes + * representing incomplete UTF-8 and UTF-16 characters will be replaced with + * substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()` is performed before returning the remaining input. + * After `end()` is called, the `stringDecoder` object can be reused for new input. + * @since v0.9.3 + * @param buffer The bytes to decode. + */ + end(buffer?: string | Buffer | NodeJS.ArrayBufferView): string; + } +} +declare module "node:string_decoder" { + export * from "string_decoder"; +} diff --git a/node_modules/@types/node/test.d.ts b/node_modules/@types/node/test.d.ts new file mode 100644 index 0000000..91524dc --- /dev/null +++ b/node_modules/@types/node/test.d.ts @@ -0,0 +1,2015 @@ +/** + * The `node:test` module facilitates the creation of JavaScript tests. + * To access it: + * + * ```js + * import test from 'node:test'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'test'; + * ``` + * + * Tests created via the `test` module consist of a single function that is + * processed in one of three ways: + * + * 1. A synchronous function that is considered failing if it throws an exception, + * and is considered passing otherwise. + * 2. A function that returns a `Promise` that is considered failing if the `Promise` rejects, and is considered passing if the `Promise` fulfills. + * 3. A function that receives a callback function. If the callback receives any + * truthy value as its first argument, the test is considered failing. If a + * falsy value is passed as the first argument to the callback, the test is + * considered passing. If the test function receives a callback function and + * also returns a `Promise`, the test will fail. + * + * The following example illustrates how tests are written using the `test` module. + * + * ```js + * test('synchronous passing test', (t) => { + * // This test passes because it does not throw an exception. + * assert.strictEqual(1, 1); + * }); + * + * test('synchronous failing test', (t) => { + * // This test fails because it throws an exception. + * assert.strictEqual(1, 2); + * }); + * + * test('asynchronous passing test', async (t) => { + * // This test passes because the Promise returned by the async + * // function is settled and not rejected. + * assert.strictEqual(1, 1); + * }); + * + * test('asynchronous failing test', async (t) => { + * // This test fails because the Promise returned by the async + * // function is rejected. + * assert.strictEqual(1, 2); + * }); + * + * test('failing test using Promises', (t) => { + * // Promises can be used directly as well. + * return new Promise((resolve, reject) => { + * setImmediate(() => { + * reject(new Error('this will cause the test to fail')); + * }); + * }); + * }); + * + * test('callback passing test', (t, done) => { + * // done() is the callback function. When the setImmediate() runs, it invokes + * // done() with no arguments. + * setImmediate(done); + * }); + * + * test('callback failing test', (t, done) => { + * // When the setImmediate() runs, done() is invoked with an Error object and + * // the test fails. + * setImmediate(() => { + * done(new Error('callback failure')); + * }); + * }); + * ``` + * + * If any tests fail, the process exit code is set to `1`. + * @since v18.0.0, v16.17.0 + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/test.js) + */ +declare module "node:test" { + import { Readable } from "node:stream"; + /** + * **Note:** `shard` is used to horizontally parallelize test running across + * machines or processes, ideal for large-scale executions across varied + * environments. It's incompatible with `watch` mode, tailored for rapid + * code iteration by automatically rerunning tests on file changes. + * + * ```js + * import { tap } from 'node:test/reporters'; + * import { run } from 'node:test'; + * import process from 'node:process'; + * import path from 'node:path'; + * + * run({ files: [path.resolve('./tests/test.js')] }) + * .compose(tap) + * .pipe(process.stdout); + * ``` + * @since v18.9.0, v16.19.0 + * @param options Configuration options for running tests. + */ + function run(options?: RunOptions): TestsStream; + /** + * The `test()` function is the value imported from the `test` module. Each + * invocation of this function results in reporting the test to the `TestsStream`. + * + * The `TestContext` object passed to the `fn` argument can be used to perform + * actions related to the current test. Examples include skipping the test, adding + * additional diagnostic information, or creating subtests. + * + * `test()` returns a `Promise` that fulfills once the test completes. + * if `test()` is called within a suite, it fulfills immediately. + * The return value can usually be discarded for top level tests. + * However, the return value from subtests should be used to prevent the parent + * test from finishing first and cancelling the subtest + * as shown in the following example. + * + * ```js + * test('top level test', async (t) => { + * // The setTimeout() in the following subtest would cause it to outlive its + * // parent test if 'await' is removed on the next line. Once the parent test + * // completes, it will cancel any outstanding subtests. + * await t.test('longer running subtest', async (t) => { + * return new Promise((resolve, reject) => { + * setTimeout(resolve, 1000); + * }); + * }); + * }); + * ``` + * + * The `timeout` option can be used to fail the test if it takes longer than `timeout` milliseconds to complete. However, it is not a reliable mechanism for + * canceling tests because a running test might block the application thread and + * thus prevent the scheduled cancellation. + * @since v18.0.0, v16.17.0 + * @param name The name of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @return Fulfilled with `undefined` once the test completes, or immediately if the test runs within a suite. + */ + function test(name?: string, fn?: TestFn): Promise; + function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function test(options?: TestOptions, fn?: TestFn): Promise; + function test(fn?: TestFn): Promise; + namespace test { + export { + after, + afterEach, + before, + beforeEach, + describe, + it, + mock, + only, + run, + skip, + snapshot, + suite, + test, + todo, + }; + } + /** + * The `suite()` function is imported from the `node:test` module. + * @param name The name of the suite, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the suite. This supports the same options as {@link test}. + * @param fn The suite function declaring nested tests and suites. The first argument to this function is a {@link SuiteContext} object. + * @return Immediately fulfilled with `undefined`. + * @since v20.13.0 + */ + function suite(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function suite(name?: string, fn?: SuiteFn): Promise; + function suite(options?: TestOptions, fn?: SuiteFn): Promise; + function suite(fn?: SuiteFn): Promise; + namespace suite { + /** + * Shorthand for skipping a suite. This is the same as calling {@link suite} with `options.skip` set to `true`. + * @since v20.13.0 + */ + function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function skip(name?: string, fn?: SuiteFn): Promise; + function skip(options?: TestOptions, fn?: SuiteFn): Promise; + function skip(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `TODO`. This is the same as calling {@link suite} with `options.todo` set to `true`. + * @since v20.13.0 + */ + function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function todo(name?: string, fn?: SuiteFn): Promise; + function todo(options?: TestOptions, fn?: SuiteFn): Promise; + function todo(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `only`. This is the same as calling {@link suite} with `options.only` set to `true`. + * @since v20.13.0 + */ + function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function only(name?: string, fn?: SuiteFn): Promise; + function only(options?: TestOptions, fn?: SuiteFn): Promise; + function only(fn?: SuiteFn): Promise; + } + /** + * Alias for {@link suite}. + * + * The `describe()` function is imported from the `node:test` module. + */ + function describe(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function describe(name?: string, fn?: SuiteFn): Promise; + function describe(options?: TestOptions, fn?: SuiteFn): Promise; + function describe(fn?: SuiteFn): Promise; + namespace describe { + /** + * Shorthand for skipping a suite. This is the same as calling {@link describe} with `options.skip` set to `true`. + * @since v18.15.0 + */ + function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function skip(name?: string, fn?: SuiteFn): Promise; + function skip(options?: TestOptions, fn?: SuiteFn): Promise; + function skip(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `TODO`. This is the same as calling {@link describe} with `options.todo` set to `true`. + * @since v18.15.0 + */ + function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function todo(name?: string, fn?: SuiteFn): Promise; + function todo(options?: TestOptions, fn?: SuiteFn): Promise; + function todo(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `only`. This is the same as calling {@link describe} with `options.only` set to `true`. + * @since v18.15.0 + */ + function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function only(name?: string, fn?: SuiteFn): Promise; + function only(options?: TestOptions, fn?: SuiteFn): Promise; + function only(fn?: SuiteFn): Promise; + } + /** + * Alias for {@link test}. + * + * The `it()` function is imported from the `node:test` module. + * @since v18.6.0, v16.17.0 + */ + function it(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function it(name?: string, fn?: TestFn): Promise; + function it(options?: TestOptions, fn?: TestFn): Promise; + function it(fn?: TestFn): Promise; + namespace it { + /** + * Shorthand for skipping a test. This is the same as calling {@link it} with `options.skip` set to `true`. + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function skip(name?: string, fn?: TestFn): Promise; + function skip(options?: TestOptions, fn?: TestFn): Promise; + function skip(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `TODO`. This is the same as calling {@link it} with `options.todo` set to `true`. + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function todo(name?: string, fn?: TestFn): Promise; + function todo(options?: TestOptions, fn?: TestFn): Promise; + function todo(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `only`. This is the same as calling {@link it} with `options.only` set to `true`. + * @since v18.15.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function only(name?: string, fn?: TestFn): Promise; + function only(options?: TestOptions, fn?: TestFn): Promise; + function only(fn?: TestFn): Promise; + } + /** + * Shorthand for skipping a test. This is the same as calling {@link test} with `options.skip` set to `true`. + * @since v20.2.0 + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function skip(name?: string, fn?: TestFn): Promise; + function skip(options?: TestOptions, fn?: TestFn): Promise; + function skip(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `TODO`. This is the same as calling {@link test} with `options.todo` set to `true`. + * @since v20.2.0 + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function todo(name?: string, fn?: TestFn): Promise; + function todo(options?: TestOptions, fn?: TestFn): Promise; + function todo(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `only`. This is the same as calling {@link test} with `options.only` set to `true`. + * @since v20.2.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function only(name?: string, fn?: TestFn): Promise; + function only(options?: TestOptions, fn?: TestFn): Promise; + function only(fn?: TestFn): Promise; + /** + * The type of a function passed to {@link test}. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + */ + type TestFn = (t: TestContext, done: (result?: any) => void) => void | Promise; + /** + * The type of a suite test function. The argument to this function is a {@link SuiteContext} object. + */ + type SuiteFn = (s: SuiteContext) => void | Promise; + interface TestShard { + /** + * A positive integer between 1 and `total` that specifies the index of the shard to run. + */ + index: number; + /** + * A positive integer that specifies the total number of shards to split the test files to. + */ + total: number; + } + interface RunOptions { + /** + * If a number is provided, then that many test processes would run in parallel, where each process corresponds to one test file. + * If `true`, it would run `os.availableParallelism() - 1` test files in parallel. If `false`, it would only run one test file at a time. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * An array containing the list of files to run. If omitted, files are run according to the + * [test runner execution model](https://nodejs.org/docs/latest-v22.x/api/test.html#test-runner-execution-model). + */ + files?: readonly string[] | undefined; + /** + * Configures the test runner to exit the process once all known + * tests have finished executing even if the event loop would + * otherwise remain active. + * @default false + */ + forceExit?: boolean | undefined; + /** + * Sets inspector port of test child process. + * If a nullish value is provided, each process gets its own port, + * incremented from the primary's `process.debugPort`. + * @default undefined + */ + inspectPort?: number | (() => number) | undefined; + /** + * If truthy, the test context will only run tests that have the `only` option set + */ + only?: boolean | undefined; + /** + * A function that accepts the `TestsStream` instance and can be used to setup listeners before any tests are run. + * @default undefined + */ + setup?: ((reporter: TestsStream) => void | Promise) | undefined; + /** + * Allows aborting an in-progress test execution. + */ + signal?: AbortSignal | undefined; + /** + * If provided, only run tests whose name matches the provided pattern. + * Strings are interpreted as JavaScript regular expressions. + * @default undefined + */ + testNamePatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * A String, RegExp or a RegExp Array, that can be used to exclude running tests whose + * name matches the provided pattern. Test name patterns are interpreted as JavaScript + * regular expressions. For each test that is executed, any corresponding test hooks, + * such as `beforeEach()`, are also run. + * @default undefined + * @since v22.1.0 + */ + testSkipPatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * The number of milliseconds after which the test execution will fail. + * If unspecified, subtests inherit this value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + /** + * Whether to run in watch mode or not. + * @default false + */ + watch?: boolean | undefined; + /** + * Running tests in a specific shard. + * @default undefined + */ + shard?: TestShard | undefined; + } + /** + * A successful call to `run()` will return a new `TestsStream` object, streaming a series of events representing the execution of the tests. + * + * Some of the events are guaranteed to be emitted in the same order as the tests are defined, while others are emitted in the order that the tests execute. + * @since v18.9.0, v16.19.0 + */ + class TestsStream extends Readable implements NodeJS.ReadableStream { + addListener(event: "test:coverage", listener: (data: TestCoverage) => void): this; + addListener(event: "test:complete", listener: (data: TestComplete) => void): this; + addListener(event: "test:dequeue", listener: (data: TestDequeue) => void): this; + addListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + addListener(event: "test:enqueue", listener: (data: TestEnqueue) => void): this; + addListener(event: "test:fail", listener: (data: TestFail) => void): this; + addListener(event: "test:pass", listener: (data: TestPass) => void): this; + addListener(event: "test:plan", listener: (data: TestPlan) => void): this; + addListener(event: "test:start", listener: (data: TestStart) => void): this; + addListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + addListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + addListener(event: "test:watch:drained", listener: () => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + emit(event: "test:coverage", data: TestCoverage): boolean; + emit(event: "test:complete", data: TestComplete): boolean; + emit(event: "test:dequeue", data: TestDequeue): boolean; + emit(event: "test:diagnostic", data: DiagnosticData): boolean; + emit(event: "test:enqueue", data: TestEnqueue): boolean; + emit(event: "test:fail", data: TestFail): boolean; + emit(event: "test:pass", data: TestPass): boolean; + emit(event: "test:plan", data: TestPlan): boolean; + emit(event: "test:start", data: TestStart): boolean; + emit(event: "test:stderr", data: TestStderr): boolean; + emit(event: "test:stdout", data: TestStdout): boolean; + emit(event: "test:watch:drained"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "test:coverage", listener: (data: TestCoverage) => void): this; + on(event: "test:complete", listener: (data: TestComplete) => void): this; + on(event: "test:dequeue", listener: (data: TestDequeue) => void): this; + on(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + on(event: "test:enqueue", listener: (data: TestEnqueue) => void): this; + on(event: "test:fail", listener: (data: TestFail) => void): this; + on(event: "test:pass", listener: (data: TestPass) => void): this; + on(event: "test:plan", listener: (data: TestPlan) => void): this; + on(event: "test:start", listener: (data: TestStart) => void): this; + on(event: "test:stderr", listener: (data: TestStderr) => void): this; + on(event: "test:stdout", listener: (data: TestStdout) => void): this; + on(event: "test:watch:drained", listener: () => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "test:coverage", listener: (data: TestCoverage) => void): this; + once(event: "test:complete", listener: (data: TestComplete) => void): this; + once(event: "test:dequeue", listener: (data: TestDequeue) => void): this; + once(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + once(event: "test:enqueue", listener: (data: TestEnqueue) => void): this; + once(event: "test:fail", listener: (data: TestFail) => void): this; + once(event: "test:pass", listener: (data: TestPass) => void): this; + once(event: "test:plan", listener: (data: TestPlan) => void): this; + once(event: "test:start", listener: (data: TestStart) => void): this; + once(event: "test:stderr", listener: (data: TestStderr) => void): this; + once(event: "test:stdout", listener: (data: TestStdout) => void): this; + once(event: "test:watch:drained", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "test:coverage", listener: (data: TestCoverage) => void): this; + prependListener(event: "test:complete", listener: (data: TestComplete) => void): this; + prependListener(event: "test:dequeue", listener: (data: TestDequeue) => void): this; + prependListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + prependListener(event: "test:enqueue", listener: (data: TestEnqueue) => void): this; + prependListener(event: "test:fail", listener: (data: TestFail) => void): this; + prependListener(event: "test:pass", listener: (data: TestPass) => void): this; + prependListener(event: "test:plan", listener: (data: TestPlan) => void): this; + prependListener(event: "test:start", listener: (data: TestStart) => void): this; + prependListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + prependListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + prependListener(event: "test:watch:drained", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "test:coverage", listener: (data: TestCoverage) => void): this; + prependOnceListener(event: "test:complete", listener: (data: TestComplete) => void): this; + prependOnceListener(event: "test:dequeue", listener: (data: TestDequeue) => void): this; + prependOnceListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + prependOnceListener(event: "test:enqueue", listener: (data: TestEnqueue) => void): this; + prependOnceListener(event: "test:fail", listener: (data: TestFail) => void): this; + prependOnceListener(event: "test:pass", listener: (data: TestPass) => void): this; + prependOnceListener(event: "test:plan", listener: (data: TestPlan) => void): this; + prependOnceListener(event: "test:start", listener: (data: TestStart) => void): this; + prependOnceListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + prependOnceListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + prependOnceListener(event: "test:watch:drained", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + } + /** + * An instance of `TestContext` is passed to each test function in order to + * interact with the test runner. However, the `TestContext` constructor is not + * exposed as part of the API. + * @since v18.0.0, v16.17.0 + */ + class TestContext { + /** + * An object containing assertion methods bound to the test context. + * The top-level functions from the `node:assert` module are exposed here for the purpose of creating test plans. + * @since v22.2.0 + */ + readonly assert: TestContextAssert; + /** + * This function is used to create a hook running before subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v20.1.0, v18.17.0 + */ + before(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running before each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + beforeEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook that runs after the current test finishes. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.13.0 + */ + after(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + afterEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to write diagnostics to the output. Any diagnostic + * information is included at the end of the test's results. This function does + * not return a value. + * + * ```js + * test('top level test', (t) => { + * t.diagnostic('A diagnostic message'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Message to be reported. + */ + diagnostic(message: string): void; + /** + * The name of the test and each of its ancestors, separated by `>`. + * @since v22.3.0 + */ + readonly fullName: string; + /** + * The name of the test. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * Used to set the number of assertions and subtests that are expected to run within the test. + * If the number of assertions and subtests that run does not match the expected count, the test will fail. + * + * To make sure assertions are tracked, the assert functions on `context.assert` must be used, + * instead of importing from the `node:assert` module. + * ```js + * test('top level test', (t) => { + * t.plan(2); + * t.assert.ok('some relevant assertion here'); + * t.test('subtest', () => {}); + * }); + * ``` + * + * When working with asynchronous code, the `plan` function can be used to ensure that the correct number of assertions are run: + * ```js + * test('planning with streams', (t, done) => { + * function* generate() { + * yield 'a'; + * yield 'b'; + * yield 'c'; + * } + * const expected = ['a', 'b', 'c']; + * t.plan(expected.length); + * const stream = Readable.from(generate()); + * stream.on('data', (chunk) => { + * t.assert.strictEqual(chunk, expected.shift()); + * }); + * stream.on('end', () => { + * done(); + * }); + * }); + * ``` + * @since v22.2.0 + */ + plan(count: number): void; + /** + * If `shouldRunOnlyTests` is truthy, the test context will only run tests that + * have the `only` option set. Otherwise, all tests are run. If Node.js was not + * started with the `--test-only` command-line option, this function is a + * no-op. + * + * ```js + * test('top level test', (t) => { + * // The test context can be set to run subtests with the 'only' option. + * t.runOnly(true); + * return Promise.all([ + * t.test('this subtest is now skipped'), + * t.test('this subtest is run', { only: true }), + * ]); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param shouldRunOnlyTests Whether or not to run `only` tests. + */ + runOnly(shouldRunOnlyTests: boolean): void; + /** + * ```js + * test('top level test', async (t) => { + * await fetch('some/uri', { signal: t.signal }); + * }); + * ``` + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + /** + * This function causes the test's output to indicate the test as skipped. If `message` is provided, it is included in the output. Calling `skip()` does + * not terminate execution of the test function. This function does not return a + * value. + * + * ```js + * test('top level test', (t) => { + * // Make sure to return here as well if the test contains additional logic. + * t.skip('this is skipped'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional skip message. + */ + skip(message?: string): void; + /** + * This function adds a `TODO` directive to the test's output. If `message` is + * provided, it is included in the output. Calling `todo()` does not terminate + * execution of the test function. This function does not return a value. + * + * ```js + * test('top level test', (t) => { + * // This test is marked as `TODO` + * t.todo('this is a todo'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional `TODO` message. + */ + todo(message?: string): void; + /** + * This function is used to create subtests under the current test. This function behaves in + * the same fashion as the top level {@link test} function. + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. This first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + test: typeof test; + /** + * Each test provides its own MockTracker instance. + */ + readonly mock: MockTracker; + } + interface TestContextAssert { + /** + * Identical to the `deepEqual` function from the `node:assert` module, but bound to the test context. + */ + deepEqual: typeof import("node:assert").deepEqual; + /** + * Identical to the `deepStrictEqual` function from the `node:assert` module, but bound to the test context. + */ + deepStrictEqual: typeof import("node:assert").deepStrictEqual; + /** + * Identical to the `doesNotMatch` function from the `node:assert` module, but bound to the test context. + */ + doesNotMatch: typeof import("node:assert").doesNotMatch; + /** + * Identical to the `doesNotReject` function from the `node:assert` module, but bound to the test context. + */ + doesNotReject: typeof import("node:assert").doesNotReject; + /** + * Identical to the `doesNotThrow` function from the `node:assert` module, but bound to the test context. + */ + doesNotThrow: typeof import("node:assert").doesNotThrow; + /** + * Identical to the `equal` function from the `node:assert` module, but bound to the test context. + */ + equal: typeof import("node:assert").equal; + /** + * Identical to the `fail` function from the `node:assert` module, but bound to the test context. + */ + fail: typeof import("node:assert").fail; + /** + * Identical to the `ifError` function from the `node:assert` module, but bound to the test context. + */ + ifError: typeof import("node:assert").ifError; + /** + * Identical to the `match` function from the `node:assert` module, but bound to the test context. + */ + match: typeof import("node:assert").match; + /** + * Identical to the `notDeepEqual` function from the `node:assert` module, but bound to the test context. + */ + notDeepEqual: typeof import("node:assert").notDeepEqual; + /** + * Identical to the `notDeepStrictEqual` function from the `node:assert` module, but bound to the test context. + */ + notDeepStrictEqual: typeof import("node:assert").notDeepStrictEqual; + /** + * Identical to the `notEqual` function from the `node:assert` module, but bound to the test context. + */ + notEqual: typeof import("node:assert").notEqual; + /** + * Identical to the `notStrictEqual` function from the `node:assert` module, but bound to the test context. + */ + notStrictEqual: typeof import("node:assert").notStrictEqual; + /** + * Identical to the `ok` function from the `node:assert` module, but bound to the test context. + */ + ok: typeof import("node:assert").ok; + /** + * Identical to the `rejects` function from the `node:assert` module, but bound to the test context. + */ + rejects: typeof import("node:assert").rejects; + /** + * Identical to the `strictEqual` function from the `node:assert` module, but bound to the test context. + */ + strictEqual: typeof import("node:assert").strictEqual; + /** + * Identical to the `throws` function from the `node:assert` module, but bound to the test context. + */ + throws: typeof import("node:assert").throws; + /** + * This function implements assertions for snapshot testing. + * ```js + * test('snapshot test with default serialization', (t) => { + * t.assert.snapshot({ value1: 1, value2: 2 }); + * }); + * + * test('snapshot test with custom serialization', (t) => { + * t.assert.snapshot({ value3: 3, value4: 4 }, { + * serializers: [(value) => JSON.stringify(value)] + * }); + * }); + * ``` + * + * Only available through the [--experimental-test-snapshots](https://nodejs.org/api/cli.html#--experimental-test-snapshots) flag. + * @since v22.3.0 + * @experimental + */ + snapshot(value: any, options?: AssertSnapshotOptions): void; + } + interface AssertSnapshotOptions { + /** + * An array of synchronous functions used to serialize `value` into a string. + * `value` is passed as the only argument to the first serializer function. + * The return value of each serializer is passed as input to the next serializer. + * Once all serializers have run, the resulting value is coerced to a string. + * + * If no serializers are provided, the test runner's default serializers are used. + */ + serializers?: ReadonlyArray<(value: any) => any> | undefined; + } + + /** + * An instance of `SuiteContext` is passed to each suite function in order to + * interact with the test runner. However, the `SuiteContext` constructor is not + * exposed as part of the API. + * @since v18.7.0, v16.17.0 + */ + class SuiteContext { + /** + * The name of the suite. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * Can be used to abort test subtasks when the test has been aborted. + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + } + interface TestOptions { + /** + * If a number is provided, then that many tests would run in parallel. + * If truthy, it would run (number of cpu cores - 1) tests in parallel. + * For subtests, it will be `Infinity` tests in parallel. + * If falsy, it would only run one test at a time. + * If unspecified, subtests inherit this value from their parent. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * If truthy, and the test context is configured to run `only` tests, then this test will be + * run. Otherwise, the test is skipped. + * @default false + */ + only?: boolean | undefined; + /** + * Allows aborting an in-progress test. + * @since v18.8.0 + */ + signal?: AbortSignal | undefined; + /** + * If truthy, the test is skipped. If a string is provided, that string is displayed in the + * test results as the reason for skipping the test. + * @default false + */ + skip?: boolean | string | undefined; + /** + * A number of milliseconds the test will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + * @since v18.7.0 + */ + timeout?: number | undefined; + /** + * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in + * the test results as the reason why the test is `TODO`. + * @default false + */ + todo?: boolean | string | undefined; + /** + * The number of assertions and subtests expected to be run in the test. + * If the number of assertions run in the test does not match the number + * specified in the plan, the test will fail. + * @default undefined + * @since v22.2.0 + */ + plan?: number | undefined; + } + /** + * This function creates a hook that runs before executing a suite. + * + * ```js + * describe('tests', async () => { + * before(() => console.log('about to run some test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function before(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after executing a suite. + * + * ```js + * describe('tests', async () => { + * after(() => console.log('finished running tests')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function after(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs before each test in the current suite. + * + * ```js + * describe('tests', async () => { + * beforeEach(() => console.log('about to run a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function beforeEach(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after each test in the current suite. + * The `afterEach()` hook is run even if the test fails. + * + * ```js + * describe('tests', async () => { + * afterEach(() => console.log('finished running a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function afterEach(fn?: HookFn, options?: HookOptions): void; + /** + * The hook function. The first argument is the context in which the hook is called. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type HookFn = (c: TestContext | SuiteContext, done: (result?: any) => void) => any; + /** + * The hook function. The first argument is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type TestContextHookFn = (t: TestContext, done: (result?: any) => void) => any; + /** + * Configuration options for hooks. + * @since v18.8.0 + */ + interface HookOptions { + /** + * Allows aborting an in-progress hook. + */ + signal?: AbortSignal | undefined; + /** + * A number of milliseconds the hook will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + } + interface MockFunctionOptions { + /** + * The number of times that the mock will use the behavior of `implementation`. + * Once the mock function has been called `times` times, + * it will automatically restore the behavior of `original`. + * This value must be an integer greater than zero. + * @default Infinity + */ + times?: number | undefined; + } + interface MockMethodOptions extends MockFunctionOptions { + /** + * If `true`, `object[methodName]` is treated as a getter. + * This option cannot be used with the `setter` option. + */ + getter?: boolean | undefined; + /** + * If `true`, `object[methodName]` is treated as a setter. + * This option cannot be used with the `getter` option. + */ + setter?: boolean | undefined; + } + type Mock = F & { + mock: MockFunctionContext; + }; + type NoOpFunction = (...args: any[]) => undefined; + type FunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? K : never; + }[keyof T]; + interface MockModuleOptions { + /** + * If false, each call to `require()` or `import()` generates a new mock module. + * If true, subsequent calls will return the same module mock, and the mock module is inserted into the CommonJS cache. + * @default false + */ + cache?: boolean | undefined; + /** + * The value to use as the mocked module's default export. + * + * If this value is not provided, ESM mocks do not include a default export. + * If the mock is a CommonJS or builtin module, this setting is used as the value of `module.exports`. + * If this value is not provided, CJS and builtin mocks use an empty object as the value of `module.exports`. + */ + defaultExport?: any; + /** + * An object whose keys and values are used to create the named exports of the mock module. + * + * If the mock is a CommonJS or builtin module, these values are copied onto `module.exports`. + * Therefore, if a mock is created with both named exports and a non-object default export, + * the mock will throw an exception when used as a CJS or builtin module. + */ + namedExports?: object | undefined; + } + /** + * The `MockTracker` class is used to manage mocking functionality. The test runner + * module provides a top level `mock` export which is a `MockTracker` instance. + * Each test also provides its own `MockTracker` instance via the test context's `mock` property. + * @since v19.1.0, v18.13.0 + */ + class MockTracker { + /** + * This function is used to create a mock function. + * + * The following example creates a mock function that increments a counter by one + * on each invocation. The `times` option is used to modify the mock behavior such + * that the first two invocations add two to the counter instead of one. + * + * ```js + * test('mocks a counting function', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne, addTwo, { times: 2 }); + * + * assert.strictEqual(fn(), 2); + * assert.strictEqual(fn(), 4); + * assert.strictEqual(fn(), 5); + * assert.strictEqual(fn(), 6); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param original An optional function to create a mock on. + * @param implementation An optional function used as the mock implementation for `original`. This is useful for creating mocks that exhibit one behavior for a specified number of calls and + * then restore the behavior of `original`. + * @param options Optional configuration options for the mock function. + * @return The mocked function. The mocked function contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked function. + */ + fn(original?: F, options?: MockFunctionOptions): Mock; + fn( + original?: F, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock; + /** + * This function is used to create a mock on an existing object method. The + * following example demonstrates how a mock is created on an existing object + * method. + * + * ```js + * test('spies on an object method', (t) => { + * const number = { + * value: 5, + * subtract(a) { + * return this.value - a; + * }, + * }; + * + * t.mock.method(number, 'subtract'); + * assert.strictEqual(number.subtract.mock.calls.length, 0); + * assert.strictEqual(number.subtract(3), 2); + * assert.strictEqual(number.subtract.mock.calls.length, 1); + * + * const call = number.subtract.mock.calls[0]; + * + * assert.deepStrictEqual(call.arguments, [3]); + * assert.strictEqual(call.result, 2); + * assert.strictEqual(call.error, undefined); + * assert.strictEqual(call.target, undefined); + * assert.strictEqual(call.this, number); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param object The object whose method is being mocked. + * @param methodName The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown. + * @param implementation An optional function used as the mock implementation for `object[methodName]`. + * @param options Optional configuration options for the mock method. + * @return The mocked method. The mocked method contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked method. + */ + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation: Implementation, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method( + object: MockedObject, + methodName: keyof MockedObject, + options: MockMethodOptions, + ): Mock; + method( + object: MockedObject, + methodName: keyof MockedObject, + implementation: Function, + options: MockMethodOptions, + ): Mock; + + /** + * This function is syntax sugar for `MockTracker.method` with `options.getter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<() => MockedObject[MethodName]>; + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<(() => MockedObject[MethodName]) | Implementation>; + /** + * This function is syntax sugar for `MockTracker.method` with `options.setter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<(value: MockedObject[MethodName]) => void>; + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<((value: MockedObject[MethodName]) => void) | Implementation>; + + /** + * This function is used to mock the exports of ECMAScript modules, CommonJS modules, and Node.js builtin modules. + * Any references to the original module prior to mocking are not impacted. + * + * Only available through the [--experimental-test-module-mocks](https://nodejs.org/api/cli.html#--experimental-test-module-mocks) flag. + * @since v22.3.0 + * @experimental + * @param specifier A string identifying the module to mock. + * @param options Optional configuration options for the mock module. + */ + module(specifier: string, options?: MockModuleOptions): MockModuleContext; + + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker` and disassociates the mocks from the `MockTracker` instance. Once disassociated, the mocks can still be used, but the `MockTracker` instance can no longer be + * used to reset their behavior or + * otherwise interact with them. + * + * After each test completes, this function is called on the test context's `MockTracker`. If the global `MockTracker` is used extensively, calling this + * function manually is recommended. + * @since v19.1.0, v18.13.0 + */ + reset(): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does + * not disassociate the mocks from the `MockTracker` instance. + * @since v19.1.0, v18.13.0 + */ + restoreAll(): void; + + timers: MockTimers; + } + const mock: MockTracker; + interface MockFunctionCall< + F extends Function, + ReturnType = F extends (...args: any) => infer T ? T + : F extends abstract new(...args: any) => infer T ? T + : unknown, + Args = F extends (...args: infer Y) => any ? Y + : F extends abstract new(...args: infer Y) => any ? Y + : unknown[], + > { + /** + * An array of the arguments passed to the mock function. + */ + arguments: Args; + /** + * If the mocked function threw then this property contains the thrown value. + */ + error: unknown | undefined; + /** + * The value returned by the mocked function. + * + * If the mocked function threw, it will be `undefined`. + */ + result: ReturnType | undefined; + /** + * An `Error` object whose stack can be used to determine the callsite of the mocked function invocation. + */ + stack: Error; + /** + * If the mocked function is a constructor, this field contains the class being constructed. + * Otherwise this will be `undefined`. + */ + target: F extends abstract new(...args: any) => any ? F : undefined; + /** + * The mocked function's `this` value. + */ + this: unknown; + } + /** + * The `MockFunctionContext` class is used to inspect or manipulate the behavior of + * mocks created via the `MockTracker` APIs. + * @since v19.1.0, v18.13.0 + */ + class MockFunctionContext { + /** + * A getter that returns a copy of the internal array used to track calls to the + * mock. Each entry in the array is an object with the following properties. + * @since v19.1.0, v18.13.0 + */ + readonly calls: Array>; + /** + * This function returns the number of times that this mock has been invoked. This + * function is more efficient than checking `ctx.calls.length` because `ctx.calls` is a getter that creates a copy of the internal call tracking array. + * @since v19.1.0, v18.13.0 + * @return The number of times that this mock has been invoked. + */ + callCount(): number; + /** + * This function is used to change the behavior of an existing mock. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, and then changes the mock implementation to a different function. + * + * ```js + * test('changes a mock behavior', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementation(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 5); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's new implementation. + */ + mockImplementation(implementation: F): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onCall` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, changes the mock implementation to a different function for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementationOnce(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 4); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's implementation for the invocation number specified by `onCall`. + * @param onCall The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown. + */ + mockImplementationOnce(implementation: F, onCall?: number): void; + /** + * Resets the call history of the mock function. + * @since v19.3.0, v18.13.0 + */ + resetCalls(): void; + /** + * Resets the implementation of the mock function to its original behavior. The + * mock can still be used after calling this function. + * @since v19.1.0, v18.13.0 + */ + restore(): void; + } + /** + * @since v22.3.0 + * @experimental + */ + class MockModuleContext { + /** + * Resets the implementation of the mock module. + * @since v22.3.0 + */ + restore(): void; + } + + type Timer = "setInterval" | "setTimeout" | "setImmediate" | "Date"; + interface MockTimersOptions { + apis: Timer[]; + now?: number | Date | undefined; + } + /** + * Mocking timers is a technique commonly used in software testing to simulate and + * control the behavior of timers, such as `setInterval` and `setTimeout`, + * without actually waiting for the specified time intervals. + * + * The MockTimers API also allows for mocking of the `Date` constructor and + * `setImmediate`/`clearImmediate` functions. + * + * The `MockTracker` provides a top-level `timers` export + * which is a `MockTimers` instance. + * @since v20.4.0 + * @experimental + */ + class MockTimers { + /** + * Enables timer mocking for the specified timers. + * + * **Note:** When you enable mocking for a specific timer, its associated + * clear function will also be implicitly mocked. + * + * **Note:** Mocking `Date` will affect the behavior of the mocked timers + * as they use the same internal clock. + * + * Example usage without setting initial time: + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1234 }); + * ``` + * + * The above example enables mocking for the `Date` constructor, `setInterval` timer and + * implicitly mocks the `clearInterval` function. Only the `Date` constructor from `globalThis`, + * `setInterval` and `clearInterval` functions from `node:timers`, `node:timers/promises`, and `globalThis` will be mocked. + * + * Example usage with initial time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: 1000 }); + * ``` + * + * Example usage with initial Date object as time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: new Date() }); + * ``` + * + * Alternatively, if you call `mock.timers.enable()` without any parameters: + * + * All timers (`'setInterval'`, `'clearInterval'`, `'Date'`, `'setImmediate'`, `'clearImmediate'`, `'setTimeout'`, and `'clearTimeout'`) + * will be mocked. + * + * The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout` functions from `node:timers`, `node:timers/promises`, + * and `globalThis` will be mocked. + * The `Date` constructor from `globalThis` will be mocked. + * + * If there is no initial epoch set, the initial date will be based on 0 in the Unix epoch. This is `January 1st, 1970, 00:00:00 UTC`. You can + * set an initial date by passing a now property to the `.enable()` method. This value will be used as the initial date for the mocked Date + * object. It can either be a positive integer, or another Date object. + * @since v20.4.0 + */ + enable(options?: MockTimersOptions): void; + /** + * You can use the `.setTime()` method to manually move the mocked date to another time. This method only accepts a positive integer. + * Note: This method will execute any mocked timers that are in the past from the new time. + * In the below example we are setting a new time for the mocked date. + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * test('sets the time of a date object', (context) => { + * // Optionally choose what to mock + * context.mock.timers.enable({ apis: ['Date'], now: 100 }); + * assert.strictEqual(Date.now(), 100); + * // Advance in time will also advance the date + * context.mock.timers.setTime(1000); + * context.mock.timers.tick(200); + * assert.strictEqual(Date.now(), 1200); + * }); + * ``` + */ + setTime(time: number): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTimers` instance and disassociates the mocks + * from the `MockTracker` instance. + * + * **Note:** After each test completes, this function is called on + * the test context's `MockTracker`. + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.reset(); + * ``` + * @since v20.4.0 + */ + reset(): void; + /** + * Advances time for all mocked timers. + * + * **Note:** This diverges from how `setTimeout` in Node.js behaves and accepts + * only positive numbers. In Node.js, `setTimeout` with negative numbers is + * only supported for web compatibility reasons. + * + * The following example mocks a `setTimeout` function and + * by using `.tick` advances in + * time triggering all pending timers. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Alternativelly, the `.tick` function can be called many times + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * const nineSecs = 9000; + * setTimeout(fn, nineSecs); + * + * const twoSeconds = 3000; + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Advancing time using `.tick` will also advance the time for any `Date` object + * created after the mock was enabled (if `Date` was also set to be mocked). + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * assert.strictEqual(Date.now(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * assert.strictEqual(fn.mock.callCount(), 1); + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * @since v20.4.0 + */ + tick(milliseconds: number): void; + /** + * Triggers all pending mocked timers immediately. If the `Date` object is also + * mocked, it will also advance the `Date` object to the furthest timer's time. + * + * The example below triggers all pending timers immediately, + * causing them to execute without any delay. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('runAll functions following the given order', (context) => { + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * const results = []; + * setTimeout(() => results.push(1), 9999); + * + * // Notice that if both timers have the same timeout, + * // the order of execution is guaranteed + * setTimeout(() => results.push(3), 8888); + * setTimeout(() => results.push(2), 8888); + * + * assert.deepStrictEqual(results, []); + * + * context.mock.timers.runAll(); + * assert.deepStrictEqual(results, [3, 2, 1]); + * // The Date object is also advanced to the furthest timer's time + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * + * **Note:** The `runAll()` function is specifically designed for + * triggering timers in the context of timer mocking. + * It does not have any effect on real-time system + * clocks or actual timers outside of the mocking environment. + * @since v20.4.0 + */ + runAll(): void; + /** + * Calls {@link MockTimers.reset()}. + */ + [Symbol.dispose](): void; + } + /** + * Only available through the [--experimental-test-snapshots](https://nodejs.org/api/cli.html#--experimental-test-snapshots) flag. + * @since v22.3.0 + * @experimental + */ + namespace snapshot { + /** + * This function is used to customize the default serialization mechanism used by the test runner. + * + * By default, the test runner performs serialization by calling `JSON.stringify(value, null, 2)` on the provided value. + * `JSON.stringify()` does have limitations regarding circular structures and supported data types. + * If a more robust serialization mechanism is required, this function should be used to specify a list of custom serializers. + * + * Serializers are called in order, with the output of the previous serializer passed as input to the next. + * The final result must be a string value. + * @since v22.3.0 + * @param serializers An array of synchronous functions used as the default serializers for snapshot tests. + */ + function setDefaultSnapshotSerializers(serializers: ReadonlyArray<(value: any) => any>): void; + /** + * This function is used to set a custom resolver for the location of the snapshot file used for snapshot testing. + * By default, the snapshot filename is the same as the entry point filename with `.snapshot` appended. + * @since v22.3.0 + * @param fn A function which returns a string specifying the location of the snapshot file. + * The function receives the path of the test file as its only argument. + * If `process.argv[1]` is not associated with a file (for example in the REPL), the input is undefined. + */ + function setResolveSnapshotPath(fn: (path: string | undefined) => string): void; + } + export { + after, + afterEach, + before, + beforeEach, + describe, + it, + Mock, + mock, + only, + run, + skip, + snapshot, + suite, + SuiteContext, + test, + test as default, + TestContext, + todo, + }; +} + +interface TestError extends Error { + cause: Error; +} +interface TestLocationInfo { + /** + * The column number where the test is defined, or + * `undefined` if the test was run through the REPL. + */ + column?: number; + /** + * The path of the test file, `undefined` if test was run through the REPL. + */ + file?: string; + /** + * The line number where the test is defined, or `undefined` if the test was run through the REPL. + */ + line?: number; +} +interface DiagnosticData extends TestLocationInfo { + /** + * The diagnostic message. + */ + message: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestCoverage { + /** + * An object containing the coverage report. + */ + summary: { + /** + * An array of coverage reports for individual files. + */ + files: Array<{ + /** + * The absolute path of the file. + */ + path: string; + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + /** + * An array of functions representing function coverage. + */ + functions: Array<{ + /** + * The name of the function. + */ + name: string; + /** + * The line number where the function is defined. + */ + line: number; + /** + * The number of times the function was called. + */ + count: number; + }>; + /** + * An array of branches representing branch coverage. + */ + branches: Array<{ + /** + * The line number where the branch is defined. + */ + line: number; + /** + * The number of times the branch was taken. + */ + count: number; + }>; + /** + * An array of lines representing line numbers and the number of times they were covered. + */ + lines: Array<{ + /** + * The line number. + */ + line: number; + /** + * The number of times the line was covered. + */ + count: number; + }>; + }>; + /** + * An object containing a summary of coverage for all files. + */ + totals: { + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + }; + /** + * The working directory when code coverage began. This + * is useful for displaying relative path names in case + * the tests changed the working directory of the Node.js process. + */ + workingDirectory: string; + }; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestComplete extends TestLocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * Whether the test passed or not. + */ + passed: boolean; + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test if it did not pass. + */ + error?: TestError; + /** + * The type of the test, used to denote whether this is a suite. + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; +} +interface TestDequeue extends TestLocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestEnqueue extends TestLocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestFail extends TestLocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test. + */ + error: TestError; + /** + * The type of the test, used to denote whether this is a suite. + * @since v20.0.0, v19.9.0, v18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; +} +interface TestPass extends TestLocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * The type of the test, used to denote whether this is a suite. + * @since 20.0.0, 19.9.0, 18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; +} +interface TestPlan extends TestLocationInfo { + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The number of subtests that have ran. + */ + count: number; +} +interface TestStart extends TestLocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestStderr { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stderr`. + */ + message: string; +} +interface TestStdout { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stdout`. + */ + message: string; +} + +/** + * The `node:test/reporters` module exposes the builtin-reporters for `node:test`. + * To access it: + * + * ```js + * import test from 'node:test/reporters'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'test/reporters'; + * ``` + * @since v19.9.0 + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/test/reporters.js) + */ +declare module "node:test/reporters" { + import { Transform, TransformOptions } from "node:stream"; + + type TestEvent = + | { type: "test:coverage"; data: TestCoverage } + | { type: "test:complete"; data: TestComplete } + | { type: "test:dequeue"; data: TestDequeue } + | { type: "test:diagnostic"; data: DiagnosticData } + | { type: "test:enqueue"; data: TestEnqueue } + | { type: "test:fail"; data: TestFail } + | { type: "test:pass"; data: TestPass } + | { type: "test:plan"; data: TestPlan } + | { type: "test:start"; data: TestStart } + | { type: "test:stderr"; data: TestStderr } + | { type: "test:stdout"; data: TestStdout } + | { type: "test:watch:drained"; data: undefined }; + type TestEventGenerator = AsyncGenerator; + + interface ReporterConstructorWrapper Transform> { + new(...args: ConstructorParameters): InstanceType; + (...args: ConstructorParameters): InstanceType; + } + + /** + * The `dot` reporter outputs the test results in a compact format, + * where each passing test is represented by a `.`, + * and each failing test is represented by a `X`. + * @since v20.0.0 + */ + function dot(source: TestEventGenerator): AsyncGenerator<"\n" | "." | "X", void>; + /** + * The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format. + * @since v20.0.0 + */ + function tap(source: TestEventGenerator): AsyncGenerator; + class SpecReporter extends Transform { + constructor(); + } + /** + * The `spec` reporter outputs the test results in a human-readable format. + * @since v20.0.0 + */ + const spec: ReporterConstructorWrapper; + /** + * The `junit` reporter outputs test results in a jUnit XML format. + * @since v21.0.0 + */ + function junit(source: TestEventGenerator): AsyncGenerator; + class LcovReporter extends Transform { + constructor(opts?: Omit); + } + /** + * The `lcov` reporter outputs test coverage when used with the + * [`--experimental-test-coverage`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--experimental-test-coverage) flag. + * @since v22.0.0 + */ + // TODO: change the export to a wrapper function once node@0db38f0 is merged (breaking change) + // const lcov: ReporterConstructorWrapper; + const lcov: LcovReporter; + + export { dot, junit, lcov, spec, tap, TestEvent }; +} diff --git a/node_modules/@types/node/timers.d.ts b/node_modules/@types/node/timers.d.ts new file mode 100644 index 0000000..624f962 --- /dev/null +++ b/node_modules/@types/node/timers.d.ts @@ -0,0 +1,240 @@ +/** + * The `timer` module exposes a global API for scheduling functions to + * be called at some future period of time. Because the timer functions are + * globals, there is no need to call `require('node:timers')` to use the API. + * + * The timer functions within Node.js implement a similar API as the timers API + * provided by Web Browsers but use a different internal implementation that is + * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/timers.js) + */ +declare module "timers" { + import { Abortable } from "node:events"; + import { + setImmediate as setImmediatePromise, + setInterval as setIntervalPromise, + setTimeout as setTimeoutPromise, + } from "node:timers/promises"; + interface TimerOptions extends Abortable { + /** + * Set to `false` to indicate that the scheduled `Timeout` + * should not require the Node.js event loop to remain active. + * @default true + */ + ref?: boolean | undefined; + } + let setTimeout: typeof global.setTimeout; + let clearTimeout: typeof global.clearTimeout; + let setInterval: typeof global.setInterval; + let clearInterval: typeof global.clearInterval; + let setImmediate: typeof global.setImmediate; + let clearImmediate: typeof global.clearImmediate; + global { + namespace NodeJS { + // compatibility with older typings + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + /** + * This object is created internally and is returned from `setImmediate()`. It + * can be passed to `clearImmediate()` in order to cancel the scheduled + * actions. + * + * By default, when an immediate is scheduled, the Node.js event loop will continue + * running as long as the immediate is active. The `Immediate` object returned by `setImmediate()` exports both `immediate.ref()` and `immediate.unref()` functions that can be used to + * control this default behavior. + */ + class Immediate implements RefCounted { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `Immediate` is active. Calling `immediate.ref()` multiple times will have no + * effect. + * + * By default, all `Immediate` objects are "ref'ed", making it normally unnecessary + * to call `immediate.ref()` unless `immediate.unref()` had been called previously. + * @since v9.7.0 + * @return a reference to `immediate` + */ + ref(): this; + /** + * When called, the active `Immediate` object will not require the Node.js event + * loop to remain active. If there is no other activity keeping the event loop + * running, the process may exit before the `Immediate` object's callback is + * invoked. Calling `immediate.unref()` multiple times will have no effect. + * @since v9.7.0 + * @return a reference to `immediate` + */ + unref(): this; + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + _onImmediate: Function; // to distinguish it from the Timeout class + /** + * Cancels the immediate. This is similar to calling `clearImmediate()`. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + } + /** + * This object is created internally and is returned from `setTimeout()` and `setInterval()`. It can be passed to either `clearTimeout()` or `clearInterval()` in order to cancel the + * scheduled actions. + * + * By default, when a timer is scheduled using either `setTimeout()` or `setInterval()`, the Node.js event loop will continue running as long as the + * timer is active. Each of the `Timeout` objects returned by these functions + * export both `timeout.ref()` and `timeout.unref()` functions that can be used to + * control this default behavior. + */ + class Timeout implements Timer { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the`Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. + * + * By default, all `Timeout` objects are "ref'ed", making it normally unnecessary + * to call `timeout.ref()` unless `timeout.unref()` had been called previously. + * @since v0.9.1 + * @return a reference to `timeout` + */ + ref(): this; + /** + * When called, the active `Timeout` object will not require the Node.js event loop + * to remain active. If there is no other activity keeping the event loop running, + * the process may exit before the `Timeout` object's callback is invoked. Calling `timeout.unref()` multiple times will have no effect. + * @since v0.9.1 + * @return a reference to `timeout` + */ + unref(): this; + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * Sets the timer's start time to the current time, and reschedules the timer to + * call its callback at the previously specified duration adjusted to the current + * time. This is useful for refreshing a timer without allocating a new + * JavaScript object. + * + * Using this on a timer that has already called its callback will reactivate the + * timer. + * @since v10.2.0 + * @return a reference to `timeout` + */ + refresh(): this; + [Symbol.toPrimitive](): number; + /** + * Cancels the timeout. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + } + } + /** + * Schedules execution of a one-time `callback` after `delay` milliseconds. + * + * The `callback` will likely not be invoked in precisely `delay` milliseconds. + * Node.js makes no guarantees about the exact timing of when callbacks will fire, + * nor of their ordering. The callback will be called as close as possible to the + * time specified. + * + * When `delay` is larger than `2147483647` or less than `1`, the `delay` will be set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setTimeout()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param [delay=1] The number of milliseconds to wait before calling the `callback`. + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearTimeout} + */ + function setTimeout( + callback: (...args: TArgs) => void, + ms?: number, + ...args: TArgs + ): NodeJS.Timeout; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setTimeout(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setTimeout { + const __promisify__: typeof setTimeoutPromise; + } + /** + * Cancels a `Timeout` object created by `setTimeout()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by {@link setTimeout} or the `primitive` of the `Timeout` object as a string or a number. + */ + function clearTimeout(timeoutId: NodeJS.Timeout | string | number | undefined): void; + /** + * Schedules repeated execution of `callback` every `delay` milliseconds. + * + * When `delay` is larger than `2147483647` or less than `1`, the `delay` will be + * set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setInterval()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param [delay=1] The number of milliseconds to wait before calling the `callback`. + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearInterval} + */ + function setInterval( + callback: (...args: TArgs) => void, + ms?: number, + ...args: TArgs + ): NodeJS.Timeout; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setInterval(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setInterval { + const __promisify__: typeof setIntervalPromise; + } + /** + * Cancels a `Timeout` object created by `setInterval()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by {@link setInterval} or the `primitive` of the `Timeout` object as a string or a number. + */ + function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void; + /** + * Schedules the "immediate" execution of the `callback` after I/O events' + * callbacks. + * + * When multiple calls to `setImmediate()` are made, the `callback` functions are + * queued for execution in the order in which they are created. The entire callback + * queue is processed every event loop iteration. If an immediate timer is queued + * from inside an executing callback, that timer will not be triggered until the + * next event loop iteration. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setImmediate()`. + * @since v0.9.1 + * @param callback The function to call at the end of this turn of the Node.js `Event Loop` + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearImmediate} + */ + function setImmediate( + callback: (...args: TArgs) => void, + ...args: TArgs + ): NodeJS.Immediate; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setImmediate(callback: (args: void) => void): NodeJS.Immediate; + namespace setImmediate { + const __promisify__: typeof setImmediatePromise; + } + /** + * Cancels an `Immediate` object created by `setImmediate()`. + * @since v0.9.1 + * @param immediate An `Immediate` object as returned by {@link setImmediate}. + */ + function clearImmediate(immediateId: NodeJS.Immediate | undefined): void; + function queueMicrotask(callback: () => void): void; + } +} +declare module "node:timers" { + export * from "timers"; +} diff --git a/node_modules/@types/node/timers/promises.d.ts b/node_modules/@types/node/timers/promises.d.ts new file mode 100644 index 0000000..50cee98 --- /dev/null +++ b/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,97 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via `require('node:timers/promises')`. + * + * ```js + * import { + * setTimeout, + * setImmediate, + * setInterval, + * } from 'timers/promises'; + * ``` + * @since v15.0.0 + */ +declare module "timers/promises" { + import { TimerOptions } from "node:timers"; + /** + * ```js + * import { + * setTimeout, + * } from 'timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from 'timers/promises'; + * + * const res = await setImmediate('result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param value A value with which the promise is fulfilled. + */ + function setImmediate(value?: T, options?: TimerOptions): Promise; + /** + * Returns an async iterator that generates values in an interval of `delay` ms. + * If `ref` is `true`, you need to call `next()` of async iterator explicitly + * or implicitly to keep the event loop alive. + * + * ```js + * import { + * setInterval, + * } from 'timers/promises'; + * + * const interval = 100; + * for await (const startTime of setInterval(interval, Date.now())) { + * const now = Date.now(); + * console.log(now); + * if ((now - startTime) > 1000) + * break; + * } + * console.log(Date.now()); + * ``` + * @since v15.9.0 + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): AsyncIterable; + interface Scheduler { + /** + * An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification being developed as a standard Web Platform API. + * + * Calling `timersPromises.scheduler.wait(delay, options)` is roughly equivalent to calling `timersPromises.setTimeout(delay, undefined, options)` except that the `ref` + * option is not supported. + * + * ```js + * import { scheduler } from 'node:timers/promises'; + * + * await scheduler.wait(1000); // Wait one second before continuing + * ``` + * @since v16.14.0 + * @experimental + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + */ + wait: (delay?: number, options?: Pick) => Promise; + /** + * An experimental API defined by the [Scheduling APIs](https://nodejs.org/docs/latest-v20.x/api/async_hooks.html#promise-execution-tracking) draft specification + * being developed as a standard Web Platform API. + * Calling `timersPromises.scheduler.yield()` is equivalent to calling `timersPromises.setImmediate()` with no arguments. + * @since v16.14.0 + * @experimental + */ + yield: () => Promise; + } + const scheduler: Scheduler; +} +declare module "node:timers/promises" { + export * from "timers/promises"; +} diff --git a/node_modules/@types/node/tls.d.ts b/node_modules/@types/node/tls.d.ts new file mode 100644 index 0000000..a409856 --- /dev/null +++ b/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1220 @@ +/** + * The `node:tls` module provides an implementation of the Transport Layer Security + * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. + * The module can be accessed using: + * + * ```js + * const tls = require('node:tls'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/tls.js) + */ +declare module "tls" { + import { X509Certificate } from "node:crypto"; + import * as net from "node:net"; + import * as stream from "stream"; + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + interface PeerCertificate { + /** + * `true` if a Certificate Authority (CA), `false` otherwise. + * @since v18.13.0 + */ + ca: boolean; + /** + * The DER encoded X.509 certificate data. + */ + raw: Buffer; + /** + * The certificate subject. + */ + subject: Certificate; + /** + * The certificate issuer, described in the same terms as the `subject`. + */ + issuer: Certificate; + /** + * The date-time the certificate is valid from. + */ + valid_from: string; + /** + * The date-time the certificate is valid to. + */ + valid_to: string; + /** + * The certificate serial number, as a hex string. + */ + serialNumber: string; + /** + * The SHA-1 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint: string; + /** + * The SHA-256 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint256: string; + /** + * The SHA-512 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint512: string; + /** + * The extended key usage, a set of OIDs. + */ + ext_key_usage?: string[]; + /** + * A string containing concatenated names for the subject, + * an alternative to the `subject` names. + */ + subjectaltname?: string; + /** + * An array describing the AuthorityInfoAccess, used with OCSP. + */ + infoAccess?: NodeJS.Dict; + /** + * For RSA keys: The RSA bit size. + * + * For EC keys: The key size in bits. + */ + bits?: number; + /** + * The RSA exponent, as a string in hexadecimal number notation. + */ + exponent?: string; + /** + * The RSA modulus, as a hexadecimal string. + */ + modulus?: string; + /** + * The public key. + */ + pubkey?: Buffer; + /** + * The ASN.1 name of the OID of the elliptic curve. + * Well-known curves are identified by an OID. + * While it is unusual, it is possible that the curve + * is identified by its mathematical properties, + * in which case it will not have an OID. + */ + asn1Curve?: string; + /** + * The NIST name for the elliptic curve, if it has one + * (not all well-known curves have been assigned names by NIST). + */ + nistCurve?: string; + } + interface DetailedPeerCertificate extends PeerCertificate { + /** + * The issuer certificate object. + * For self-signed certificates, this may be a circular reference. + */ + issuerCertificate: DetailedPeerCertificate; + } + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + /** + * IETF name for the cipher suite. + */ + standardName: string; + } + interface EphemeralKeyInfo { + /** + * The supported types are 'DH' and 'ECDH'. + */ + type: string; + /** + * The name property is available only when type is 'ECDH'. + */ + name?: string | undefined; + /** + * The size of parameter of an ephemeral key exchange. + */ + size: number; + } + interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean | undefined; + /** + * An optional net.Server instance. + */ + server?: net.Server | undefined; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer | undefined; + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean | undefined; + } + /** + * Performs transparent encryption of written data and all required TLS + * negotiation. + * + * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. + * + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the + * connection is open. + * @since v0.11.4 + */ + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket | stream.Duplex, options?: TLSSocketOptions); + /** + * This property is `true` if the peer certificate was signed by one of the CAs + * specified when creating the `tls.TLSSocket` instance, otherwise `false`. + * @since v0.11.4 + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This + * property is set only when `tlsSocket.authorized === false`. + * @since v0.11.4 + */ + authorizationError: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. + * @since v0.11.4 + */ + encrypted: true; + /** + * String containing the selected ALPN protocol. + * Before a handshake has completed, this value is always null. + * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol: string | false | null; + /** + * Returns an object representing the local certificate. The returned object has + * some properties corresponding to the fields of the certificate. + * + * See {@link TLSSocket.getPeerCertificate} for an example of the certificate + * structure. + * + * If there is no local certificate, an empty object will be returned. If the + * socket has been destroyed, `null` will be returned. + * @since v11.2.0 + */ + getCertificate(): PeerCertificate | object | null; + /** + * Returns an object containing information on the negotiated cipher suite. + * + * For example, a TLSv1.2 protocol with AES256-SHA cipher: + * + * ```json + * { + * "name": "AES256-SHA", + * "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", + * "version": "SSLv3" + * } + * ``` + * + * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. + * @since v0.11.4 + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the type, name, and size of parameter of + * an ephemeral key exchange in `perfect forward secrecy` on a client + * connection. It returns an empty object when the key exchange is not + * ephemeral. As this is only supported on a client socket; `null` is returned + * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The `name` property is available only when type is `'ECDH'`. + * + * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. + * @since v5.0.0 + */ + getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. + */ + getFinished(): Buffer | undefined; + /** + * Returns an object representing the peer's certificate. If the peer does not + * provide a certificate, an empty object will be returned. If the socket has been + * destroyed, `null` will be returned. + * + * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's + * certificate. + * @since v0.11.4 + * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. + * @return A certificate object. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so + * far. + */ + getPeerFinished(): Buffer | undefined; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the + * current connection. The value `'unknown'` will be returned for connected + * sockets that have not completed the handshaking process. The value `null` will + * be returned for server sockets or disconnected client sockets. + * + * Protocol versions are: + * + * * `'SSLv3'` + * * `'TLSv1'` + * * `'TLSv1.1'` + * * `'TLSv1.2'` + * * `'TLSv1.3'` + * + * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. + * @since v5.7.0 + */ + getProtocol(): string | null; + /** + * Returns the TLS session data or `undefined` if no session was + * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful + * for debugging. + * + * See `Session Resumption` for more information. + * + * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications + * must use the `'session'` event (it also works for TLSv1.2 and below). + * @since v0.11.4 + */ + getSession(): Buffer | undefined; + /** + * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. + * @since v12.11.0 + * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. + */ + getSharedSigalgs(): string[]; + /** + * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. + * + * It may be useful for debugging. + * + * See `Session Resumption` for more information. + * @since v0.11.4 + */ + getTLSTicket(): Buffer | undefined; + /** + * See `Session Resumption` for more information. + * @since v0.5.6 + * @return `true` if the session was reused, `false` otherwise. + */ + isSessionReused(): boolean; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * Upon completion, the `callback` function will be passed a single argument + * that is either an `Error` (if the request failed) or `null`. + * + * This method can be used to request a peer's certificate after the secure + * connection has been established. + * + * When running as the server, the socket will be destroyed with an error after `handshakeTimeout` timeout. + * + * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the + * protocol. + * @since v0.11.8 + * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with + * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. + * @return `true` if renegotiation was initiated, `false` otherwise. + */ + renegotiate( + options: { + rejectUnauthorized?: boolean | undefined; + requestCert?: boolean | undefined; + }, + callback: (err: Error | null) => void, + ): undefined | boolean; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. + * Returns `true` if setting the limit succeeded; `false` otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger + * fragments are buffered by the TLS layer until the entire fragment is received + * and its integrity is verified; large fragments can span multiple roundtrips + * and their processing can be delayed due to packet loss or reordering. However, + * smaller fragments add extra TLS framing bytes and CPU overhead, which may + * decrease overall server throughput. + * @since v0.11.11 + * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + /** + * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts + * to renegotiate will trigger an `'error'` event on the `TLSSocket`. + * @since v8.4.0 + */ + disableRenegotiation(): void; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * + * The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by + * OpenSSL's `SSL_trace()` function, the format is undocumented, can change + * without notice, and should not be relied on. + * @since v12.2.0 + */ + enableTrace(): void; + /** + * Returns the peer certificate as an `X509Certificate` object. + * + * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getPeerX509Certificate(): X509Certificate | undefined; + /** + * Returns the local certificate as an `X509Certificate` object. + * + * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getX509Certificate(): X509Certificate | undefined; + /** + * Keying material is used for validations to prevent different kind of attacks in + * network protocols, for example in the specifications of IEEE 802.1X. + * + * Example + * + * ```js + * const keyingMaterial = tlsSocket.exportKeyingMaterial( + * 128, + * 'client finished'); + * + * /* + * Example return value of keyingMaterial: + * + * + * ``` + * + * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more + * information. + * @since v13.10.0, v12.17.0 + * @param length number of bytes to retrieve from keying material + * @param label an application specific label, typically this will be a value from the [IANA Exporter Label + * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * @param context Optionally provide a context. + * @return requested bytes of the keying material + */ + exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + addListener(event: "session", listener: (session: Buffer) => void): this; + addListener(event: "keylog", listener: (line: Buffer) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; + emit(event: "session", session: Buffer): boolean; + emit(event: "keylog", line: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + on(event: "session", listener: (session: Buffer) => void): this; + on(event: "keylog", listener: (line: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + once(event: "session", listener: (session: Buffer) => void): this; + once(event: "keylog", listener: (line: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + prependListener(event: "session", listener: (session: Buffer) => void): this; + prependListener(event: "keylog", listener: (line: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + prependOnceListener(event: "session", listener: (session: Buffer) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer) => void): this; + } + interface CommonConnectionOptions { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext | undefined; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * @default false + */ + enableTrace?: boolean | undefined; + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean | undefined; + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) + */ + ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. + * @default true + */ + rejectUnauthorized?: boolean | undefined; + } + interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { + /** + * Abort the connection if the SSL/TLS handshake does not finish in the + * specified number of milliseconds. A 'tlsClientError' is emitted on + * the tls.Server object whenever a handshake times out. Default: + * 120000 (120 seconds). + */ + handshakeTimeout?: number | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + */ + ticketKeys?: Buffer | undefined; + /** + * @param socket + * @param identity identity parameter sent from the client. + * @return pre-shared key that must either be + * a buffer or `null` to stop the negotiation process. Returned PSK must be + * compatible with the selected cipher's digest. + * + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with the identity provided by the client. + * If the return value is `null` the negotiation process will stop and an + * "unknown_psk_identity" alert message will be sent to the other party. + * If the server wishes to hide the fact that the PSK identity was not known, + * the callback must provide some random data as `psk` to make the connection + * fail with "decrypt_error" before negotiation is finished. + * PSK ciphers are disabled by default, and using TLS-PSK thus + * requires explicitly specifying a cipher suite with the `ciphers` option. + * More information can be found in the RFC 4279. + */ + pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; + /** + * hint to send to a client to help + * with selecting the identity during TLS-PSK negotiation. Will be ignored + * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be + * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. + */ + pskIdentityHint?: string | undefined; + } + interface PSKCallbackNegotation { + psk: DataView | NodeJS.TypedArray; + identity: string; + } + interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { + host?: string | undefined; + port?: number | undefined; + path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket + checkServerIdentity?: typeof checkServerIdentity | undefined; + servername?: string | undefined; // SNI TLS Extension + session?: Buffer | undefined; + minDHSize?: number | undefined; + lookup?: net.LookupFunction | undefined; + timeout?: number | undefined; + /** + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with optional identity `hint` provided by the server or `null` + * in case of TLS 1.3 where `hint` was removed. + * It will be necessary to provide a custom `tls.checkServerIdentity()` + * for the connection as the default one will try to check hostname/IP + * of the server against the certificate but that's not applicable for PSK + * because there won't be a certificate present. + * More information can be found in the RFC 4279. + * + * @param hint message sent from the server to help client + * decide which identity to use during negotiation. + * Always `null` if TLS 1.3 is used. + * @returns Return `null` to stop the negotiation process. `psk` must be + * compatible with the selected cipher's digest. + * `identity` must use UTF-8 encoding. + */ + pskCallback?(hint: string | null): PSKCallbackNegotation | null; + } + /** + * Accepts encrypted connections using TLS or SSL. + * @since v0.3.2 + */ + class Server extends net.Server { + constructor(secureConnectionListener?: (socket: TLSSocket) => void); + constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); + /** + * The `server.addContext()` method adds a secure context that will be used if + * the client request's SNI name matches the supplied `hostname` (or wildcard). + * + * When there are multiple matching contexts, the most recently added one is + * used. + * @since v0.5.3 + * @param hostname A SNI host name or wildcard (e.g. `'*'`) + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc), or a TLS context object created + * with {@link createSecureContext} itself. + */ + addContext(hostname: string, context: SecureContextOptions): void; + /** + * Returns the session ticket keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @return A 48-byte buffer containing the session ticket keys. + */ + getTicketKeys(): Buffer; + /** + * The `server.setSecureContext()` method replaces the secure context of an + * existing server. Existing connections to the server are not interrupted. + * @since v11.0.0 + * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + setSecureContext(options: SecureContextOptions): void; + /** + * Sets the session ticket keys. + * + * Changes to the ticket keys are effective only for future server connections. + * Existing or currently pending server connections will use the previous keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @param keys A 48-byte buffer containing the session ticket keys. + */ + setTicketKeys(keys: Buffer): void; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + * 6. keylog + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + addListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: () => void): boolean; + emit( + event: "OCSPRequest", + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ): boolean; + emit( + event: "resumeSession", + sessionId: Buffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + emit(event: "keylog", line: Buffer, tlsSocket: TLSSocket): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void): this; + on( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + on(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + once(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + } + /** + * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. + */ + interface SecurePair { + encrypted: TLSSocket; + cleartext: TLSSocket; + } + type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1"; + interface SecureContextOptions { + /** + * If set, this will be called when a client opens a connection using the ALPN extension. + * One argument will be passed to the callback: an object containing `servername` and `protocols` fields, + * respectively containing the server name from the SNI extension (if any) and an array of + * ALPN protocol name strings. The callback must return either one of the strings listed in `protocols`, + * which will be returned to the client as the selected ALPN protocol, or `undefined`, + * to reject the connection with a fatal alert. If a string is returned that does not match one of + * the client's ALPN protocols, an error will be thrown. + * This option cannot be used with the `ALPNProtocols` option, and setting both options will throw an error. + */ + ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined; + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Colon-separated list of supported signature algorithms. The list + * can contain digest algorithms (SHA256, MD5 etc.), public key + * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g + * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). + */ + sigalgs?: string | undefined; + /** + * Cipher suite specification, replacing the default. For more + * information, see modifying the default cipher suite. Permitted + * ciphers can be obtained via tls.getCiphers(). Cipher names must be + * uppercased in order for OpenSSL to accept them. + */ + ciphers?: string | undefined; + /** + * Name of an OpenSSL engine which can provide the client certificate. + * @deprecated + */ + clientCertEngine?: string | undefined; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: string | Buffer | Array | undefined; + /** + * `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. + * If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. + * ECDHE-based perfect forward secrecy will still be available. + */ + dhparam?: string | Buffer | undefined; + /** + * A string describing a named curve or a colon separated list of curve + * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key + * agreement. Set to auto to select the curve automatically. Use + * crypto.getCurves() to obtain a list of available curve names. On + * recent releases, openssl ecparam -list_curves will also display the + * name and description of each available elliptic curve. Default: + * tls.DEFAULT_ECDH_CURVE. + */ + ecdhCurve?: string | undefined; + /** + * Attempt to use the server's cipher suite preferences instead of the + * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be + * set in secureOptions + */ + honorCipherOrder?: boolean | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Name of an OpenSSL engine to get private key from. Should be used + * together with privateKeyIdentifier. + * @deprecated + */ + privateKeyEngine?: string | undefined; + /** + * Identifier of a private key managed by an OpenSSL engine. Should be + * used together with privateKeyEngine. Should not be set together with + * key, because both options define a private key in different ways. + * @deprecated + */ + privateKeyIdentifier?: string | undefined; + /** + * Optionally set the maximum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. + * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using + * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to + * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. + */ + maxVersion?: SecureVersion | undefined; + /** + * Optionally set the minimum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to + * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. + */ + minVersion?: SecureVersion | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form {buf: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted PFX will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; + /** + * Optionally affect the OpenSSL protocol behavior, which is not + * usually necessary. This should be used carefully if at all! Value is + * a numeric bitmask of the SSL_OP_* options from OpenSSL Options + */ + secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options + /** + * Legacy mechanism to select the TLS protocol version to use, it does + * not support independent control of the minimum and maximum version, + * and does not support limiting the protocol to TLSv1.3. Use + * minVersion and maxVersion instead. The possible values are listed as + * SSL_METHODS, use the function names as strings. For example, use + * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow + * any TLS protocol version up to TLSv1.3. It is not recommended to use + * TLS versions less than 1.2, but it may be required for + * interoperability. Default: none, see minVersion. + */ + secureProtocol?: string | undefined; + /** + * Opaque identifier used by servers to ensure session state is not + * shared between applications. Unused by clients. + */ + sessionIdContext?: string | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + * See Session Resumption for more information. + */ + ticketKeys?: Buffer | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + } + interface SecureContext { + context: any; + } + /** + * Verifies the certificate `cert` is issued to `hostname`. + * + * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on + * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). + * + * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as + * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead. + * + * This function can be overwritten by providing an alternative function as the `options.checkServerIdentity` option that is passed to `tls.connect()`. The + * overwriting function can call `tls.checkServerIdentity()` of course, to augment + * the checks done with additional verification. + * + * This function is only called if the certificate passed all other checks, such as + * being issued by trusted CA (`options.ca`). + * + * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name + * was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use + * a custom `options.checkServerIdentity` function that implements the desired behavior. + * @since v0.8.4 + * @param hostname The host name or IP address to verify the certificate against. + * @param cert A `certificate object` representing the peer's certificate. + */ + function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; + /** + * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is + * automatically set as a listener for the `'secureConnection'` event. + * + * The `ticketKeys` options is automatically shared between `node:cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * const tls = require('node:tls'); + * const fs = require('node:fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * + * // This is necessary only if using client certificate authentication. + * requestCert: true, + * + * // This is necessary only if the client uses a self-signed certificate. + * ca: [ fs.readFileSync('client-cert.pem') ], + * }; + * + * const server = tls.createServer(options, (socket) => { + * console.log('server connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * socket.write('welcome!\n'); + * socket.setEncoding('utf8'); + * socket.pipe(socket); + * }); + * server.listen(8000, () => { + * console.log('server bound'); + * }); + * ``` + * + * The server can be tested by connecting to it using the example client from {@link connect}. + * @since v0.3.2 + */ + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. + * + * `tls.connect()` returns a {@link TLSSocket} object. + * + * Unlike the `https` API, `tls.connect()` does not enable the + * SNI (Server Name Indication) extension by default, which may cause some + * servers to return an incorrect certificate or reject the connection + * altogether. To enable SNI, set the `servername` option in addition + * to `host`. + * + * The following illustrates a client for the echo server example from {@link createServer}: + * + * ```js + * // Assumes an echo server that is listening on port 8000. + * const tls = require('node:tls'); + * const fs = require('node:fs'); + * + * const options = { + * // Necessary only if the server requires client certificate authentication. + * key: fs.readFileSync('client-key.pem'), + * cert: fs.readFileSync('client-cert.pem'), + * + * // Necessary only if the server uses a self-signed certificate. + * ca: [ fs.readFileSync('server-cert.pem') ], + * + * // Necessary only if the server's cert isn't for "localhost". + * checkServerIdentity: () => { return null; }, + * }; + * + * const socket = tls.connect(8000, options, () => { + * console.log('client connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * process.stdin.pipe(socket); + * process.stdin.resume(); + * }); + * socket.setEncoding('utf8'); + * socket.on('data', (data) => { + * console.log(data); + * }); + * socket.on('end', () => { + * console.log('server ends connection'); + * }); + * ``` + * @since v0.11.3 + */ + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect( + port: number, + host?: string, + options?: ConnectionOptions, + secureConnectListener?: () => void, + ): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * Creates a new secure pair object with two streams, one of which reads and writes + * the encrypted data and the other of which reads and writes the cleartext data. + * Generally, the encrypted stream is piped to/from an incoming encrypted data + * stream and the cleartext one is used as a replacement for the initial encrypted + * stream. + * + * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and `encrypted` stream properties. + * + * Using `cleartext` has the same API as {@link TLSSocket}. + * + * The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code: + * + * ```js + * pair = tls.createSecurePair(// ... ); + * pair.encrypted.pipe(socket); + * socket.pipe(pair.encrypted); + * ``` + * + * can be replaced by: + * + * ```js + * secureSocket = tls.TLSSocket(socket, options); + * ``` + * + * where `secureSocket` has the same API as `pair.cleartext`. + * @since v0.3.2 + * @deprecated Since v0.11.3 - Use {@link TLSSocket} instead. + * @param context A secure context object as returned by `tls.createSecureContext()` + * @param isServer `true` to specify that this TLS connection should be opened as a server. + * @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`. + * @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`. + */ + function createSecurePair( + context?: SecureContext, + isServer?: boolean, + requestCert?: boolean, + rejectUnauthorized?: boolean, + ): SecurePair; + /** + * `{@link createServer}` sets the default value of the `honorCipherOrder` option + * to `true`, other APIs that create secure contexts leave it unset. + * + * `{@link createServer}` uses a 128 bit truncated SHA1 hash value generated + * from `process.argv` as the default value of the `sessionIdContext` option, other + * APIs that create secure contexts have no default value. + * + * The `tls.createSecureContext()` method creates a `SecureContext` object. It is + * usable as an argument to several `tls` APIs, such as `server.addContext()`, + * but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option. + * + * A key is _required_ for ciphers that use certificates. Either `key` or `pfx` can be used to provide it. + * + * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of + * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * + * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto' `option. When set to `'auto'`, well-known DHE parameters of sufficient strength + * will be selected automatically. Otherwise, if necessary, `openssl dhparam` can + * be used to create custom parameters. The key length must be greater than or + * equal to 1024 bits or else an error will be thrown. Although 1024 bits is + * permissible, use 2048 bits or larger for stronger security. + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * Returns an array with the names of the supported TLS ciphers. The names are + * lower-case for historical reasons, but must be uppercased to be used in + * the `ciphers` option of `{@link createSecureContext}`. + * + * Not all supported ciphers are enabled by default. See + * [Modifying the default TLS cipher suite](https://nodejs.org/docs/latest-v22.x/api/tls.html#modifying-the-default-tls-cipher-suite). + * + * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for + * TLSv1.2 and below. + * + * ```js + * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] + * ``` + * @since v0.10.2 + */ + function getCiphers(): string[]; + /** + * The default curve name to use for ECDH key agreement in a tls server. + * The default value is `'auto'`. See `{@link createSecureContext()}` for further + * information. + * @since v0.11.13 + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the `maxVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.3'`, unless + * changed using CLI options. Using `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using + * `--tls-max-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the highest maximum is used. + * @since v11.4.0 + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the `minVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.2'`, unless + * changed using CLI options. Using `--tls-min-v1.0` sets the default to + * `'TLSv1'`. Using `--tls-min-v1.1` sets the default to `'TLSv1.1'`. Using + * `--tls-min-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the lowest minimum is used. + * @since v11.4.0 + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * The default value of the `ciphers` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported OpenSSL ciphers. + * Defaults to the content of `crypto.constants.defaultCoreCipherList`, unless + * changed using CLI options using `--tls-default-ciphers`. + * @since v19.8.0 + */ + let DEFAULT_CIPHERS: string; + /** + * An immutable array of strings representing the root certificates (in PEM format) + * from the bundled Mozilla CA store as supplied by the current Node.js version. + * + * The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store + * that is fixed at release time. It is identical on all supported platforms. + * @since v12.3.0 + */ + const rootCertificates: readonly string[]; +} +declare module "node:tls" { + export * from "tls"; +} diff --git a/node_modules/@types/node/trace_events.d.ts b/node_modules/@types/node/trace_events.d.ts new file mode 100644 index 0000000..f339455 --- /dev/null +++ b/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,197 @@ +/** + * The `node:trace_events` module provides a mechanism to centralize tracing information + * generated by V8, Node.js core, and userspace code. + * + * Tracing can be enabled with the `--trace-event-categories` command-line flag + * or by using the `trace_events` module. The `--trace-event-categories` flag + * accepts a list of comma-separated category names. + * + * The available categories are: + * + * * `node`: An empty placeholder. + * * `node.async_hooks`: Enables capture of detailed [`async_hooks`](https://nodejs.org/docs/latest-v22.x/api/async_hooks.html) trace data. + * The [`async_hooks`](https://nodejs.org/docs/latest-v22.x/api/async_hooks.html) events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. + * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. + * * `node.console`: Enables capture of `console.time()` and `console.count()` output. + * * `node.threadpoolwork.sync`: Enables capture of trace data for threadpool synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.threadpoolwork.async`: Enables capture of trace data for threadpool asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.dns.native`: Enables capture of trace data for DNS queries. + * * `node.net.native`: Enables capture of trace data for network. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.fs_dir.sync`: Enables capture of trace data for file system sync directory methods. + * * `node.fs.async`: Enables capture of trace data for file system async methods. + * * `node.fs_dir.async`: Enables capture of trace data for file system async directory methods. + * * `node.perf`: Enables capture of [Performance API](https://nodejs.org/docs/latest-v22.x/api/perf_hooks.html) measurements. + * * `node.perf.usertiming`: Enables capture of only Performance API User Timing + * measures and marks. + * * `node.perf.timerify`: Enables capture of only Performance API timerify + * measurements. + * * `node.promises.rejections`: Enables capture of trace data tracking the number + * of unhandled Promise rejections and handled-after-rejections. + * * `node.vm.script`: Enables capture of trace data for the `node:vm` module's `runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The [V8](https://nodejs.org/docs/latest-v22.x/api/v8.html) events are GC, compiling, and execution related. + * * `node.http`: Enables capture of trace data for http request / response. + * + * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. + * + * ```bash + * node --trace-event-categories v8,node,node.async_hooks server.js + * ``` + * + * Prior versions of Node.js required the use of the `--trace-events-enabled` flag to enable trace events. This requirement has been removed. However, the `--trace-events-enabled` flag _may_ still be + * used and will enable the `node`, `node.async_hooks`, and `v8` trace event categories by default. + * + * ```bash + * node --trace-events-enabled + * + * # is equivalent to + * + * node --trace-event-categories v8,node,node.async_hooks + * ``` + * + * Alternatively, trace events may be enabled using the `node:trace_events` module: + * + * ```js + * const trace_events = require('node:trace_events'); + * const tracing = trace_events.createTracing({ categories: ['node.perf'] }); + * tracing.enable(); // Enable trace event capture for the 'node.perf' category + * + * // do work + * + * tracing.disable(); // Disable trace event capture for the 'node.perf' category + * ``` + * + * Running Node.js with tracing enabled will produce log files that can be opened + * in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome. + * + * The logging file is by default called `node_trace.${rotation}.log`, where `${rotation}` is an incrementing log-rotation id. The filepath pattern can + * be specified with `--trace-event-file-pattern` that accepts a template + * string that supports `${rotation}` and `${pid}`: + * + * ```bash + * node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js + * ``` + * + * To guarantee that the log file is properly generated after signal events like `SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers + * in your code, such as: + * + * ```js + * process.on('SIGINT', function onSigint() { + * console.info('Received SIGINT.'); + * process.exit(130); // Or applicable exit code depending on OS and signal + * }); + * ``` + * + * The tracing system uses the same time source + * as the one used by `process.hrtime()`. + * However the trace-event timestamps are expressed in microseconds, + * unlike `process.hrtime()` which returns nanoseconds. + * + * The features from this module are not available in [`Worker`](https://nodejs.org/docs/latest-v22.x/api/worker_threads.html#class-worker) threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/trace_events.js) + */ +declare module "trace_events" { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + * @since v10.0.0 + */ + readonly categories: string; + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + * + * ```js + * const trace_events = require('node:trace_events'); + * const t1 = trace_events.createTracing({ categories: ['node', 'v8'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] }); + * t1.enable(); + * t2.enable(); + * + * // Prints 'node,node.perf,v8' + * console.log(trace_events.getEnabledCategories()); + * + * t2.disable(); // Will only disable emission of the 'node.perf' category + * + * // Prints 'node,v8' + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + * @since v10.0.0 + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + * @since v10.0.0 + */ + readonly enabled: boolean; + } + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + /** + * Creates and returns a `Tracing` object for the given set of `categories`. + * + * ```js + * const trace_events = require('node:trace_events'); + * const categories = ['node.perf', 'node.async_hooks']; + * const tracing = trace_events.createTracing({ categories }); + * tracing.enable(); + * // do stuff + * tracing.disable(); + * ``` + * @since v10.0.0 + */ + function createTracing(options: CreateTracingOptions): Tracing; + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is determined + * by the _union_ of all currently-enabled `Tracing` objects and any categories + * enabled using the `--trace-event-categories` flag. + * + * Given the file `test.js` below, the command `node --trace-event-categories node.perf test.js` will print `'node.async_hooks,node.perf'` to the console. + * + * ```js + * const trace_events = require('node:trace_events'); + * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); + * const t3 = trace_events.createTracing({ categories: ['v8'] }); + * + * t1.enable(); + * t2.enable(); + * + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + function getEnabledCategories(): string | undefined; +} +declare module "node:trace_events" { + export * from "trace_events"; +} diff --git a/node_modules/@types/node/tty.d.ts b/node_modules/@types/node/tty.d.ts new file mode 100644 index 0000000..b88dbbd --- /dev/null +++ b/node_modules/@types/node/tty.d.ts @@ -0,0 +1,208 @@ +/** + * The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. In most cases, it will not be necessary or possible to use this module + * directly. However, it can be accessed using: + * + * ```js + * const tty = require('node:tty'); + * ``` + * + * When Node.js detects that it is being run with a text terminal ("TTY") + * attached, `process.stdin` will, by default, be initialized as an instance of `tty.ReadStream` and both `process.stdout` and `process.stderr` will, by + * default, be instances of `tty.WriteStream`. The preferred method of determining + * whether Node.js is being run within a TTY context is to check that the value of + * the `process.stdout.isTTY` property is `true`: + * + * ```console + * $ node -p -e "Boolean(process.stdout.isTTY)" + * true + * $ node -p -e "Boolean(process.stdout.isTTY)" | cat + * false + * ``` + * + * In most cases, there should be little to no reason for an application to + * manually create instances of the `tty.ReadStream` and `tty.WriteStream` classes. + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/tty.js) + */ +declare module "tty" { + import * as net from "node:net"; + /** + * The `tty.isatty()` method returns `true` if the given `fd` is associated with + * a TTY and `false` if it is not, including whenever `fd` is not a non-negative + * integer. + * @since v0.5.8 + * @param fd A numeric file descriptor + */ + function isatty(fd: number): boolean; + /** + * Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js + * process and there should be no reason to create additional instances. + * @since v0.5.8 + */ + class ReadStream extends net.Socket { + constructor(fd: number, options?: net.SocketConstructorOpts); + /** + * A `boolean` that is `true` if the TTY is currently configured to operate as a + * raw device. + * + * This flag is always `false` when a process starts, even if the terminal is + * operating in raw mode. Its value will change with subsequent calls to `setRawMode`. + * @since v0.7.7 + */ + isRaw: boolean; + /** + * Allows configuration of `tty.ReadStream` so that it operates as a raw device. + * + * When in raw mode, input is always available character-by-character, not + * including modifiers. Additionally, all special processing of characters by the + * terminal is disabled, including echoing input + * characters. Ctrl+C will no longer cause a `SIGINT` when + * in this mode. + * @since v0.7.7 + * @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` + * property will be set to the resulting mode. + * @return The read stream instance. + */ + setRawMode(mode: boolean): this; + /** + * A `boolean` that is always `true` for `tty.ReadStream` instances. + * @since v0.5.8 + */ + isTTY: boolean; + } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; + /** + * Represents the writable side of a TTY. In normal circumstances, `process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there + * should be no reason to create additional instances. + * @since v0.5.8 + */ + class WriteStream extends net.Socket { + constructor(fd: number); + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "resize", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "resize"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "resize", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "resize", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "resize", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "resize", listener: () => void): this; + /** + * `writeStream.clearLine()` clears the current line of this `WriteStream` in a + * direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearLine(dir: Direction, callback?: () => void): boolean; + /** + * `writeStream.clearScreenDown()` clears this `WriteStream` from the current + * cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearScreenDown(callback?: () => void): boolean; + /** + * `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified + * position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + cursorTo(x: number, y?: number, callback?: () => void): boolean; + cursorTo(x: number, callback: () => void): boolean; + /** + * `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its + * current position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + moveCursor(dx: number, dy: number, callback?: () => void): boolean; + /** + * Returns: + * + * * `1` for 2, + * * `4` for 16, + * * `8` for 256, + * * `24` for 16,777,216 colors supported. + * + * Use this to determine what colors the terminal supports. Due to the nature of + * colors in terminals it is possible to either have false positives or false + * negatives. It depends on process information and the environment variables that + * may lie about what terminal is used. + * It is possible to pass in an `env` object to simulate the usage of a specific + * terminal. This can be useful to check how specific environment settings behave. + * + * To enforce a specific color support, use one of the below environment settings. + * + * * 2 colors: `FORCE_COLOR = 0` (Disables colors) + * * 16 colors: `FORCE_COLOR = 1` + * * 256 colors: `FORCE_COLOR = 2` + * * 16,777,216 colors: `FORCE_COLOR = 3` + * + * Disabling color support is also possible by using the `NO_COLOR` and `NODE_DISABLE_COLORS` environment variables. + * @since v9.9.0 + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + getColorDepth(env?: object): number; + /** + * Returns `true` if the `writeStream` supports at least as many colors as provided + * in `count`. Minimum support is 2 (black and white). + * + * This has the same false positives and negatives as described in `writeStream.getColorDepth()`. + * + * ```js + * process.stdout.hasColors(); + * // Returns true or false depending on if `stdout` supports at least 16 colors. + * process.stdout.hasColors(256); + * // Returns true or false depending on if `stdout` supports at least 256 colors. + * process.stdout.hasColors({ TMUX: '1' }); + * // Returns true. + * process.stdout.hasColors(2 ** 24, { TMUX: '1' }); + * // Returns false (the environment setting pretends to support 2 ** 8 colors). + * ``` + * @since v11.13.0, v10.16.0 + * @param [count=16] The number of colors that are requested (minimum 2). + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + hasColors(count?: number): boolean; + hasColors(env?: object): boolean; + hasColors(count: number, env?: object): boolean; + /** + * `writeStream.getWindowSize()` returns the size of the TTY + * corresponding to this `WriteStream`. The array is of the type `[numColumns, numRows]` where `numColumns` and `numRows` represent the number + * of columns and rows in the corresponding TTY. + * @since v0.7.7 + */ + getWindowSize(): [number, number]; + /** + * A `number` specifying the number of columns the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + columns: number; + /** + * A `number` specifying the number of rows the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + rows: number; + /** + * A `boolean` that is always `true`. + * @since v0.5.8 + */ + isTTY: boolean; + } +} +declare module "node:tty" { + export * from "tty"; +} diff --git a/node_modules/@types/node/url.d.ts b/node_modules/@types/node/url.d.ts new file mode 100644 index 0000000..cb06e06 --- /dev/null +++ b/node_modules/@types/node/url.d.ts @@ -0,0 +1,969 @@ +/** + * The `node:url` module provides utilities for URL resolution and parsing. It can + * be accessed using: + * + * ```js + * import url from 'node:url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/url.js) + */ +declare module "url" { + import { Blob as NodeBlob } from "node:buffer"; + import { ClientRequestArgs } from "node:http"; + import { ParsedUrlQuery, ParsedUrlQueryInput } from "node:querystring"; + // Input to `url.format` + interface UrlObject { + auth?: string | null | undefined; + hash?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + href?: string | null | undefined; + pathname?: string | null | undefined; + protocol?: string | null | undefined; + search?: string | null | undefined; + slashes?: boolean | null | undefined; + port?: string | number | null | undefined; + query?: string | null | ParsedUrlQueryInput | undefined; + } + // Output of `url.parse` + interface Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; + } + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + interface UrlWithStringQuery extends Url { + query: string | null; + } + interface FileUrlToPathOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + * @since v22.1.0 + */ + windows?: boolean | undefined; + } + interface PathToFileUrlOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + * @since v22.1.0 + */ + windows?: boolean | undefined; + } + /** + * The `url.parse()` method takes a URL string, parses it, and returns a URL + * object. + * + * A `TypeError` is thrown if `urlString` is not a string. + * + * A `URIError` is thrown if the `auth` property is present but cannot be decoded. + * + * `url.parse()` uses a lenient, non-standard algorithm for parsing URL + * strings. It is prone to security issues such as [host name spoofing](https://hackerone.com/reports/678487) and incorrect handling of usernames and passwords. Do not use with untrusted + * input. CVEs are not issued for `url.parse()` vulnerabilities. Use the `WHATWG URL` API instead. + * @since v0.1.25 + * @deprecated Use the WHATWG URL API instead. + * @param urlString The URL string to parse. + * @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property + * on the returned URL object will be an unparsed, undecoded string. + * @param [slashesDenoteHost=false] If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the + * result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + */ + function parse(urlString: string): UrlWithStringQuery; + function parse( + urlString: string, + parseQueryString: false | undefined, + slashesDenoteHost?: boolean, + ): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * const url = require('node:url'); + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: URL, options?: URLFormatOptions): string; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * const url = require('node:url'); + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: UrlObject | string): string; + /** + * The `url.resolve()` method resolves a target URL relative to a base URL in a + * manner similar to that of a web browser resolving an anchor tag. + * + * ```js + * const url = require('node:url'); + * url.resolve('/one/two/three', 'four'); // '/one/two/four' + * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' + * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * + * To achieve the same result using the WHATWG URL API: + * + * ```js + * function resolve(from, to) { + * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); + * if (resolvedUrl.protocol === 'resolve:') { + * // `from` is a relative URL. + * const { pathname, search, hash } = resolvedUrl; + * return pathname + search + hash; + * } + * return resolvedUrl.toString(); + * } + * + * resolve('/one/two/three', 'four'); // '/one/two/four' + * resolve('http://example.com/', '/one'); // 'http://example.com/one' + * resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param from The base URL to use if `to` is a relative URL. + * @param to The target URL to resolve. + */ + function resolve(from: string, to: string): string; + /** + * Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an + * invalid domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToUnicode}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToASCII('español.com')); + * // Prints xn--espaol-zwa.com + * console.log(url.domainToASCII('中文.com')); + * // Prints xn--fiq228c.com + * console.log(url.domainToASCII('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToASCII(domain: string): string; + /** + * Returns the Unicode serialization of the `domain`. If `domain` is an invalid + * domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToASCII}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToUnicode('xn--espaol-zwa.com')); + * // Prints español.com + * console.log(url.domainToUnicode('xn--fiq228c.com')); + * // Prints 中文.com + * console.log(url.domainToUnicode('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToUnicode(domain: string): string; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * + * ```js + * import { fileURLToPath } from 'node:url'; + * + * const __filename = fileURLToPath(import.meta.url); + * + * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ + * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) + * + * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt + * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) + * + * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt + * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) + * + * new URL('file:///hello world').pathname; // Incorrect: /hello%20world + * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) + * ``` + * @since v10.12.0 + * @param url The file URL string or URL object to convert to a path. + * @return The fully-resolved platform-specific Node.js file path. + */ + function fileURLToPath(url: string | URL, options?: FileUrlToPathOptions): string; + /** + * This function ensures that `path` is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * + * ```js + * import { pathToFileURL } from 'node:url'; + * + * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 + * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) + * + * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c + * pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) + * ``` + * @since v10.12.0 + * @param path The path to convert to a File URL. + * @return The file URL object. + */ + function pathToFileURL(path: string, options?: PathToFileUrlOptions): URL; + /** + * This utility function converts a URL object into an ordinary options object as + * expected by the `http.request()` and `https.request()` APIs. + * + * ```js + * import { urlToHttpOptions } from 'node:url'; + * const myURL = new URL('https://a:b@測試?abc#foo'); + * + * console.log(urlToHttpOptions(myURL)); + * /* + * { + * protocol: 'https:', + * hostname: 'xn--g6w251d', + * hash: '#foo', + * search: '?abc', + * pathname: '/', + * path: '/?abc', + * href: 'https://a:b@xn--g6w251d/?abc#foo', + * auth: 'a:b' + * } + * + * ``` + * @since v15.7.0, v14.18.0 + * @param url The `WHATWG URL` object to convert to an options object. + * @return Options object + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; + interface URLFormatOptions { + /** + * `true` if the serialized URL string should include the username and password, `false` otherwise. + * @default true + */ + auth?: boolean | undefined; + /** + * `true` if the serialized URL string should include the fragment, `false` otherwise. + * @default true + */ + fragment?: boolean | undefined; + /** + * `true` if the serialized URL string should include the search query, `false` otherwise. + * @default true + */ + search?: boolean | undefined; + /** + * `true` if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to + * being Punycode encoded. + * @default false + */ + unicode?: boolean | undefined; + } + /** + * Browser-compatible `URL` class, implemented by following the WHATWG URL + * Standard. [Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself. + * The `URL` class is also available on the global object. + * + * In accordance with browser conventions, all properties of `URL` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. Thus, unlike `legacy urlObject`s, + * using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still + * return `true`. + * @since v7.0.0, v6.13.0 + */ + class URL { + /** + * Creates a `'blob:nodedata:...'` URL string that represents the given `Blob` object and can be used to retrieve the `Blob` later. + * + * ```js + * const { + * Blob, + * resolveObjectURL, + * } = require('node:buffer'); + * + * const blob = new Blob(['hello']); + * const id = URL.createObjectURL(blob); + * + * // later... + * + * const otherBlob = resolveObjectURL(id); + * console.log(otherBlob.size); + * ``` + * + * The data stored by the registered `Blob` will be retained in memory until `URL.revokeObjectURL()` is called to remove it. + * + * `Blob` objects are registered within the current thread. If using Worker + * Threads, `Blob` objects registered within one Worker will not be available + * to other workers or the main thread. + * @since v16.7.0 + * @experimental + */ + static createObjectURL(blob: NodeBlob): string; + /** + * Removes the stored `Blob` identified by the given ID. Attempting to revoke a + * ID that isn't registered will silently fail. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + static revokeObjectURL(id: string): void; + /** + * Checks if an `input` relative to the `base` can be parsed to a `URL`. + * + * ```js + * const isValid = URL.canParse('/foo', 'https://example.org/'); // true + * + * const isNotValid = URL.canParse('/foo'); // false + * ``` + * @since v19.9.0 + * @param input The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored. If `input` is not a string, it is + * `converted to a string` first. + * @param base The base URL to resolve against if the `input` is not absolute. If `base` is not a string, it is `converted to a string` first. + */ + static canParse(input: string, base?: string): boolean; + /** + * Parses a string as a URL. If `base` is provided, it will be used as the base URL for the purpose of resolving non-absolute `input` URLs. + * Returns `null` if `input` is not a valid. + * @param input The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored. If `input` is not a string, it is + * `converted to a string` first. + * @param base The base URL to resolve against if the `input` is not absolute. If `base` is not a string, it is `converted to a string` first. + * @since v22.1.0 + */ + static parse(input: string, base?: string): URL | null; + constructor(input: string | { toString: () => string }, base?: string | URL); + /** + * Gets and sets the fragment portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/foo#bar'); + * console.log(myURL.hash); + * // Prints #bar + * + * myURL.hash = 'baz'; + * console.log(myURL.href); + * // Prints https://example.org/foo#baz + * ``` + * + * Invalid URL characters included in the value assigned to the `hash` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + hash: string; + /** + * Gets and sets the host portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.host); + * // Prints example.org:81 + * + * myURL.host = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:82/foo + * ``` + * + * Invalid host values assigned to the `host` property are ignored. + */ + host: string; + /** + * Gets and sets the host name portion of the URL. The key difference between`url.host` and `url.hostname` is that `url.hostname` does _not_ include the + * port. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.hostname); + * // Prints example.org + * + * // Setting the hostname does not change the port + * myURL.hostname = 'example.com'; + * console.log(myURL.href); + * // Prints https://example.com:81/foo + * + * // Use myURL.host to change the hostname and port + * myURL.host = 'example.org:82'; + * console.log(myURL.href); + * // Prints https://example.org:82/foo + * ``` + * + * Invalid host name values assigned to the `hostname` property are ignored. + */ + hostname: string; + /** + * Gets and sets the serialized URL. + * + * ```js + * const myURL = new URL('https://example.org/foo'); + * console.log(myURL.href); + * // Prints https://example.org/foo + * + * myURL.href = 'https://example.com/bar'; + * console.log(myURL.href); + * // Prints https://example.com/bar + * ``` + * + * Getting the value of the `href` property is equivalent to calling {@link toString}. + * + * Setting the value of this property to a new value is equivalent to creating a + * new `URL` object using `new URL(value)`. Each of the `URL` object's properties will be modified. + * + * If the value assigned to the `href` property is not a valid URL, a `TypeError` will be thrown. + */ + href: string; + /** + * Gets the read-only serialization of the URL's origin. + * + * ```js + * const myURL = new URL('https://example.org/foo/bar?baz'); + * console.log(myURL.origin); + * // Prints https://example.org + * ``` + * + * ```js + * const idnURL = new URL('https://測試'); + * console.log(idnURL.origin); + * // Prints https://xn--g6w251d + * + * console.log(idnURL.hostname); + * // Prints xn--g6w251d + * ``` + */ + readonly origin: string; + /** + * Gets and sets the password portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.password); + * // Prints xyz + * + * myURL.password = '123'; + * console.log(myURL.href); + * // Prints https://abc:123@example.com/ + * ``` + * + * Invalid URL characters included in the value assigned to the `password` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + password: string; + /** + * Gets and sets the path portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc/xyz?123'); + * console.log(myURL.pathname); + * // Prints /abc/xyz + * + * myURL.pathname = '/abcdef'; + * console.log(myURL.href); + * // Prints https://example.org/abcdef?123 + * ``` + * + * Invalid URL characters included in the value assigned to the `pathname` property are `percent-encoded`. The selection of which characters + * to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + pathname: string; + /** + * Gets and sets the port portion of the URL. + * + * The port value may be a number or a string containing a number in the range `0` to `65535` (inclusive). Setting the value to the default port of the `URL` objects given `protocol` will + * result in the `port` value becoming + * the empty string (`''`). + * + * The port value can be an empty string in which case the port depends on + * the protocol/scheme: + * + * + * + * Upon assigning a value to the port, the value will first be converted to a + * string using `.toString()`. + * + * If that string is invalid but it begins with a number, the leading number is + * assigned to `port`. + * If the number lies outside the range denoted above, it is ignored. + * + * ```js + * const myURL = new URL('https://example.org:8888'); + * console.log(myURL.port); + * // Prints 8888 + * + * // Default ports are automatically transformed to the empty string + * // (HTTPS protocol's default port is 443) + * myURL.port = '443'; + * console.log(myURL.port); + * // Prints the empty string + * console.log(myURL.href); + * // Prints https://example.org/ + * + * myURL.port = 1234; + * console.log(myURL.port); + * // Prints 1234 + * console.log(myURL.href); + * // Prints https://example.org:1234/ + * + * // Completely invalid port strings are ignored + * myURL.port = 'abcd'; + * console.log(myURL.port); + * // Prints 1234 + * + * // Leading numbers are treated as a port number + * myURL.port = '5678abcd'; + * console.log(myURL.port); + * // Prints 5678 + * + * // Non-integers are truncated + * myURL.port = 1234.5678; + * console.log(myURL.port); + * // Prints 1234 + * + * // Out-of-range numbers which are not represented in scientific notation + * // will be ignored. + * myURL.port = 1e10; // 10000000000, will be range-checked as described below + * console.log(myURL.port); + * // Prints 1234 + * ``` + * + * Numbers which contain a decimal point, + * such as floating-point numbers or numbers in scientific notation, + * are not an exception to this rule. + * Leading numbers up to the decimal point will be set as the URL's port, + * assuming they are valid: + * + * ```js + * myURL.port = 4.567e21; + * console.log(myURL.port); + * // Prints 4 (because it is the leading number in the string '4.567e21') + * ``` + */ + port: string; + /** + * Gets and sets the protocol portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org'); + * console.log(myURL.protocol); + * // Prints https: + * + * myURL.protocol = 'ftp'; + * console.log(myURL.href); + * // Prints ftp://example.org/ + * ``` + * + * Invalid URL protocol values assigned to the `protocol` property are ignored. + */ + protocol: string; + /** + * Gets and sets the serialized query portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc?123'); + * console.log(myURL.search); + * // Prints ?123 + * + * myURL.search = 'abc=xyz'; + * console.log(myURL.href); + * // Prints https://example.org/abc?abc=xyz + * ``` + * + * Any invalid URL characters appearing in the value assigned the `search` property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + search: string; + /** + * Gets the `URLSearchParams` object representing the query parameters of the + * URL. This property is read-only but the `URLSearchParams` object it provides + * can be used to mutate the URL instance; to replace the entirety of query + * parameters of the URL, use the {@link search} setter. See `URLSearchParams` documentation for details. + * + * Use care when using `.searchParams` to modify the `URL` because, + * per the WHATWG specification, the `URLSearchParams` object uses + * different rules to determine which characters to percent-encode. For + * instance, the `URL` object will not percent encode the ASCII tilde (`~`) + * character, while `URLSearchParams` will always encode it: + * + * ```js + * const myURL = new URL('https://example.org/abc?foo=~bar'); + * + * console.log(myURL.search); // prints ?foo=~bar + * + * // Modify the URL via searchParams... + * myURL.searchParams.sort(); + * + * console.log(myURL.search); // prints ?foo=%7Ebar + * ``` + */ + readonly searchParams: URLSearchParams; + /** + * Gets and sets the username portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.username); + * // Prints abc + * + * myURL.username = '123'; + * console.log(myURL.href); + * // Prints https://123:xyz@example.com/ + * ``` + * + * Any invalid URL characters appearing in the value assigned the `username` property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + username: string; + /** + * The `toString()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toJSON}. + */ + toString(): string; + /** + * The `toJSON()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toString}. + * + * This method is automatically called when an `URL` object is serialized + * with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). + * + * ```js + * const myURLs = [ + * new URL('https://www.example.com'), + * new URL('https://test.example.org'), + * ]; + * console.log(JSON.stringify(myURLs)); + * // Prints ["https://www.example.com/","https://test.example.org/"] + * ``` + */ + toJSON(): string; + } + /** + * The `URLSearchParams` API provides read and write access to the query of a `URL`. The `URLSearchParams` class can also be used standalone with one of the + * four following constructors. + * The `URLSearchParams` class is also available on the global object. + * + * The WHATWG `URLSearchParams` interface and the `querystring` module have + * similar purpose, but the purpose of the `querystring` module is more + * general, as it allows the customization of delimiter characters (`&` and `=`). + * On the other hand, this API is designed purely for URL query strings. + * + * ```js + * const myURL = new URL('https://example.org/?abc=123'); + * console.log(myURL.searchParams.get('abc')); + * // Prints 123 + * + * myURL.searchParams.append('abc', 'xyz'); + * console.log(myURL.href); + * // Prints https://example.org/?abc=123&abc=xyz + * + * myURL.searchParams.delete('abc'); + * myURL.searchParams.set('a', 'b'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * + * const newSearchParams = new URLSearchParams(myURL.searchParams); + * // The above is equivalent to + * // const newSearchParams = new URLSearchParams(myURL.search); + * + * newSearchParams.append('a', 'c'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * console.log(newSearchParams.toString()); + * // Prints a=b&a=c + * + * // newSearchParams.toString() is implicitly called + * myURL.search = newSearchParams; + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * newSearchParams.delete('a'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * ``` + * @since v7.5.0, v6.13.0 + */ + class URLSearchParams implements Iterable<[string, string]> { + constructor( + init?: + | URLSearchParams + | string + | Record + | Iterable<[string, string]> + | ReadonlyArray<[string, string]>, + ); + /** + * Append a new name-value pair to the query string. + */ + append(name: string, value: string): void; + /** + * If `value` is provided, removes all name-value pairs + * where name is `name` and value is `value`. + * + * If `value` is not provided, removes all name-value pairs whose name is `name`. + */ + delete(name: string, value?: string): void; + /** + * Returns an ES6 `Iterator` over each of the name-value pairs in the query. + * Each item of the iterator is a JavaScript `Array`. The first item of the `Array` is the `name`, the second item of the `Array` is the `value`. + * + * Alias for `urlSearchParams[@@iterator]()`. + */ + entries(): IterableIterator<[string, string]>; + /** + * Iterates over each name-value pair in the query and invokes the given function. + * + * ```js + * const myURL = new URL('https://example.org/?a=b&c=d'); + * myURL.searchParams.forEach((value, name, searchParams) => { + * console.log(name, value, myURL.searchParams === searchParams); + * }); + * // Prints: + * // a b true + * // c d true + * ``` + * @param fn Invoked for each name-value pair in the query + * @param thisArg To be used as `this` value for when `fn` is called + */ + forEach( + fn: (this: TThis, value: string, name: string, searchParams: URLSearchParams) => void, + thisArg?: TThis, + ): void; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns the values of all name-value pairs whose name is `name`. If there are + * no such pairs, an empty array is returned. + */ + getAll(name: string): string[]; + /** + * Checks if the `URLSearchParams` object contains key-value pair(s) based on `name` and an optional `value` argument. + * + * If `value` is provided, returns `true` when name-value pair with + * same `name` and `value` exists. + * + * If `value` is not provided, returns `true` if there is at least one name-value + * pair whose name is `name`. + */ + has(name: string, value?: string): boolean; + /** + * Returns an ES6 `Iterator` over the names of each name-value pair. + * + * ```js + * const params = new URLSearchParams('foo=bar&foo=baz'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // foo + * ``` + */ + keys(): IterableIterator; + /** + * Sets the value in the `URLSearchParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value` and remove all others. If not, + * append the name-value pair to the query string. + * + * ```js + * const params = new URLSearchParams(); + * params.append('foo', 'bar'); + * params.append('foo', 'baz'); + * params.append('abc', 'def'); + * console.log(params.toString()); + * // Prints foo=bar&foo=baz&abc=def + * + * params.set('foo', 'def'); + * params.set('xyz', 'opq'); + * console.log(params.toString()); + * // Prints foo=def&abc=def&xyz=opq + * ``` + */ + set(name: string, value: string): void; + /** + * The total number of parameter entries. + * @since v19.8.0 + */ + readonly size: number; + /** + * Sort all existing name-value pairs in-place by their names. Sorting is done + * with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs + * with the same name is preserved. + * + * This method can be used, in particular, to increase cache hits. + * + * ```js + * const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); + * params.sort(); + * console.log(params.toString()); + * // Prints query%5B%5D=abc&query%5B%5D=123&type=search + * ``` + * @since v7.7.0, v6.13.0 + */ + sort(): void; + /** + * Returns the search parameters serialized as a string, with characters + * percent-encoded where necessary. + */ + toString(): string; + /** + * Returns an ES6 `Iterator` over the values of each name-value pair. + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; + } + import { URL as _URL, URLSearchParams as _URLSearchParams } from "url"; + global { + interface URLSearchParams extends _URLSearchParams {} + interface URL extends _URL {} + interface Global { + URL: typeof _URL; + URLSearchParams: typeof _URLSearchParams; + } + /** + * `URL` class is a global reference for `require('url').URL` + * https://nodejs.org/api/url.html#the-whatwg-url-api + * @since v10.0.0 + */ + var URL: typeof globalThis extends { + onmessage: any; + URL: infer T; + } ? T + : typeof _URL; + /** + * `URLSearchParams` class is a global reference for `require('url').URLSearchParams` + * https://nodejs.org/api/url.html#class-urlsearchparams + * @since v10.0.0 + */ + var URLSearchParams: typeof globalThis extends { + onmessage: any; + URLSearchParams: infer T; + } ? T + : typeof _URLSearchParams; + } +} +declare module "node:url" { + export * from "url"; +} diff --git a/node_modules/@types/node/util.d.ts b/node_modules/@types/node/util.d.ts new file mode 100644 index 0000000..275cd6e --- /dev/null +++ b/node_modules/@types/node/util.d.ts @@ -0,0 +1,2301 @@ +/** + * The `node:util` module supports the needs of Node.js internal APIs. Many of the + * utilities are useful for application and module developers as well. To access + * it: + * + * ```js + * const util = require('node:util'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/util.js) + */ +declare module "util" { + import * as types from "node:util/types"; + export interface InspectOptions { + /** + * If `true`, object's non-enumerable symbols and properties are included in the formatted result. + * `WeakMap` and `WeakSet` entries are also included as well as user defined prototype properties (excluding method properties). + * @default false + */ + showHidden?: boolean | undefined; + /** + * Specifies the number of times to recurse while formatting object. + * This is useful for inspecting large objects. + * To recurse up to the maximum call stack size pass `Infinity` or `null`. + * @default 2 + */ + depth?: number | null | undefined; + /** + * If `true`, the output is styled with ANSI color codes. Colors are customizable. + */ + colors?: boolean | undefined; + /** + * If `false`, `[util.inspect.custom](depth, opts, inspect)` functions are not invoked. + * @default true + */ + customInspect?: boolean | undefined; + /** + * If `true`, `Proxy` inspection includes the target and handler objects. + * @default false + */ + showProxy?: boolean | undefined; + /** + * Specifies the maximum number of `Array`, `TypedArray`, `WeakMap`, and `WeakSet` elements + * to include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no elements. + * @default 100 + */ + maxArrayLength?: number | null | undefined; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default 10000 + */ + maxStringLength?: number | null | undefined; + /** + * The length at which input values are split across multiple lines. + * Set to `Infinity` to format the input as a single line + * (in combination with `compact` set to `true` or any number >= `1`). + * @default 80 + */ + breakLength?: number | undefined; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default true + */ + compact?: boolean | number | undefined; + /** + * If set to `true` or a function, all properties of an object, and `Set` and `Map` + * entries are sorted in the resulting string. + * If set to `true` the default sort is used. + * If set to a function, it is used as a compare function. + */ + sorted?: boolean | ((a: string, b: string) => number) | undefined; + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default false + */ + getters?: "get" | "set" | boolean | undefined; + /** + * If set to `true`, an underscore is used to separate every three digits in all bigints and numbers. + * @default false + */ + numericSeparator?: boolean | undefined; + } + export type Style = + | "special" + | "number" + | "bigint" + | "boolean" + | "undefined" + | "null" + | "string" + | "symbol" + | "date" + | "regexp" + | "module"; + export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => any; // TODO: , inspect: inspect + export interface InspectOptionsStylized extends InspectOptions { + stylize(text: string, styleType: Style): string; + } + /** + * The `util.format()` method returns a formatted string using the first argument + * as a `printf`-like format string which can contain zero or more format + * specifiers. Each specifier is replaced with the converted value from the + * corresponding argument. Supported specifiers are: + * + * If a specifier does not have a corresponding argument, it is not replaced: + * + * ```js + * util.format('%s:%s', 'foo'); + * // Returns: 'foo:%s' + * ``` + * + * Values that are not part of the format string are formatted using `util.inspect()` if their type is not `string`. + * + * If there are more arguments passed to the `util.format()` method than the + * number of specifiers, the extra arguments are concatenated to the returned + * string, separated by spaces: + * + * ```js + * util.format('%s:%s', 'foo', 'bar', 'baz'); + * // Returns: 'foo:bar baz' + * ``` + * + * If the first argument does not contain a valid format specifier, `util.format()` returns a string that is the concatenation of all arguments separated by spaces: + * + * ```js + * util.format(1, 2, 3); + * // Returns: '1 2 3' + * ``` + * + * If only one argument is passed to `util.format()`, it is returned as it is + * without any formatting: + * + * ```js + * util.format('%% %s'); + * // Returns: '%% %s' + * ``` + * + * `util.format()` is a synchronous method that is intended as a debugging tool. + * Some input values can have a significant performance overhead that can block the + * event loop. Use this function with care and never in a hot code path. + * @since v0.5.3 + * @param format A `printf`-like format string. + */ + export function format(format?: any, ...param: any[]): string; + /** + * This function is identical to {@link format}, except in that it takes + * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}. + * + * ```js + * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + * // Returns 'See object { foo: 42 }', where `42` is colored as a number + * // when printed to a terminal. + * ``` + * @since v10.0.0 + */ + export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; + /** + * Returns the string name for a numeric error code that comes from a Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const name = util.getSystemErrorName(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v9.7.0 + */ + export function getSystemErrorName(err: number): string; + /** + * Returns a Map of all system error codes available from the Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const errorMap = util.getSystemErrorMap(); + * const name = errorMap.get(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v16.0.0, v14.17.0 + */ + export function getSystemErrorMap(): Map; + /** + * The `util.log()` method prints the given `string` to `stdout` with an included + * timestamp. + * + * ```js + * const util = require('node:util'); + * + * util.log('Timestamped message.'); + * ``` + * @since v0.3.0 + * @deprecated Since v6.0.0 - Use a third party module instead. + */ + export function log(string: string): void; + /** + * Returns the `string` after replacing any surrogate code points + * (or equivalently, any unpaired surrogate code units) with the + * Unicode "replacement character" U+FFFD. + * @since v16.8.0, v14.18.0 + */ + export function toUSVString(string: string): string; + /** + * Creates and returns an `AbortController` instance whose `AbortSignal` is marked + * as transferable and can be used with `structuredClone()` or `postMessage()`. + * @since v18.11.0 + * @experimental + * @returns A transferable AbortController + */ + export function transferableAbortController(): AbortController; + /** + * Marks the given `AbortSignal` as transferable so that it can be used with`structuredClone()` and `postMessage()`. + * + * ```js + * const signal = transferableAbortSignal(AbortSignal.timeout(100)); + * const channel = new MessageChannel(); + * channel.port2.postMessage(signal, [signal]); + * ``` + * @since v18.11.0 + * @experimental + * @param signal The AbortSignal + * @returns The same AbortSignal + */ + export function transferableAbortSignal(signal: AbortSignal): AbortSignal; + /** + * Listens to abort event on the provided `signal` and + * returns a promise that is fulfilled when the `signal` is + * aborted. If the passed `resource` is garbage collected before the `signal` is + * aborted, the returned promise shall remain pending indefinitely. + * + * ```js + * import { aborted } from 'node:util'; + * + * const dependent = obtainSomethingAbortable(); + * + * aborted(dependent.signal, dependent).then(() => { + * // Do something when dependent is aborted. + * }); + * + * dependent.on('event', () => { + * dependent.abort(); + * }); + * ``` + * @since v19.7.0 + * @experimental + * @param resource Any non-null entity, reference to which is held weakly. + */ + export function aborted(signal: AbortSignal, resource: any): Promise; + /** + * The `util.inspect()` method returns a string representation of `object` that is + * intended for debugging. The output of `util.inspect` may change at any time + * and should not be depended upon programmatically. Additional `options` may be + * passed that alter the result. `util.inspect()` will use the constructor's name and/or `@@toStringTag` to make + * an identifiable tag for an inspected value. + * + * ```js + * class Foo { + * get [Symbol.toStringTag]() { + * return 'bar'; + * } + * } + * + * class Bar {} + * + * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); + * + * util.inspect(new Foo()); // 'Foo [bar] {}' + * util.inspect(new Bar()); // 'Bar {}' + * util.inspect(baz); // '[foo] {}' + * ``` + * + * Circular references point to their anchor by using a reference index: + * + * ```js + * const { inspect } = require('node:util'); + * + * const obj = {}; + * obj.a = [obj]; + * obj.b = {}; + * obj.b.inner = obj.b; + * obj.b.obj = obj; + * + * console.log(inspect(obj)); + * // { + * // a: [ [Circular *1] ], + * // b: { inner: [Circular *2], obj: [Circular *1] } + * // } + * ``` + * + * The following example inspects all properties of the `util` object: + * + * ```js + * const util = require('node:util'); + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * const util = require('node:util'); + * + * const o = { + * a: [1, 2, [[ + * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + + * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', + * 'test', + * 'foo']], 4], + * b: new Map([['za', 1], ['zb', 'test']]), + * }; + * console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 })); + * + * // { a: + * // [ 1, + * // 2, + * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line + * // 'test', + * // 'foo' ] ], + * // 4 ], + * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } + * + * // Setting `compact` to false or an integer creates more reader friendly output. + * console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 })); + * + * // { + * // a: [ + * // 1, + * // 2, + * // [ + * // [ + * // 'Lorem ipsum dolor sit amet,\n' + + * // 'consectetur adipiscing elit, sed do eiusmod \n' + + * // 'tempor incididunt ut labore et dolore magna aliqua.', + * // 'test', + * // 'foo' + * // ] + * // ], + * // 4 + * // ], + * // b: Map(2) { + * // 'za' => 1, + * // 'zb' => 'test' + * // } + * // } + * + * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a + * // single line. + * ``` + * + * The `showHidden` option allows [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) and + * [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries to be + * inspected. If there are more entries than `maxArrayLength`, there is no + * guarantee which entries are displayed. That means retrieving the same [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries twice may + * result in different output. Furthermore, entries + * with no remaining strong references may be garbage collected at any time. + * + * ```js + * const { inspect } = require('node:util'); + * + * const obj = { a: 1 }; + * const obj2 = { b: 2 }; + * const weakSet = new WeakSet([obj, obj2]); + * + * console.log(inspect(weakSet, { showHidden: true })); + * // WeakSet { { a: 1 }, { b: 2 } } + * ``` + * + * The `sorted` option ensures that an object's property insertion order does not + * impact the result of `util.inspect()`. + * + * ```js + * const { inspect } = require('node:util'); + * const assert = require('node:assert'); + * + * const o1 = { + * b: [2, 3, 1], + * a: '`a` comes before `b`', + * c: new Set([2, 3, 1]), + * }; + * console.log(inspect(o1, { sorted: true })); + * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } + * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); + * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } + * + * const o2 = { + * c: new Set([2, 1, 3]), + * a: '`a` comes before `b`', + * b: [2, 3, 1], + * }; + * assert.strict.equal( + * inspect(o1, { sorted: true }), + * inspect(o2, { sorted: true }), + * ); + * ``` + * + * The `numericSeparator` option adds an underscore every three digits to all + * numbers. + * + * ```js + * const { inspect } = require('node:util'); + * + * const thousand = 1_000; + * const million = 1_000_000; + * const bigNumber = 123_456_789n; + * const bigDecimal = 1_234.123_45; + * + * console.log(inspect(thousand, { numericSeparator: true })); + * // 1_000 + * console.log(inspect(million, { numericSeparator: true })); + * // 1_000_000 + * console.log(inspect(bigNumber, { numericSeparator: true })); + * // 123_456_789n + * console.log(inspect(bigDecimal, { numericSeparator: true })); + * // 1_234.123_45 + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MiB. Inputs that result in longer output will + * be truncated. + * @since v0.3.0 + * @param object Any JavaScript primitive or `Object`. + * @return The representation of `object`. + */ + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options?: InspectOptions): string; + export namespace inspect { + let colors: NodeJS.Dict<[number, number]>; + let styles: { + [K in Style]: string; + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; + /** + * That can be used to declare custom inspect functions. + */ + const custom: unique symbol; + } + /** + * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). + * + * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isArray([]); + * // Returns: true + * util.isArray(new Array()); + * // Returns: true + * util.isArray({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use `isArray` instead. + */ + export function isArray(object: unknown): object is unknown[]; + /** + * Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isRegExp(/some regexp/); + * // Returns: true + * util.isRegExp(new RegExp('another regexp')); + * // Returns: true + * util.isRegExp({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Deprecated + */ + export function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isDate(new Date()); + * // Returns: true + * util.isDate(Date()); + * // false (without 'new' returns a String) + * util.isDate({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isDate} instead. + */ + export function isDate(object: unknown): object is Date; + /** + * Returns `true` if the given `object` is an `Error`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isError(new Error()); + * // Returns: true + * util.isError(new TypeError()); + * // Returns: true + * util.isError({ name: 'Error', message: 'an error occurred' }); + * // Returns: false + * ``` + * + * This method relies on `Object.prototype.toString()` behavior. It is + * possible to obtain an incorrect result when the `object` argument manipulates `@@toStringTag`. + * + * ```js + * const util = require('node:util'); + * const obj = { name: 'Error', message: 'an error occurred' }; + * + * util.isError(obj); + * // Returns: false + * obj[Symbol.toStringTag] = 'Error'; + * util.isError(obj); + * // Returns: true + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isNativeError} instead. + */ + export function isError(object: unknown): object is Error; + /** + * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and `extends` keywords to get language level inheritance support. Also note + * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). + * + * Inherit the prototype methods from one [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The + * prototype of `constructor` will be set to a new object created from `superConstructor`. + * + * This mainly adds some input validation on top of`Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. + * As an additional convenience, `superConstructor` will be accessible + * through the `constructor.super_` property. + * + * ```js + * const util = require('node:util'); + * const EventEmitter = require('node:events'); + * + * function MyStream() { + * EventEmitter.call(this); + * } + * + * util.inherits(MyStream, EventEmitter); + * + * MyStream.prototype.write = function(data) { + * this.emit('data', data); + * }; + * + * const stream = new MyStream(); + * + * console.log(stream instanceof EventEmitter); // true + * console.log(MyStream.super_ === EventEmitter); // true + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('It works!'); // Received data: "It works!" + * ``` + * + * ES6 example using `class` and `extends`: + * + * ```js + * const EventEmitter = require('node:events'); + * + * class MyStream extends EventEmitter { + * write(data) { + * this.emit('data', data); + * } + * } + * + * const stream = new MyStream(); + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('With ES6'); + * ``` + * @since v0.3.0 + * @legacy Use ES2015 class syntax and `extends` keyword instead. + */ + export function inherits(constructor: unknown, superConstructor: unknown): void; + export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; + export interface DebugLogger extends DebugLoggerFunction { + enabled: boolean; + } + /** + * The `util.debuglog()` method is used to create a function that conditionally + * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG`environment variable. If the `section` name appears within the value of that + * environment variable, then the returned function operates similar to `console.error()`. If not, then the returned function is a no-op. + * + * ```js + * const util = require('node:util'); + * const debuglog = util.debuglog('foo'); + * + * debuglog('hello from foo [%d]', 123); + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then + * it will output something like: + * + * ```console + * FOO 3245: hello from foo [123] + * ``` + * + * where `3245` is the process id. If it is not run with that + * environment variable set, then it will not print anything. + * + * The `section` supports wildcard also: + * + * ```js + * const util = require('node:util'); + * const debuglog = util.debuglog('foo-bar'); + * + * debuglog('hi there, it\'s foo-bar [%d]', 2333); + * ``` + * + * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output + * something like: + * + * ```console + * FOO-BAR 3257: hi there, it's foo-bar [2333] + * ``` + * + * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`environment variable: `NODE_DEBUG=fs,net,tls`. + * + * The optional `callback` argument can be used to replace the logging function + * with a different function that doesn't have any initialization or + * unnecessary wrapping. + * + * ```js + * const util = require('node:util'); + * let debuglog = util.debuglog('internals', (debug) => { + * // Replace with a logging function that optimizes out + * // testing if the section is enabled + * debuglog = debug; + * }); + * ``` + * @since v0.11.3 + * @param section A string identifying the portion of the application for which the `debuglog` function is being created. + * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function. + * @return The logging function + */ + export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; + export const debug: typeof debuglog; + /** + * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isBoolean(1); + * // Returns: false + * util.isBoolean(0); + * // Returns: false + * util.isBoolean(false); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'boolean'` instead. + */ + export function isBoolean(object: unknown): object is boolean; + /** + * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isBuffer({ length: 0 }); + * // Returns: false + * util.isBuffer([]); + * // Returns: false + * util.isBuffer(Buffer.from('hello world')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `isBuffer` instead. + */ + export function isBuffer(object: unknown): object is Buffer; + /** + * Returns `true` if the given `object` is a `Function`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * function Foo() {} + * const Bar = () => {}; + * + * util.isFunction({}); + * // Returns: false + * util.isFunction(Foo); + * // Returns: true + * util.isFunction(Bar); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'function'` instead. + */ + export function isFunction(object: unknown): boolean; + /** + * Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`. + * + * ```js + * const util = require('node:util'); + * + * util.isNull(0); + * // Returns: false + * util.isNull(undefined); + * // Returns: false + * util.isNull(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === null` instead. + */ + export function isNull(object: unknown): object is null; + /** + * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, + * returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isNullOrUndefined(0); + * // Returns: false + * util.isNullOrUndefined(undefined); + * // Returns: true + * util.isNullOrUndefined(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined || value === null` instead. + */ + export function isNullOrUndefined(object: unknown): object is null | undefined; + /** + * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isNumber(false); + * // Returns: false + * util.isNumber(Infinity); + * // Returns: true + * util.isNumber(0); + * // Returns: true + * util.isNumber(NaN); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'number'` instead. + */ + export function isNumber(object: unknown): object is number; + /** + * Returns `true` if the given `object` is strictly an `Object`**and** not a`Function` (even though functions are objects in JavaScript). + * Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isObject(5); + * // Returns: false + * util.isObject(null); + * // Returns: false + * util.isObject({}); + * // Returns: true + * util.isObject(() => {}); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value !== null && typeof value === 'object'` instead. + */ + export function isObject(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a primitive type. Otherwise, returns`false`. + * + * ```js + * const util = require('node:util'); + * + * util.isPrimitive(5); + * // Returns: true + * util.isPrimitive('foo'); + * // Returns: true + * util.isPrimitive(false); + * // Returns: true + * util.isPrimitive(null); + * // Returns: true + * util.isPrimitive(undefined); + * // Returns: true + * util.isPrimitive({}); + * // Returns: false + * util.isPrimitive(() => {}); + * // Returns: false + * util.isPrimitive(/^$/); + * // Returns: false + * util.isPrimitive(new Date()); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. + */ + export function isPrimitive(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isString(''); + * // Returns: true + * util.isString('foo'); + * // Returns: true + * util.isString(String('foo')); + * // Returns: true + * util.isString(5); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'string'` instead. + */ + export function isString(object: unknown): object is string; + /** + * Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isSymbol(5); + * // Returns: false + * util.isSymbol('foo'); + * // Returns: false + * util.isSymbol(Symbol('foo')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'symbol'` instead. + */ + export function isSymbol(object: unknown): object is symbol; + /** + * Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * const foo = undefined; + * util.isUndefined(5); + * // Returns: false + * util.isUndefined(foo); + * // Returns: true + * util.isUndefined(null); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined` instead. + */ + export function isUndefined(object: unknown): object is undefined; + /** + * The `util.deprecate()` method wraps `fn` (which may be a function or class) in + * such a way that it is marked as deprecated. + * + * ```js + * const util = require('node:util'); + * + * exports.obsoleteFunction = util.deprecate(() => { + * // Do something here. + * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); + * ``` + * + * When called, `util.deprecate()` will return a function that will emit a `DeprecationWarning` using the `'warning'` event. The warning will + * be emitted and printed to `stderr` the first time the returned function is + * called. After the warning is emitted, the wrapped function is called without + * emitting a warning. + * + * If the same optional `code` is supplied in multiple calls to `util.deprecate()`, + * the warning will be emitted only once for that `code`. + * + * ```js + * const util = require('node:util'); + * + * const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001'); + * const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001'); + * fn1(); // Emits a deprecation warning with code DEP0001 + * fn2(); // Does not emit a deprecation warning because it has the same code + * ``` + * + * If either the `--no-deprecation` or `--no-warnings` command-line flags are + * used, or if the `process.noDeprecation` property is set to `true`_prior_ to + * the first deprecation warning, the `util.deprecate()` method does nothing. + * + * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, + * or the `process.traceDeprecation` property is set to `true`, a warning and a + * stack trace are printed to `stderr` the first time the deprecated function is + * called. + * + * If the `--throw-deprecation` command-line flag is set, or the `process.throwDeprecation` property is set to `true`, then an exception will be + * thrown when the deprecated function is called. + * + * The `--throw-deprecation` command-line flag and `process.throwDeprecation` property take precedence over `--trace-deprecation` and `process.traceDeprecation`. + * @since v0.8.0 + * @param fn The function that is being deprecated. + * @param msg A warning message to display when the deprecated function is invoked. + * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes. + * @return The deprecated function wrapped to emit a warning. + */ + export function deprecate(fn: T, msg: string, code?: string): T; + /** + * Returns `true` if there is deep strict equality between `val1` and `val2`. + * Otherwise, returns `false`. + * + * See `assert.deepStrictEqual()` for more information about deep strict + * equality. + * @since v9.0.0 + */ + export function isDeepStrictEqual(val1: unknown, val2: unknown): boolean; + /** + * Returns `str` with any ANSI escape codes removed. + * + * ```js + * console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); + * // Prints "value" + * ``` + * @since v16.11.0 + */ + export function stripVTControlCharacters(str: string): string; + /** + * Takes an `async` function (or a function that returns a `Promise`) and returns a + * function following the error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument. In the callback, the + * first argument will be the rejection reason (or `null` if the `Promise` resolved), and the second argument will be the resolved value. + * + * ```js + * const util = require('node:util'); + * + * async function fn() { + * return 'hello world'; + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * if (err) throw err; + * console.log(ret); + * }); + * ``` + * + * Will print: + * + * ```text + * hello world + * ``` + * + * The callback is executed asynchronously, and will have a limited stack trace. + * If the callback throws, the process will emit an `'uncaughtException'` event, and if not handled will exit. + * + * Since `null` has a special meaning as the first argument to a callback, if a + * wrapped function rejects a `Promise` with a falsy value as a reason, the value + * is wrapped in an `Error` with the original value stored in a field named `reason`. + * + * ```js + * function fn() { + * return Promise.reject(null); + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * // When the Promise was rejected with `null` it is wrapped with an Error and + * // the original value is stored in `reason`. + * err && Object.hasOwn(err, 'reason') && err.reason === null; // true + * }); + * ``` + * @since v8.2.0 + * @param fn An `async` function + * @return a callback style function + */ + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: () => Promise, + ): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export interface CustomPromisifyLegacy extends Function { + __promisify__: TCustom; + } + export interface CustomPromisifySymbol extends Function { + [promisify.custom]: TCustom; + } + export type CustomPromisify = + | CustomPromisifySymbol + | CustomPromisifyLegacy; + /** + * Takes a function following the common error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument, and returns a version + * that returns promises. + * + * ```js + * const util = require('node:util'); + * const fs = require('node:fs'); + * + * const stat = util.promisify(fs.stat); + * stat('.').then((stats) => { + * // Do something with `stats` + * }).catch((error) => { + * // Handle the error. + * }); + * ``` + * + * Or, equivalently using `async function`s: + * + * ```js + * const util = require('node:util'); + * const fs = require('node:fs'); + * + * const stat = util.promisify(fs.stat); + * + * async function callStat() { + * const stats = await stat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * + * callStat(); + * ``` + * + * If there is an `original[util.promisify.custom]` property present, `promisify` will return its value, see `Custom promisified functions`. + * + * `promisify()` assumes that `original` is a function taking a callback as its + * final argument in all cases. If `original` is not a function, `promisify()` will throw an error. If `original` is a function but its last argument is not + * an error-first callback, it will still be passed an error-first + * callback as its last argument. + * + * Using `promisify()` on class methods or other methods that use `this` may not + * work as expected unless handled specially: + * + * ```js + * const util = require('node:util'); + * + * class Foo { + * constructor() { + * this.a = 42; + * } + * + * bar(callback) { + * callback(null, this.a); + * } + * } + * + * const foo = new Foo(); + * + * const naiveBar = util.promisify(foo.bar); + * // TypeError: Cannot read property 'a' of undefined + * // naiveBar().then(a => console.log(a)); + * + * naiveBar.call(foo).then((a) => console.log(a)); // '42' + * + * const bindBar = naiveBar.bind(foo); + * bindBar().then((a) => console.log(a)); // '42' + * ``` + * @since v8.0.0 + */ + export function promisify(fn: CustomPromisify): TCustom; + export function promisify( + fn: (callback: (err: any, result: TResult) => void) => void, + ): () => Promise; + export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + export function promisify( + fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: Function): Function; + export namespace promisify { + /** + * That can be used to declare custom promisified variants of functions. + */ + const custom: unique symbol; + } + /** + * Stability: 1.1 - Active development + * Given an example `.env` file: + * + * ```js + * const { parseEnv } = require('node:util'); + * + * parseEnv('HELLO=world\nHELLO=oh my\n'); + * // Returns: { HELLO: 'oh my' } + * ``` + * @param content The raw contents of a `.env` file. + * @since v20.12.0 + */ + export function parseEnv(content: string): object; + // https://nodejs.org/docs/latest/api/util.html#foreground-colors + type ForegroundColors = + | "black" + | "blackBright" + | "blue" + | "blueBright" + | "cyan" + | "cyanBright" + | "gray" + | "green" + | "greenBright" + | "grey" + | "magenta" + | "magentaBright" + | "red" + | "redBright" + | "white" + | "whiteBright" + | "yellow" + | "yellowBright"; + // https://nodejs.org/docs/latest/api/util.html#background-colors + type BackgroundColors = + | "bgBlack" + | "bgBlackBright" + | "bgBlue" + | "bgBlueBright" + | "bgCyan" + | "bgCyanBright" + | "bgGray" + | "bgGreen" + | "bgGreenBright" + | "bgGrey" + | "bgMagenta" + | "bgMagentaBright" + | "bgRed" + | "bgRedBright" + | "bgWhite" + | "bgWhiteBright" + | "bgYellow" + | "bgYellowBright"; + // https://nodejs.org/docs/latest/api/util.html#modifiers + type Modifiers = + | "blink" + | "bold" + | "dim" + | "doubleunderline" + | "framed" + | "hidden" + | "inverse" + | "italic" + | "overlined" + | "reset" + | "strikethrough" + | "underline"; + /** + * Stability: 1.1 - Active development + * + * This function returns a formatted text considering the `format` passed. + * + * ```js + * const { styleText } = require('node:util'); + * const errorMessage = styleText('red', 'Error! Error!'); + * console.log(errorMessage); + * ``` + * + * `util.inspect.colors` also provides text formats such as `italic`, and `underline` and you can combine both: + * + * ```js + * console.log( + * util.styleText(['underline', 'italic'], 'My italic underlined message'), + * ); + * ``` + * + * When passing an array of formats, the order of the format applied is left to right so the following style + * might overwrite the previous one. + * + * ```js + * console.log( + * util.styleText(['red', 'green'], 'text'), // green + * ); + * ``` + * + * The full list of formats can be found in [modifiers](https://nodejs.org/docs/latest-v22.x/api/util.html#modifiers). + * @param format A text format or an Array of text formats defined in `util.inspect.colors`. + * @param text The text to to be formatted. + * @since v20.12.0 + */ + export function styleText( + format: + | ForegroundColors + | BackgroundColors + | Modifiers + | Array, + text: string, + ): string; + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. + * + * ```js + * const decoder = new TextDecoder(); + * const u8arr = new Uint8Array([72, 101, 108, 108, 111]); + * console.log(decoder.decode(u8arr)); // Hello + * ``` + * @since v8.3.0 + */ + export class TextDecoder { + /** + * The encoding supported by the `TextDecoder` instance. + */ + readonly encoding: string; + /** + * The value will be `true` if decoding errors result in a `TypeError` being + * thrown. + */ + readonly fatal: boolean; + /** + * The value will be `true` if the decoding result will include the byte order + * mark. + */ + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { + fatal?: boolean | undefined; + ignoreBOM?: boolean | undefined; + }, + ); + /** + * Decodes the `input` and returns a string. If `options.stream` is `true`, any + * incomplete byte sequences occurring at the end of the `input` are buffered + * internally and emitted after the next call to `textDecoder.decode()`. + * + * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a `TypeError` being thrown. + * @param input An `ArrayBuffer`, `DataView`, or `TypedArray` instance containing the encoded data. + */ + decode( + input?: NodeJS.ArrayBufferView | ArrayBuffer | null, + options?: { + stream?: boolean | undefined; + }, + ): string; + } + export interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; + } + export { types }; + + //// TextEncoder/Decoder + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All + * instances of `TextEncoder` only support UTF-8 encoding. + * + * ```js + * const encoder = new TextEncoder(); + * const uint8array = encoder.encode('this is some data'); + * ``` + * + * The `TextEncoder` class is also available on the global object. + * @since v8.3.0 + */ + export class TextEncoder { + /** + * The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. + */ + readonly encoding: string; + /** + * UTF-8 encodes the `input` string and returns a `Uint8Array` containing the + * encoded bytes. + * @param [input='an empty string'] The text to encode. + */ + encode(input?: string): Uint8Array; + /** + * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object + * containing the read Unicode code units and written UTF-8 bytes. + * + * ```js + * const encoder = new TextEncoder(); + * const src = 'this is some data'; + * const dest = new Uint8Array(10); + * const { read, written } = encoder.encodeInto(src, dest); + * ``` + * @param src The text to encode. + * @param dest The array to hold the encode result. + */ + encodeInto(src: string, dest: Uint8Array): EncodeIntoResult; + } + import { TextDecoder as _TextDecoder, TextEncoder as _TextEncoder } from "util"; + global { + /** + * `TextDecoder` class is a global reference for `require('util').TextDecoder` + * https://nodejs.org/api/globals.html#textdecoder + * @since v11.0.0 + */ + var TextDecoder: typeof globalThis extends { + onmessage: any; + TextDecoder: infer TextDecoder; + } ? TextDecoder + : typeof _TextDecoder; + /** + * `TextEncoder` class is a global reference for `require('util').TextEncoder` + * https://nodejs.org/api/globals.html#textencoder + * @since v11.0.0 + */ + var TextEncoder: typeof globalThis extends { + onmessage: any; + TextEncoder: infer TextEncoder; + } ? TextEncoder + : typeof _TextEncoder; + } + + //// parseArgs + /** + * Provides a higher level API for command-line argument parsing than interacting + * with `process.argv` directly. Takes a specification for the expected arguments + * and returns a structured object with the parsed options and positionals. + * + * ```js + * import { parseArgs } from 'node:util'; + * const args = ['-f', '--bar', 'b']; + * const options = { + * foo: { + * type: 'boolean', + * short: 'f', + * }, + * bar: { + * type: 'string', + * }, + * }; + * const { + * values, + * positionals, + * } = parseArgs({ args, options }); + * console.log(values, positionals); + * // Prints: [Object: null prototype] { foo: true, bar: 'b' } [] + * ``` + * @since v18.3.0, v16.17.0 + * @param config Used to provide arguments for parsing and to configure the parser. `config` supports the following properties: + * @return The parsed command line arguments: + */ + export function parseArgs(config?: T): ParsedResults; + interface ParseArgsOptionConfig { + /** + * Type of argument. + */ + type: "string" | "boolean"; + /** + * Whether this option can be provided multiple times. + * If `true`, all values will be collected in an array. + * If `false`, values for the option are last-wins. + * @default false. + */ + multiple?: boolean | undefined; + /** + * A single character alias for the option. + */ + short?: string | undefined; + /** + * The default option value when it is not set by args. + * It must be of the same type as the the `type` property. + * When `multiple` is `true`, it must be an array. + * @since v18.11.0 + */ + default?: string | boolean | string[] | boolean[] | undefined; + } + interface ParseArgsOptionsConfig { + [longOption: string]: ParseArgsOptionConfig; + } + export interface ParseArgsConfig { + /** + * Array of argument strings. + */ + args?: string[] | undefined; + /** + * Used to describe arguments known to the parser. + */ + options?: ParseArgsOptionsConfig | undefined; + /** + * Should an error be thrown when unknown arguments are encountered, + * or when arguments are passed that do not match the `type` configured in `options`. + * @default true + */ + strict?: boolean | undefined; + /** + * Whether this command accepts positional arguments. + */ + allowPositionals?: boolean | undefined; + /** + * If `true`, allows explicitly setting boolean options to `false` by prefixing the option name with `--no-`. + * @default false + * @since v22.4.0 + */ + allowNegative?: boolean | undefined; + /** + * Return the parsed tokens. This is useful for extending the built-in behavior, + * from adding additional checks through to reprocessing the tokens in different ways. + * @default false + */ + tokens?: boolean | undefined; + } + /* + IfDefaultsTrue and IfDefaultsFalse are helpers to handle default values for missing boolean properties. + TypeScript does not have exact types for objects: https://github.com/microsoft/TypeScript/issues/12936 + This means it is impossible to distinguish between "field X is definitely not present" and "field X may or may not be present". + But we expect users to generally provide their config inline or `as const`, which means TS will always know whether a given field is present. + So this helper treats "not definitely present" (i.e., not `extends boolean`) as being "definitely not present", i.e. it should have its default value. + This is technically incorrect but is a much nicer UX for the common case. + The IfDefaultsTrue version is for things which default to true; the IfDefaultsFalse version is for things which default to false. + */ + type IfDefaultsTrue = T extends true ? IfTrue + : T extends false ? IfFalse + : IfTrue; + + // we put the `extends false` condition first here because `undefined` compares like `any` when `strictNullChecks: false` + type IfDefaultsFalse = T extends false ? IfFalse + : T extends true ? IfTrue + : IfFalse; + + type ExtractOptionValue = IfDefaultsTrue< + T["strict"], + O["type"] extends "string" ? string : O["type"] extends "boolean" ? boolean : string | boolean, + string | boolean + >; + + type ParsedValues = + & IfDefaultsTrue + & (T["options"] extends ParseArgsOptionsConfig ? { + -readonly [LongOption in keyof T["options"]]: + // when "default" is not undefined, the value will be present + | (T["options"][LongOption]["default"] extends {} ? never : undefined) + | IfDefaultsFalse< + T["options"][LongOption]["multiple"], + Array>, + ExtractOptionValue + >; + } + : {}); + + type ParsedPositionals = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type PreciseTokenForOptions< + K extends string, + O extends ParseArgsOptionConfig, + > = O["type"] extends "string" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: string; + inlineValue: boolean; + } + : O["type"] extends "boolean" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: undefined; + inlineValue: undefined; + } + : OptionToken & { name: K }; + + type TokenForOptions< + T extends ParseArgsConfig, + K extends keyof T["options"] = keyof T["options"], + > = K extends unknown + ? T["options"] extends ParseArgsOptionsConfig ? PreciseTokenForOptions + : OptionToken + : never; + + type ParsedOptionToken = IfDefaultsTrue, OptionToken>; + + type ParsedPositionalToken = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type ParsedTokens = Array< + ParsedOptionToken | ParsedPositionalToken | { kind: "option-terminator"; index: number } + >; + + type PreciseParsedResults = IfDefaultsFalse< + T["tokens"], + { + values: ParsedValues; + positionals: ParsedPositionals; + tokens: ParsedTokens; + }, + { + values: ParsedValues; + positionals: ParsedPositionals; + } + >; + + type OptionToken = + | { kind: "option"; index: number; name: string; rawName: string; value: string; inlineValue: boolean } + | { + kind: "option"; + index: number; + name: string; + rawName: string; + value: undefined; + inlineValue: undefined; + }; + + type Token = + | OptionToken + | { kind: "positional"; index: number; value: string } + | { kind: "option-terminator"; index: number }; + + // If ParseArgsConfig extends T, then the user passed config constructed elsewhere. + // So we can't rely on the `"not definitely present" implies "definitely not present"` assumption mentioned above. + type ParsedResults = ParseArgsConfig extends T ? { + values: { + [longOption: string]: undefined | string | boolean | Array; + }; + positionals: string[]; + tokens?: Token[]; + } + : PreciseParsedResults; + + /** + * An implementation of [the MIMEType class](https://bmeck.github.io/node-proposal-mime-api/). + * + * In accordance with browser conventions, all properties of `MIMEType` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. + * + * A MIME string is a structured string containing multiple meaningful + * components. When parsed, a `MIMEType` object is returned containing + * properties for each of these components. + * @since v19.1.0, v18.13.0 + * @experimental + */ + export class MIMEType { + /** + * Creates a new MIMEType object by parsing the input. + * + * A `TypeError` will be thrown if the `input` is not a valid MIME. + * Note that an effort will be made to coerce the given values into strings. + * @param input The input MIME to parse. + */ + constructor(input: string | { toString: () => string }); + + /** + * Gets and sets the type portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript'); + * console.log(myMIME.type); + * // Prints: text + * myMIME.type = 'application'; + * console.log(myMIME.type); + * // Prints: application + * console.log(String(myMIME)); + * // Prints: application/javascript + * ``` + */ + type: string; + /** + * Gets and sets the subtype portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/ecmascript'); + * console.log(myMIME.subtype); + * // Prints: ecmascript + * myMIME.subtype = 'javascript'; + * console.log(myMIME.subtype); + * // Prints: javascript + * console.log(String(myMIME)); + * // Prints: text/javascript + * ``` + */ + subtype: string; + /** + * Gets the essence of the MIME. This property is read only. + * Use `mime.type` or `mime.subtype` to alter the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript;key=value'); + * console.log(myMIME.essence); + * // Prints: text/javascript + * myMIME.type = 'application'; + * console.log(myMIME.essence); + * // Prints: application/javascript + * console.log(String(myMIME)); + * // Prints: application/javascript;key=value + * ``` + */ + readonly essence: string; + /** + * Gets the `MIMEParams` object representing the + * parameters of the MIME. This property is read-only. See `MIMEParams` documentation for details. + */ + readonly params: MIMEParams; + /** + * The `toString()` method on the `MIMEType` object returns the serialized MIME. + * + * Because of the need for standard compliance, this method does not allow users + * to customize the serialization process of the MIME. + */ + toString(): string; + } + /** + * The `MIMEParams` API provides read and write access to the parameters of a `MIMEType`. + * @since v19.1.0, v18.13.0 + */ + export class MIMEParams { + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: string): void; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + * Each item of the iterator is a JavaScript `Array`. The first item of the array + * is the `name`, the second item of the array is the `value`. + */ + entries(): IterableIterator<[name: string, value: string]>; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: string): boolean; + /** + * Returns an iterator over the names of each name-value pair. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // bar + * ``` + */ + keys(): IterableIterator; + /** + * Sets the value in the `MIMEParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value`. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * params.set('foo', 'def'); + * params.set('baz', 'xyz'); + * console.log(params.toString()); + * // Prints: foo=def;bar=1;baz=xyz + * ``` + */ + set(name: string, value: string): void; + /** + * Returns an iterator over the values of each name-value pair. + */ + values(): IterableIterator; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + */ + [Symbol.iterator]: typeof MIMEParams.prototype.entries; + } +} +declare module "util/types" { + import { KeyObject, webcrypto } from "node:crypto"; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or + * [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * + * See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`. + * + * ```js + * util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isAnyArrayBuffer(object: unknown): object is ArrayBufferLike; + /** + * Returns `true` if the value is an `arguments` object. + * + * ```js + * function foo() { + * util.types.isArgumentsObject(arguments); // Returns true + * } + * ``` + * @since v10.0.0 + */ + function isArgumentsObject(object: unknown): object is IArguments; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance. + * This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false + * ``` + * @since v10.0.0 + */ + function isArrayBuffer(object: unknown): object is ArrayBuffer; + /** + * Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) views, such as typed + * array objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent to + * [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * + * ```js + * util.types.isArrayBufferView(new Int8Array()); // true + * util.types.isArrayBufferView(Buffer.from('hello world')); // true + * util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true + * util.types.isArrayBufferView(new ArrayBuffer()); // false + * ``` + * @since v10.0.0 + */ + function isArrayBufferView(object: unknown): object is NodeJS.ArrayBufferView; + /** + * Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isAsyncFunction(function foo() {}); // Returns false + * util.types.isAsyncFunction(async function foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isAsyncFunction(object: unknown): boolean; + /** + * Returns `true` if the value is a `BigInt64Array` instance. + * + * ```js + * util.types.isBigInt64Array(new BigInt64Array()); // Returns true + * util.types.isBigInt64Array(new BigUint64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isBigInt64Array(value: unknown): value is BigInt64Array; + /** + * Returns `true` if the value is a `BigUint64Array` instance. + * + * ```js + * util.types.isBigUint64Array(new BigInt64Array()); // Returns false + * util.types.isBigUint64Array(new BigUint64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isBigUint64Array(value: unknown): value is BigUint64Array; + /** + * Returns `true` if the value is a boolean object, e.g. created + * by `new Boolean()`. + * + * ```js + * util.types.isBooleanObject(false); // Returns false + * util.types.isBooleanObject(true); // Returns false + * util.types.isBooleanObject(new Boolean(false)); // Returns true + * util.types.isBooleanObject(new Boolean(true)); // Returns true + * util.types.isBooleanObject(Boolean(false)); // Returns false + * util.types.isBooleanObject(Boolean(true)); // Returns false + * ``` + * @since v10.0.0 + */ + function isBooleanObject(object: unknown): object is Boolean; + /** + * Returns `true` if the value is any boxed primitive object, e.g. created + * by `new Boolean()`, `new String()` or `Object(Symbol())`. + * + * For example: + * + * ```js + * util.types.isBoxedPrimitive(false); // Returns false + * util.types.isBoxedPrimitive(new Boolean(false)); // Returns true + * util.types.isBoxedPrimitive(Symbol('foo')); // Returns false + * util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true + * util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true + * ``` + * @since v10.11.0 + */ + function isBoxedPrimitive(object: unknown): object is String | Number | BigInt | Boolean | Symbol; + /** + * Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance. + * + * ```js + * const ab = new ArrayBuffer(20); + * util.types.isDataView(new DataView(ab)); // Returns true + * util.types.isDataView(new Float64Array()); // Returns false + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isDataView(object: unknown): object is DataView; + /** + * Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance. + * + * ```js + * util.types.isDate(new Date()); // Returns true + * ``` + * @since v10.0.0 + */ + function isDate(object: unknown): object is Date; + /** + * Returns `true` if the value is a native `External` value. + * + * A native `External` value is a special type of object that contains a + * raw C++ pointer (`void*`) for access from native code, and has no other + * properties. Such objects are created either by Node.js internals or native + * addons. In JavaScript, they are [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a`null` prototype. + * + * ```c + * #include + * #include + * napi_value result; + * static napi_value MyNapi(napi_env env, napi_callback_info info) { + * int* raw = (int*) malloc(1024); + * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); + * if (status != napi_ok) { + * napi_throw_error(env, NULL, "napi_create_external failed"); + * return NULL; + * } + * return result; + * } + * ... + * DECLARE_NAPI_PROPERTY("myNapi", MyNapi) + * ... + * ``` + * + * ```js + * const native = require('napi_addon.node'); + * const data = native.myNapi(); + * util.types.isExternal(data); // returns true + * util.types.isExternal(0); // returns false + * util.types.isExternal(new String('foo')); // returns false + * ``` + * + * For further information on `napi_create_external`, refer to `napi_create_external()`. + * @since v10.0.0 + */ + function isExternal(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance. + * + * ```js + * util.types.isFloat32Array(new ArrayBuffer()); // Returns false + * util.types.isFloat32Array(new Float32Array()); // Returns true + * util.types.isFloat32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isFloat32Array(object: unknown): object is Float32Array; + /** + * Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance. + * + * ```js + * util.types.isFloat64Array(new ArrayBuffer()); // Returns false + * util.types.isFloat64Array(new Uint8Array()); // Returns false + * util.types.isFloat64Array(new Float64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isFloat64Array(object: unknown): object is Float64Array; + /** + * Returns `true` if the value is a generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isGeneratorFunction(function foo() {}); // Returns false + * util.types.isGeneratorFunction(function* foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorFunction(object: unknown): object is GeneratorFunction; + /** + * Returns `true` if the value is a generator object as returned from a + * built-in generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * function* foo() {} + * const generator = foo(); + * util.types.isGeneratorObject(generator); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorObject(object: unknown): object is Generator; + /** + * Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance. + * + * ```js + * util.types.isInt8Array(new ArrayBuffer()); // Returns false + * util.types.isInt8Array(new Int8Array()); // Returns true + * util.types.isInt8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt8Array(object: unknown): object is Int8Array; + /** + * Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance. + * + * ```js + * util.types.isInt16Array(new ArrayBuffer()); // Returns false + * util.types.isInt16Array(new Int16Array()); // Returns true + * util.types.isInt16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt16Array(object: unknown): object is Int16Array; + /** + * Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance. + * + * ```js + * util.types.isInt32Array(new ArrayBuffer()); // Returns false + * util.types.isInt32Array(new Int32Array()); // Returns true + * util.types.isInt32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt32Array(object: unknown): object is Int32Array; + /** + * Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * util.types.isMap(new Map()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMap( + object: T | {}, + ): object is T extends ReadonlyMap ? (unknown extends T ? never : ReadonlyMap) + : Map; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * const map = new Map(); + * util.types.isMapIterator(map.keys()); // Returns true + * util.types.isMapIterator(map.values()); // Returns true + * util.types.isMapIterator(map.entries()); // Returns true + * util.types.isMapIterator(map[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMapIterator(object: unknown): boolean; + /** + * Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects). + * + * ```js + * import * as ns from './a.js'; + * + * util.types.isModuleNamespaceObject(ns); // Returns true + * ``` + * @since v10.0.0 + */ + function isModuleNamespaceObject(value: unknown): boolean; + /** + * Returns `true` if the value was returned by the constructor of a [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects). + * + * ```js + * console.log(util.types.isNativeError(new Error())); // true + * console.log(util.types.isNativeError(new TypeError())); // true + * console.log(util.types.isNativeError(new RangeError())); // true + * ``` + * + * Subclasses of the native error types are also native errors: + * + * ```js + * class MyError extends Error {} + * console.log(util.types.isNativeError(new MyError())); // true + * ``` + * + * A value being `instanceof` a native error class is not equivalent to `isNativeError()` returning `true` for that value. `isNativeError()` returns `true` for errors + * which come from a different [realm](https://tc39.es/ecma262/#realm) while `instanceof Error` returns `false` for these errors: + * + * ```js + * const vm = require('node:vm'); + * const context = vm.createContext({}); + * const myError = vm.runInContext('new Error()', context); + * console.log(util.types.isNativeError(myError)); // true + * console.log(myError instanceof Error); // false + * ``` + * + * Conversely, `isNativeError()` returns `false` for all objects which were not + * returned by the constructor of a native error. That includes values + * which are `instanceof` native errors: + * + * ```js + * const myError = { __proto__: Error.prototype }; + * console.log(util.types.isNativeError(myError)); // false + * console.log(myError instanceof Error); // true + * ``` + * @since v10.0.0 + */ + function isNativeError(object: unknown): object is Error; + /** + * Returns `true` if the value is a number object, e.g. created + * by `new Number()`. + * + * ```js + * util.types.isNumberObject(0); // Returns false + * util.types.isNumberObject(new Number(0)); // Returns true + * ``` + * @since v10.0.0 + */ + function isNumberObject(object: unknown): object is Number; + /** + * Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * + * ```js + * util.types.isPromise(Promise.resolve(42)); // Returns true + * ``` + * @since v10.0.0 + */ + function isPromise(object: unknown): object is Promise; + /** + * Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance. + * + * ```js + * const target = {}; + * const proxy = new Proxy(target, {}); + * util.types.isProxy(target); // Returns false + * util.types.isProxy(proxy); // Returns true + * ``` + * @since v10.0.0 + */ + function isProxy(object: unknown): boolean; + /** + * Returns `true` if the value is a regular expression object. + * + * ```js + * util.types.isRegExp(/abc/); // Returns true + * util.types.isRegExp(new RegExp('abc')); // Returns true + * ``` + * @since v10.0.0 + */ + function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * util.types.isSet(new Set()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSet( + object: T | {}, + ): object is T extends ReadonlySet ? (unknown extends T ? never : ReadonlySet) : Set; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * const set = new Set(); + * util.types.isSetIterator(set.keys()); // Returns true + * util.types.isSetIterator(set.values()); // Returns true + * util.types.isSetIterator(set.entries()); // Returns true + * util.types.isSetIterator(set[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSetIterator(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * This does _not_ include [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false + * util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSharedArrayBuffer(object: unknown): object is SharedArrayBuffer; + /** + * Returns `true` if the value is a string object, e.g. created + * by `new String()`. + * + * ```js + * util.types.isStringObject('foo'); // Returns false + * util.types.isStringObject(new String('foo')); // Returns true + * ``` + * @since v10.0.0 + */ + function isStringObject(object: unknown): object is String; + /** + * Returns `true` if the value is a symbol object, created + * by calling `Object()` on a `Symbol` primitive. + * + * ```js + * const symbol = Symbol('foo'); + * util.types.isSymbolObject(symbol); // Returns false + * util.types.isSymbolObject(Object(symbol)); // Returns true + * ``` + * @since v10.0.0 + */ + function isSymbolObject(object: unknown): object is Symbol; + /** + * Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance. + * + * ```js + * util.types.isTypedArray(new ArrayBuffer()); // Returns false + * util.types.isTypedArray(new Uint8Array()); // Returns true + * util.types.isTypedArray(new Float64Array()); // Returns true + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isTypedArray(object: unknown): object is NodeJS.TypedArray; + /** + * Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance. + * + * ```js + * util.types.isUint8Array(new ArrayBuffer()); // Returns false + * util.types.isUint8Array(new Uint8Array()); // Returns true + * util.types.isUint8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8Array(object: unknown): object is Uint8Array; + /** + * Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance. + * + * ```js + * util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false + * util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true + * util.types.isUint8ClampedArray(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8ClampedArray(object: unknown): object is Uint8ClampedArray; + /** + * Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance. + * + * ```js + * util.types.isUint16Array(new ArrayBuffer()); // Returns false + * util.types.isUint16Array(new Uint16Array()); // Returns true + * util.types.isUint16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint16Array(object: unknown): object is Uint16Array; + /** + * Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance. + * + * ```js + * util.types.isUint32Array(new ArrayBuffer()); // Returns false + * util.types.isUint32Array(new Uint32Array()); // Returns true + * util.types.isUint32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint32Array(object: unknown): object is Uint32Array; + /** + * Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance. + * + * ```js + * util.types.isWeakMap(new WeakMap()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakMap(object: unknown): object is WeakMap; + /** + * Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance. + * + * ```js + * util.types.isWeakSet(new WeakSet()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakSet(object: unknown): object is WeakSet; + /** + * Returns `true` if `value` is a `KeyObject`, `false` otherwise. + * @since v16.2.0 + */ + function isKeyObject(object: unknown): object is KeyObject; + /** + * Returns `true` if `value` is a `CryptoKey`, `false` otherwise. + * @since v16.2.0 + */ + function isCryptoKey(object: unknown): object is webcrypto.CryptoKey; +} +declare module "node:util" { + export * from "util"; +} +declare module "node:util/types" { + export * from "util/types"; +} diff --git a/node_modules/@types/node/v8.d.ts b/node_modules/@types/node/v8.d.ts new file mode 100644 index 0000000..58b8bb3 --- /dev/null +++ b/node_modules/@types/node/v8.d.ts @@ -0,0 +1,808 @@ +/** + * The `node:v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: + * + * ```js + * const v8 = require('node:v8'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/v8.js) + */ +declare module "v8" { + import { Readable } from "node:stream"; + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + number_of_native_contexts: number; + number_of_detached_contexts: number; + total_global_handles_size: number; + used_global_handles_size: number; + external_memory: number; + } + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + interface HeapSnapshotOptions { + /** + * If true, expose internals in the heap snapshot. + * @default false + */ + exposeInternals?: boolean; + /** + * If true, expose numeric values in artificial fields. + * @default false + */ + exposeNumericValues?: boolean; + } + /** + * Returns an integer representing a version tag derived from the V8 version, + * command-line flags, and detected CPU features. This is useful for determining + * whether a `vm.Script` `cachedData` buffer is compatible with this instance + * of V8. + * + * ```js + * console.log(v8.cachedDataVersionTag()); // 3947234607 + * // The value returned by v8.cachedDataVersionTag() is derived from the V8 + * // version, command-line flags, and detected CPU features. Test that the value + * // does indeed update when flags are toggled. + * v8.setFlagsFromString('--allow_natives_syntax'); + * console.log(v8.cachedDataVersionTag()); // 183726201 + * ``` + * @since v8.0.0 + */ + function cachedDataVersionTag(): number; + /** + * Returns an object with the following properties: + * + * `does_zap_garbage` is a 0/1 boolean, which signifies whether the `--zap_code_space` option is enabled or not. This makes V8 overwrite heap + * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger + * because it continuously touches all heap pages and that makes them less likely + * to get swapped out by the operating system. + * + * `number_of_native_contexts` The value of native\_context is the number of the + * top-level contexts currently active. Increase of this number over time indicates + * a memory leak. + * + * `number_of_detached_contexts` The value of detached\_context is the number + * of contexts that were detached and not yet garbage collected. This number + * being non-zero indicates a potential memory leak. + * + * `total_global_handles_size` The value of total\_global\_handles\_size is the + * total memory size of V8 global handles. + * + * `used_global_handles_size` The value of used\_global\_handles\_size is the + * used memory size of V8 global handles. + * + * `external_memory` The value of external\_memory is the memory size of array + * buffers and external strings. + * + * ```js + * { + * total_heap_size: 7326976, + * total_heap_size_executable: 4194304, + * total_physical_size: 7326976, + * total_available_size: 1152656, + * used_heap_size: 3476208, + * heap_size_limit: 1535115264, + * malloced_memory: 16384, + * peak_malloced_memory: 1127496, + * does_zap_garbage: 0, + * number_of_native_contexts: 1, + * number_of_detached_contexts: 0, + * total_global_handles_size: 8192, + * used_global_handles_size: 3296, + * external_memory: 318824 + * } + * ``` + * @since v1.0.0 + */ + function getHeapStatistics(): HeapInfo; + /** + * Returns statistics about the V8 heap spaces, i.e. the segments which make up + * the V8 heap. Neither the ordering of heap spaces, nor the availability of a + * heap space can be guaranteed as the statistics are provided via the + * V8 [`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the + * next. + * + * The value returned is an array of objects containing the following properties: + * + * ```json + * [ + * { + * "space_name": "new_space", + * "space_size": 2063872, + * "space_used_size": 951112, + * "space_available_size": 80824, + * "physical_space_size": 2063872 + * }, + * { + * "space_name": "old_space", + * "space_size": 3090560, + * "space_used_size": 2493792, + * "space_available_size": 0, + * "physical_space_size": 3090560 + * }, + * { + * "space_name": "code_space", + * "space_size": 1260160, + * "space_used_size": 644256, + * "space_available_size": 960, + * "physical_space_size": 1260160 + * }, + * { + * "space_name": "map_space", + * "space_size": 1094160, + * "space_used_size": 201608, + * "space_available_size": 0, + * "physical_space_size": 1094160 + * }, + * { + * "space_name": "large_object_space", + * "space_size": 0, + * "space_used_size": 0, + * "space_available_size": 1490980608, + * "physical_space_size": 0 + * } + * ] + * ``` + * @since v6.0.0 + */ + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + /** + * The `v8.setFlagsFromString()` method can be used to programmatically set + * V8 command-line flags. This method should be used with care. Changing settings + * after the VM has started may result in unpredictable behavior, including + * crashes and data loss; or it may simply do nothing. + * + * The V8 options available for a version of Node.js may be determined by running `node --v8-options`. + * + * Usage: + * + * ```js + * // Print GC events to stdout for one minute. + * const v8 = require('node:v8'); + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ + function setFlagsFromString(flags: string): void; + /** + * This is similar to the [`queryObjects()` console API](https://developer.chrome.com/docs/devtools/console/utilities#queryObjects-function) + * provided by the Chromium DevTools console. It can be used to search for objects that have the matching constructor on its prototype chain + * in the heap after a full garbage collection, which can be useful for memory leak regression tests. To avoid surprising results, users should + * avoid using this API on constructors whose implementation they don't control, or on constructors that can be invoked by other parties in the + * application. + * + * To avoid accidental leaks, this API does not return raw references to the objects found. By default, it returns the count of the objects + * found. If `options.format` is `'summary'`, it returns an array containing brief string representations for each object. The visibility provided + * in this API is similar to what the heap snapshot provides, while users can save the cost of serialization and parsing and directly filter the + * target objects during the search. + * + * Only objects created in the current execution context are included in the results. + * + * ```js + * import { queryObjects } from 'node:v8'; + * class A { foo = 'bar'; } + * console.log(queryObjects(A)); // 0 + * const a = new A(); + * console.log(queryObjects(A)); // 1 + * // [ "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * + * class B extends A { bar = 'qux'; } + * const b = new B(); + * console.log(queryObjects(B)); // 1 + * // [ "B { foo: 'bar', bar: 'qux' }" ] + * console.log(queryObjects(B, { format: 'summary' })); + * + * // Note that, when there are child classes inheriting from a constructor, + * // the constructor also shows up in the prototype chain of the child + * // classes's prototoype, so the child classes's prototoype would also be + * // included in the result. + * console.log(queryObjects(A)); // 3 + * // [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * ``` + * @param ctor The constructor that can be used to search on the prototype chain in order to filter target objects in the heap. + * @since v20.13.0 + * @experimental + */ + function queryObjects(ctor: Function): number | string[]; + function queryObjects(ctor: Function, options: { format: "count" }): number; + function queryObjects(ctor: Function, options: { format: "summary" }): string[]; + /** + * Generates a snapshot of the current V8 heap and returns a Readable + * Stream that may be used to read the JSON serialized representation. + * This JSON stream format is intended to be used with tools such as + * Chrome DevTools. The JSON schema is undocumented and specific to the + * V8 engine. Therefore, the schema may change from one version of V8 to the next. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * // Print heap snapshot to the console + * const v8 = require('node:v8'); + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable containing the V8 heap snapshot. + */ + function getHeapSnapshot(options?: HeapSnapshotOptions): Readable; + /** + * Generates a snapshot of the current V8 heap and writes it to a JSON + * file. This file is intended to be used with tools such as Chrome + * DevTools. The JSON schema is undocumented and specific to the V8 + * engine, and may change from one version of V8 to the next. + * + * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will + * not contain any information about the workers, and vice versa. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * const { writeHeapSnapshot } = require('node:v8'); + * const { + * Worker, + * isMainThread, + * parentPort, + * } = require('node:worker_threads'); + * + * if (isMainThread) { + * const worker = new Worker(__filename); + * + * worker.once('message', (filename) => { + * console.log(`worker heapdump: ${filename}`); + * // Now get a heapdump for the main thread. + * console.log(`main thread heapdump: ${writeHeapSnapshot()}`); + * }); + * + * // Tell the worker to create a heapdump. + * worker.postMessage('heapdump'); + * } else { + * parentPort.once('message', (message) => { + * if (message === 'heapdump') { + * // Generate a heapdump for the worker + * // and return the filename to the parent. + * parentPort.postMessage(writeHeapSnapshot()); + * } + * }); + * } + * ``` + * @since v11.13.0 + * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be + * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a + * worker thread. + * @return The filename where the snapshot was saved. + */ + function writeHeapSnapshot(filename?: string, options?: HeapSnapshotOptions): string; + /** + * Get statistics about code and its metadata in the heap, see + * V8 [`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the + * following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794, + * cpu_profiler_metadata_size: 0, + * } + * ``` + * @since v12.8.0 + */ + function getHeapCodeStatistics(): HeapCodeStatistics; + /** + * @since v8.0.0 + */ + class Serializer { + /** + * Writes out a header, which includes the serialization format version. + */ + writeHeader(): void; + /** + * Serializes a JavaScript value and adds the serialized representation to the + * internal buffer. + * + * This throws an error if `value` cannot be serialized. + */ + writeValue(val: any): boolean; + /** + * Returns the stored internal buffer. This serializer should not be used once + * the buffer is released. Calling this method results in undefined behavior + * if a previous write has failed. + */ + releaseBuffer(): Buffer; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Write a raw 32-bit unsigned integer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint32(value: number): void; + /** + * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint64(hi: number, lo: number): void; + /** + * Write a JS `number` value. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeDouble(value: number): void; + /** + * Write raw bytes into the serializer's internal buffer. The deserializer + * will require a way to compute the length of the buffer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeRawBytes(buffer: NodeJS.TypedArray): void; + } + /** + * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only + * stores the part of their underlying `ArrayBuffer`s that they are referring to. + * @since v8.0.0 + */ + class DefaultSerializer extends Serializer {} + /** + * @since v8.0.0 + */ + class Deserializer { + constructor(data: NodeJS.TypedArray); + /** + * Reads and validates a header (including the format version). + * May, for example, reject an invalid or unsupported wire format. In that case, + * an `Error` is thrown. + */ + readHeader(): boolean; + /** + * Deserializes a JavaScript value from the buffer and returns it. + */ + readValue(): any; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of + * `SharedArrayBuffer`s). + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Reads the underlying wire format version. Likely mostly to be useful to + * legacy code reading old wire format versions. May not be called before `.readHeader()`. + */ + getWireFormatVersion(): number; + /** + * Read a raw 32-bit unsigned integer and return it. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint32(): number; + /** + * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]` with two 32-bit unsigned integer entries. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint64(): [number, number]; + /** + * Read a JS `number` value. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readDouble(): number; + /** + * Read raw bytes from the deserializer's internal buffer. The `length` parameter + * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readRawBytes(length: number): Buffer; + } + /** + * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`. + * @since v8.0.0 + */ + class DefaultDeserializer extends Deserializer {} + /** + * Uses a `DefaultSerializer` to serialize `value` into a buffer. + * + * `ERR_BUFFER_TOO_LARGE` will be thrown when trying to + * serialize a huge object which requires buffer + * larger than `buffer.constants.MAX_LENGTH`. + * @since v8.0.0 + */ + function serialize(value: any): Buffer; + /** + * Uses a `DefaultDeserializer` with default options to read a JS value + * from a buffer. + * @since v8.0.0 + * @param buffer A buffer returned by {@link serialize}. + */ + function deserialize(buffer: NodeJS.TypedArray): any; + /** + * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple + * times during the lifetime of the process. Each time the execution counter will + * be reset and a new coverage report will be written to the directory specified + * by `NODE_V8_COVERAGE`. + * + * When the process is about to exit, one last coverage will still be written to + * disk unless {@link stopCoverage} is invoked before the process exits. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function takeCoverage(): void; + /** + * The `v8.stopCoverage()` method allows the user to stop the coverage collection + * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count + * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function stopCoverage(): void; + /** + * The API is a no-op if `--heapsnapshot-near-heap-limit` is already set from the command line or the API is called more than once. + * `limit` must be a positive integer. See [`--heapsnapshot-near-heap-limit`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--heapsnapshot-near-heap-limitmax_count) for more information. + * @experimental + * @since v18.10.0, v16.18.0 + */ + function setHeapSnapshotNearHeapLimit(limit: number): void; + /** + * This API collects GC data in current thread. + * @since v19.6.0, v18.15.0 + */ + class GCProfiler { + /** + * Start collecting GC data. + * @since v19.6.0, v18.15.0 + */ + start(): void; + /** + * Stop collecting GC data and return an object. The content of object + * is as follows. + * + * ```json + * { + * "version": 1, + * "startTime": 1674059033862, + * "statistics": [ + * { + * "gcType": "Scavenge", + * "beforeGC": { + * "heapStatistics": { + * "totalHeapSize": 5005312, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5226496, + * "totalAvailableSize": 4341325216, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4883840, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * }, + * "cost": 1574.14, + * "afterGC": { + * "heapStatistics": { + * "totalHeapSize": 6053888, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5500928, + * "totalAvailableSize": 4341101384, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4059096, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * } + * } + * ], + * "endTime": 1674059036865 + * } + * ``` + * + * Here's an example. + * + * ```js + * const { GCProfiler } = require('v8'); + * const profiler = new GCProfiler(); + * profiler.start(); + * setTimeout(() => { + * console.log(profiler.stop()); + * }, 1000); + * ``` + * @since v19.6.0, v18.15.0 + */ + stop(): GCProfilerResult; + } + interface GCProfilerResult { + version: number; + startTime: number; + endTime: number; + statistics: Array<{ + gcType: string; + cost: number; + beforeGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + afterGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + }>; + } + interface HeapStatistics { + totalHeapSize: number; + totalHeapSizeExecutable: number; + totalPhysicalSize: number; + totalAvailableSize: number; + totalGlobalHandlesSize: number; + usedGlobalHandlesSize: number; + usedHeapSize: number; + heapSizeLimit: number; + mallocedMemory: number; + externalMemory: number; + peakMallocedMemory: number; + } + interface HeapSpaceStatistics { + spaceName: string; + spaceSize: number; + spaceUsedSize: number; + spaceAvailableSize: number; + physicalSpaceSize: number; + } + /** + * Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will + * happen if a promise is created without ever getting a continuation. + * @since v17.1.0, v16.14.0 + * @param promise The promise being created. + * @param parent The promise continued from, if applicable. + */ + interface Init { + (promise: Promise, parent: Promise): void; + } + /** + * Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming. + * + * The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise. + * The before callback may be called many times in the case where many continuations have been made from the same promise. + * @since v17.1.0, v16.14.0 + */ + interface Before { + (promise: Promise): void; + } + /** + * Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await. + * @since v17.1.0, v16.14.0 + */ + interface After { + (promise: Promise): void; + } + /** + * Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or + * {@link Promise.reject()}. + * @since v17.1.0, v16.14.0 + */ + interface Settled { + (promise: Promise): void; + } + /** + * Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or + * around an await, and when the promise resolves or rejects. + * + * Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and + * `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop. + * @since v17.1.0, v16.14.0 + */ + interface HookCallbacks { + init?: Init; + before?: Before; + after?: After; + settled?: Settled; + } + interface PromiseHooks { + /** + * The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param init The {@link Init | `init` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onInit: (init: Init) => Function; + /** + * The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param settled The {@link Settled | `settled` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onSettled: (settled: Settled) => Function; + /** + * The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param before The {@link Before | `before` callback} to call before a promise continuation executes. + * @return Call to stop the hook. + */ + onBefore: (before: Before) => Function; + /** + * The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param after The {@link After | `after` callback} to call after a promise continuation executes. + * @return Call to stop the hook. + */ + onAfter: (after: After) => Function; + /** + * Registers functions to be called for different lifetime events of each promise. + * The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime. + * All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed. + * The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param callbacks The {@link HookCallbacks | Hook Callbacks} to register + * @return Used for disabling hooks + */ + createHook: (callbacks: HookCallbacks) => Function; + } + /** + * The `promiseHooks` interface can be used to track promise lifecycle events. + * @since v17.1.0, v16.14.0 + */ + const promiseHooks: PromiseHooks; + type StartupSnapshotCallbackFn = (args: any) => any; + interface StartupSnapshot { + /** + * Add a callback that will be called when the Node.js instance is about to get serialized into a snapshot and exit. + * This can be used to release resources that should not or cannot be serialized or to convert user data into a form more suitable for serialization. + * @since v18.6.0, v16.17.0 + */ + addSerializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Add a callback that will be called when the Node.js instance is deserialized from a snapshot. + * The `callback` and the `data` (if provided) will be serialized into the snapshot, they can be used to re-initialize the state of the application or + * to re-acquire resources that the application needs when the application is restarted from the snapshot. + * @since v18.6.0, v16.17.0 + */ + addDeserializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * This sets the entry point of the Node.js application when it is deserialized from a snapshot. This can be called only once in the snapshot building script. + * If called, the deserialized application no longer needs an additional entry point script to start up and will simply invoke the callback along with the deserialized + * data (if provided), otherwise an entry point script still needs to be provided to the deserialized application. + * @since v18.6.0, v16.17.0 + */ + setDeserializeMainFunction(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Returns true if the Node.js instance is run to build a snapshot. + * @since v18.6.0, v16.17.0 + */ + isBuildingSnapshot(): boolean; + } + /** + * The `v8.startupSnapshot` interface can be used to add serialization and deserialization hooks for custom startup snapshots. + * + * ```bash + * $ node --snapshot-blob snapshot.blob --build-snapshot entry.js + * # This launches a process with the snapshot + * $ node --snapshot-blob snapshot.blob + * ``` + * + * In the example above, `entry.js` can use methods from the `v8.startupSnapshot` interface to specify how to save information for custom objects + * in the snapshot during serialization and how the information can be used to synchronize these objects during deserialization of the snapshot. + * For example, if the `entry.js` contains the following script: + * + * ```js + * 'use strict'; + * + * const fs = require('node:fs'); + * const zlib = require('node:zlib'); + * const path = require('node:path'); + * const assert = require('node:assert'); + * + * const v8 = require('node:v8'); + * + * class BookShelf { + * storage = new Map(); + * + * // Reading a series of files from directory and store them into storage. + * constructor(directory, books) { + * for (const book of books) { + * this.storage.set(book, fs.readFileSync(path.join(directory, book))); + * } + * } + * + * static compressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gzipSync(content)); + * } + * } + * + * static decompressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gunzipSync(content)); + * } + * } + * } + * + * // __dirname here is where the snapshot script is placed + * // during snapshot building time. + * const shelf = new BookShelf(__dirname, [ + * 'book1.en_US.txt', + * 'book1.es_ES.txt', + * 'book2.zh_CN.txt', + * ]); + * + * assert(v8.startupSnapshot.isBuildingSnapshot()); + * // On snapshot serialization, compress the books to reduce size. + * v8.startupSnapshot.addSerializeCallback(BookShelf.compressAll, shelf); + * // On snapshot deserialization, decompress the books. + * v8.startupSnapshot.addDeserializeCallback(BookShelf.decompressAll, shelf); + * v8.startupSnapshot.setDeserializeMainFunction((shelf) => { + * // process.env and process.argv are refreshed during snapshot + * // deserialization. + * const lang = process.env.BOOK_LANG || 'en_US'; + * const book = process.argv[1]; + * const name = `${book}.${lang}.txt`; + * console.log(shelf.storage.get(name)); + * }, shelf); + * ``` + * + * The resulted binary will get print the data deserialized from the snapshot during start up, using the refreshed `process.env` and `process.argv` of the launched process: + * + * ```bash + * $ BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1 + * # Prints content of book1.es_ES.txt deserialized from the snapshot. + * ``` + * + * Currently the application deserialized from a user-land snapshot cannot be snapshotted again, so these APIs are only available to applications that are not deserialized from a user-land snapshot. + * + * @experimental + * @since v18.6.0, v16.17.0 + */ + const startupSnapshot: StartupSnapshot; +} +declare module "node:v8" { + export * from "v8"; +} diff --git a/node_modules/@types/node/vm.d.ts b/node_modules/@types/node/vm.d.ts new file mode 100644 index 0000000..82d53a5 --- /dev/null +++ b/node_modules/@types/node/vm.d.ts @@ -0,0 +1,922 @@ +/** + * The `node:vm` module enables compiling and running code within V8 Virtual + * Machine contexts. + * + * **The `node:vm` module is not a security** + * **mechanism. Do not use it to run untrusted code.** + * + * JavaScript code can be compiled and run immediately or + * compiled, saved, and run later. + * + * A common use case is to run the code in a different V8 Context. This means + * invoked code has a different global object than the invoking code. + * + * One can provide the context by `contextifying` an + * object. The invoked code treats any property in the context like a + * global variable. Any changes to global variables caused by the invoked + * code are reflected in the context object. + * + * ```js + * const vm = require('node:vm'); + * + * const x = 1; + * + * const context = { x: 2 }; + * vm.createContext(context); // Contextify the object. + * + * const code = 'x += 40; var y = 17;'; + * // `x` and `y` are global variables in the context. + * // Initially, x has the value 2 because that is the value of context.x. + * vm.runInContext(code, context); + * + * console.log(context.x); // 42 + * console.log(context.y); // 17 + * + * console.log(x); // 1; y is not defined. + * ``` + * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/vm.js) + */ +declare module "vm" { + import { ImportAttributes } from "node:module"; + interface Context extends NodeJS.Dict {} + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * @default '' + */ + filename?: string | undefined; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + lineOffset?: number | undefined; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + columnOffset?: number | undefined; + } + interface ScriptOptions extends BaseOptions { + /** + * V8's code cache data for the supplied source. + */ + cachedData?: Buffer | NodeJS.ArrayBufferView | undefined; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean | undefined; + /** + * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is + * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see + * [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v22.x/api/vm.html#support-of-dynamic-import-in-compilation-apis). + */ + importModuleDynamically?: + | ((specifier: string, script: Script, importAttributes: ImportAttributes) => Module) + | typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER + | undefined; + } + interface RunningScriptOptions extends BaseOptions { + /** + * When `true`, if an `Error` occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. + * @default true + */ + displayErrors?: boolean | undefined; + /** + * Specifies the number of milliseconds to execute code before terminating execution. + * If execution is terminated, an `Error` will be thrown. This value must be a strictly positive integer. + */ + timeout?: number | undefined; + /** + * If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. + * Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. + * If execution is terminated, an `Error` will be thrown. + * @default false + */ + breakOnSigint?: boolean | undefined; + } + interface RunningScriptInNewContextOptions extends RunningScriptOptions { + /** + * Human-readable name of the newly created context. + */ + contextName?: CreateContextOptions["name"]; + /** + * Origin corresponding to the newly created context for display purposes. The origin should be formatted like a URL, + * but with only the scheme, host, and port (if necessary), like the value of the `url.origin` property of a `URL` object. + * Most notably, this string should omit the trailing slash, as that denotes a path. + */ + contextOrigin?: CreateContextOptions["origin"]; + contextCodeGeneration?: CreateContextOptions["codeGeneration"]; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: CreateContextOptions["microtaskMode"]; + } + interface RunningCodeOptions extends RunningScriptOptions { + cachedData?: ScriptOptions["cachedData"]; + importModuleDynamically?: ScriptOptions["importModuleDynamically"]; + } + interface RunningCodeInNewContextOptions extends RunningScriptInNewContextOptions { + cachedData?: ScriptOptions["cachedData"]; + importModuleDynamically?: ScriptOptions["importModuleDynamically"]; + } + interface CompileFunctionOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer | undefined; + /** + * Specifies whether to produce new cache data. + * @default false + */ + produceCachedData?: boolean | undefined; + /** + * The sandbox/context in which the said function should be compiled in. + */ + parsingContext?: Context | undefined; + /** + * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling + */ + contextExtensions?: Object[] | undefined; + } + interface CreateContextOptions { + /** + * Human-readable name of the newly created context. + * @default 'VM Context i' Where i is an ascending numerical index of the created context. + */ + name?: string | undefined; + /** + * Corresponds to the newly created context for display purposes. + * The origin should be formatted like a `URL`, but with only the scheme, host, and port (if necessary), + * like the value of the `url.origin` property of a URL object. + * Most notably, this string should omit the trailing slash, as that denotes a path. + * @default '' + */ + origin?: string | undefined; + codeGeneration?: + | { + /** + * If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc) + * will throw an EvalError. + * @default true + */ + strings?: boolean | undefined; + /** + * If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError. + * @default true + */ + wasm?: boolean | undefined; + } + | undefined; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: "afterEvaluate" | undefined; + } + type MeasureMemoryMode = "summary" | "detailed"; + interface MeasureMemoryOptions { + /** + * @default 'summary' + */ + mode?: MeasureMemoryMode | undefined; + /** + * @default 'default' + */ + execution?: "default" | "eager" | undefined; + } + interface MemoryMeasurement { + total: { + jsMemoryEstimate: number; + jsMemoryRange: [number, number]; + }; + } + /** + * Instances of the `vm.Script` class contain precompiled scripts that can be + * executed in specific contexts. + * @since v0.3.1 + */ + class Script { + constructor(code: string, options?: ScriptOptions | string); + /** + * Runs the compiled code contained by the `vm.Script` object within the given `contextifiedObject` and returns the result. Running code does not have access + * to local scope. + * + * The following example compiles code that increments a global variable, sets + * the value of another global variable, then execute the code multiple times. + * The globals are contained in the `context` object. + * + * ```js + * const vm = require('node:vm'); + * + * const context = { + * animal: 'cat', + * count: 2, + * }; + * + * const script = new vm.Script('count += 1; name = "kitty";'); + * + * vm.createContext(context); + * for (let i = 0; i < 10; ++i) { + * script.runInContext(context); + * } + * + * console.log(context); + * // Prints: { animal: 'cat', count: 12, name: 'kitty' } + * ``` + * + * Using the `timeout` or `breakOnSigint` options will result in new event loops + * and corresponding threads being started, which have a non-zero performance + * overhead. + * @since v0.3.1 + * @param contextifiedObject A `contextified` object as returned by the `vm.createContext()` method. + * @return the result of the very last statement executed in the script. + */ + runInContext(contextifiedObject: Context, options?: RunningScriptOptions): any; + /** + * First contextifies the given `contextObject`, runs the compiled code contained + * by the `vm.Script` object within the created context, and returns the result. + * Running code does not have access to local scope. + * + * The following example compiles code that sets a global variable, then executes + * the code multiple times in different contexts. The globals are set on and + * contained within each individual `context`. + * + * ```js + * const vm = require('node:vm'); + * + * const script = new vm.Script('globalVar = "set"'); + * + * const contexts = [{}, {}, {}]; + * contexts.forEach((context) => { + * script.runInNewContext(context); + * }); + * + * console.log(contexts); + * // Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] + * ``` + * @since v0.3.1 + * @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created. + * @return the result of the very last statement executed in the script. + */ + runInNewContext(contextObject?: Context, options?: RunningScriptInNewContextOptions): any; + /** + * Runs the compiled code contained by the `vm.Script` within the context of the + * current `global` object. Running code does not have access to local scope, but _does_ have access to the current `global` object. + * + * The following example compiles code that increments a `global` variable then + * executes that code multiple times: + * + * ```js + * const vm = require('node:vm'); + * + * global.globalVar = 0; + * + * const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); + * + * for (let i = 0; i < 1000; ++i) { + * script.runInThisContext(); + * } + * + * console.log(globalVar); + * + * // 1000 + * ``` + * @since v0.3.1 + * @return the result of the very last statement executed in the script. + */ + runInThisContext(options?: RunningScriptOptions): any; + /** + * Creates a code cache that can be used with the `Script` constructor's `cachedData` option. Returns a `Buffer`. This method may be called at any + * time and any number of times. + * + * The code cache of the `Script` doesn't contain any JavaScript observable + * states. The code cache is safe to be saved along side the script source and + * used to construct new `Script` instances multiple times. + * + * Functions in the `Script` source can be marked as lazily compiled and they are + * not compiled at construction of the `Script`. These functions are going to be + * compiled when they are invoked the first time. The code cache serializes the + * metadata that V8 currently knows about the `Script` that it can use to speed up + * future compilations. + * + * ```js + * const script = new vm.Script(` + * function add(a, b) { + * return a + b; + * } + * + * const x = add(1, 2); + * `); + * + * const cacheWithoutAdd = script.createCachedData(); + * // In `cacheWithoutAdd` the function `add()` is marked for full compilation + * // upon invocation. + * + * script.runInThisContext(); + * + * const cacheWithAdd = script.createCachedData(); + * // `cacheWithAdd` contains fully compiled function `add()`. + * ``` + * @since v10.6.0 + */ + createCachedData(): Buffer; + /** @deprecated in favor of `script.createCachedData()` */ + cachedDataProduced?: boolean | undefined; + /** + * When `cachedData` is supplied to create the `vm.Script`, this value will be set + * to either `true` or `false` depending on acceptance of the data by V8. + * Otherwise the value is `undefined`. + * @since v5.7.0 + */ + cachedDataRejected?: boolean | undefined; + cachedData?: Buffer | undefined; + /** + * When the script is compiled from a source that contains a source map magic + * comment, this property will be set to the URL of the source map. + * + * ```js + * import vm from 'node:vm'; + * + * const script = new vm.Script(` + * function myFunc() {} + * //# sourceMappingURL=sourcemap.json + * `); + * + * console.log(script.sourceMapURL); + * // Prints: sourcemap.json + * ``` + * @since v19.1.0, v18.13.0 + */ + sourceMapURL?: string | undefined; + } + /** + * If given a `contextObject`, the `vm.createContext()` method will + * [prepare that object](https://nodejs.org/docs/latest-v22.x/api/vm.html#what-does-it-mean-to-contextify-an-object) + * and return a reference to it so that it can be used in `{@link runInContext}` or + * [`script.runInContext()`](https://nodejs.org/docs/latest-v22.x/api/vm.html#scriptrunincontextcontextifiedobject-options). Inside such + * scripts, the `contextObject` will be the global object, retaining all of its + * existing properties but also having the built-in objects and functions any + * standard [global object](https://es5.github.io/#x15.1) has. Outside of scripts run by the vm module, global + * variables will remain unchanged. + * + * ```js + * const vm = require('node:vm'); + * + * global.globalVar = 3; + * + * const context = { globalVar: 1 }; + * vm.createContext(context); + * + * vm.runInContext('globalVar *= 2;', context); + * + * console.log(context); + * // Prints: { globalVar: 2 } + * + * console.log(global.globalVar); + * // Prints: 3 + * ``` + * + * If `contextObject` is omitted (or passed explicitly as `undefined`), a new, + * empty `contextified` object will be returned. + * + * The `vm.createContext()` method is primarily useful for creating a single + * context that can be used to run multiple scripts. For instance, if emulating a + * web browser, the method can be used to create a single context representing a + * window's global object, then run all ` +``` + +#### Modules +```html + +``` + +## API +The JSON5 API is compatible with the [JSON API]. + +[JSON API]: +https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON + +### JSON5.parse() +Parses a JSON5 string, constructing the JavaScript value or object described by +the string. An optional reviver function can be provided to perform a +transformation on the resulting object before it is returned. + +#### Syntax + JSON5.parse(text[, reviver]) + +#### Parameters +- `text`: The string to parse as JSON5. +- `reviver`: If a function, this prescribes how the value originally produced by + parsing is transformed, before being returned. + +#### Return value +The object corresponding to the given JSON5 text. + +### JSON5.stringify() +Converts a JavaScript value to a JSON5 string, optionally replacing values if a +replacer function is specified, or optionally including only the specified +properties if a replacer array is specified. + +#### Syntax + JSON5.stringify(value[, replacer[, space]]) + JSON5.stringify(value[, options]) + +#### Parameters +- `value`: The value to convert to a JSON5 string. +- `replacer`: A function that alters the behavior of the stringification + process, or an array of String and Number objects that serve as a whitelist + for selecting/filtering the properties of the value object to be included in + the JSON5 string. If this value is null or not provided, all properties of the + object are included in the resulting JSON5 string. +- `space`: A String or Number object that's used to insert white space into the + output JSON5 string for readability purposes. If this is a Number, it + indicates the number of space characters to use as white space; this number is + capped at 10 (if it is greater, the value is just 10). Values less than 1 + indicate that no space should be used. If this is a String, the string (or the + first 10 characters of the string, if it's longer than that) is used as white + space. If this parameter is not provided (or is null), no white space is used. + If white space is used, trailing commas will be used in objects and arrays. +- `options`: An object with the following properties: + - `replacer`: Same as the `replacer` parameter. + - `space`: Same as the `space` parameter. + - `quote`: A String representing the quote character to use when serializing + strings. + +#### Return value +A JSON5 string representing the value. + +### Node.js `require()` JSON5 files +When using Node.js, you can `require()` JSON5 files by adding the following +statement. + +```js +require('json5/lib/register') +``` + +Then you can load a JSON5 file with a Node.js `require()` statement. For +example: + +```js +const config = require('./config.json5') +``` + +## CLI +Since JSON is more widely used than JSON5, this package includes a CLI for +converting JSON5 to JSON and for validating the syntax of JSON5 documents. + +### Installation +```sh +npm install --global json5 +``` + +### Usage +```sh +json5 [options] +``` + +If `` is not provided, then STDIN is used. + +#### Options: +- `-s`, `--space`: The number of spaces to indent or `t` for tabs +- `-o`, `--out-file [file]`: Output to the specified file, otherwise STDOUT +- `-v`, `--validate`: Validate JSON5 but do not output JSON +- `-V`, `--version`: Output the version number +- `-h`, `--help`: Output usage information + +## Contributing +### Development +```sh +git clone https://github.com/json5/json5 +cd json5 +npm install +``` + +When contributing code, please write relevant tests and run `npm test` and `npm +run lint` before submitting pull requests. Please use an editor that supports +[EditorConfig](http://editorconfig.org/). + +### Issues +To report bugs or request features regarding the JSON5 **data format**, +please submit an issue to the official +**[_specification_ repository](https://github.com/json5/json5-spec)**. + +Note that we will never add any features that make JSON5 incompatible with ES5; +that compatibility is a fundamental premise of JSON5. + +To report bugs or request features regarding this **JavaScript implementation** +of JSON5, please submit an issue to **_this_ repository**. + +### Security Vulnerabilities and Disclosures +To report a security vulnerability, please follow the follow the guidelines +described in our [security policy](./SECURITY.md). + +## License +MIT. See [LICENSE.md](./LICENSE.md) for details. + +## Credits +[Aseem Kishore](https://github.com/aseemk) founded this project. +He wrote a [blog post](https://aseemk.substack.com/p/ignore-the-f-ing-haters-json5) +about the journey and lessons learned 10 years in. + +[Michael Bolin](http://bolinfest.com/) independently arrived at and published +some of these same ideas with awesome explanations and detail. Recommended +reading: [Suggested Improvements to JSON](http://bolinfest.com/essays/json.html) + +[Douglas Crockford](http://www.crockford.com/) of course designed and built +JSON, but his state machine diagrams on the [JSON website](http://json.org/), as +cheesy as it may sound, gave us motivation and confidence that building a new +parser to implement these ideas was within reach! The original +implementation of JSON5 was also modeled directly off of Doug’s open-source +[json_parse.js] parser. We’re grateful for that clean and well-documented +code. + +[json_parse.js]: +https://github.com/douglascrockford/JSON-js/blob/03157639c7a7cddd2e9f032537f346f1a87c0f6d/json_parse.js + +[Max Nanasy](https://github.com/MaxNanasy) has been an early and prolific +supporter, contributing multiple patches and ideas. + +[Andrew Eisenberg](https://github.com/aeisenberg) contributed the original +`stringify` method. + +[Jordan Tucker](https://github.com/jordanbtucker) has aligned JSON5 more closely +with ES5, wrote the official JSON5 specification, completely rewrote the +codebase from the ground up, and is actively maintaining this project. diff --git a/node_modules/json5/dist/index.js b/node_modules/json5/dist/index.js new file mode 100644 index 0000000..bf86533 --- /dev/null +++ b/node_modules/json5/dist/index.js @@ -0,0 +1,1737 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.JSON5 = factory()); +}(this, (function () { 'use strict'; + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + var _global = createCommonjsModule(function (module) { + // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 + var global = module.exports = typeof window != 'undefined' && window.Math == Math + ? window : typeof self != 'undefined' && self.Math == Math ? self + // eslint-disable-next-line no-new-func + : Function('return this')(); + if (typeof __g == 'number') { __g = global; } // eslint-disable-line no-undef + }); + + var _core = createCommonjsModule(function (module) { + var core = module.exports = { version: '2.6.5' }; + if (typeof __e == 'number') { __e = core; } // eslint-disable-line no-undef + }); + var _core_1 = _core.version; + + var _isObject = function (it) { + return typeof it === 'object' ? it !== null : typeof it === 'function'; + }; + + var _anObject = function (it) { + if (!_isObject(it)) { throw TypeError(it + ' is not an object!'); } + return it; + }; + + var _fails = function (exec) { + try { + return !!exec(); + } catch (e) { + return true; + } + }; + + // Thank's IE8 for his funny defineProperty + var _descriptors = !_fails(function () { + return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; + }); + + var document = _global.document; + // typeof document.createElement is 'object' in old IE + var is = _isObject(document) && _isObject(document.createElement); + var _domCreate = function (it) { + return is ? document.createElement(it) : {}; + }; + + var _ie8DomDefine = !_descriptors && !_fails(function () { + return Object.defineProperty(_domCreate('div'), 'a', { get: function () { return 7; } }).a != 7; + }); + + // 7.1.1 ToPrimitive(input [, PreferredType]) + + // instead of the ES6 spec version, we didn't implement @@toPrimitive case + // and the second argument - flag - preferred type is a string + var _toPrimitive = function (it, S) { + if (!_isObject(it)) { return it; } + var fn, val; + if (S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) { return val; } + if (typeof (fn = it.valueOf) == 'function' && !_isObject(val = fn.call(it))) { return val; } + if (!S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) { return val; } + throw TypeError("Can't convert object to primitive value"); + }; + + var dP = Object.defineProperty; + + var f = _descriptors ? Object.defineProperty : function defineProperty(O, P, Attributes) { + _anObject(O); + P = _toPrimitive(P, true); + _anObject(Attributes); + if (_ie8DomDefine) { try { + return dP(O, P, Attributes); + } catch (e) { /* empty */ } } + if ('get' in Attributes || 'set' in Attributes) { throw TypeError('Accessors not supported!'); } + if ('value' in Attributes) { O[P] = Attributes.value; } + return O; + }; + + var _objectDp = { + f: f + }; + + var _propertyDesc = function (bitmap, value) { + return { + enumerable: !(bitmap & 1), + configurable: !(bitmap & 2), + writable: !(bitmap & 4), + value: value + }; + }; + + var _hide = _descriptors ? function (object, key, value) { + return _objectDp.f(object, key, _propertyDesc(1, value)); + } : function (object, key, value) { + object[key] = value; + return object; + }; + + var hasOwnProperty = {}.hasOwnProperty; + var _has = function (it, key) { + return hasOwnProperty.call(it, key); + }; + + var id = 0; + var px = Math.random(); + var _uid = function (key) { + return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); + }; + + var _library = false; + + var _shared = createCommonjsModule(function (module) { + var SHARED = '__core-js_shared__'; + var store = _global[SHARED] || (_global[SHARED] = {}); + + (module.exports = function (key, value) { + return store[key] || (store[key] = value !== undefined ? value : {}); + })('versions', []).push({ + version: _core.version, + mode: _library ? 'pure' : 'global', + copyright: '© 2019 Denis Pushkarev (zloirock.ru)' + }); + }); + + var _functionToString = _shared('native-function-to-string', Function.toString); + + var _redefine = createCommonjsModule(function (module) { + var SRC = _uid('src'); + + var TO_STRING = 'toString'; + var TPL = ('' + _functionToString).split(TO_STRING); + + _core.inspectSource = function (it) { + return _functionToString.call(it); + }; + + (module.exports = function (O, key, val, safe) { + var isFunction = typeof val == 'function'; + if (isFunction) { _has(val, 'name') || _hide(val, 'name', key); } + if (O[key] === val) { return; } + if (isFunction) { _has(val, SRC) || _hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); } + if (O === _global) { + O[key] = val; + } else if (!safe) { + delete O[key]; + _hide(O, key, val); + } else if (O[key]) { + O[key] = val; + } else { + _hide(O, key, val); + } + // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative + })(Function.prototype, TO_STRING, function toString() { + return typeof this == 'function' && this[SRC] || _functionToString.call(this); + }); + }); + + var _aFunction = function (it) { + if (typeof it != 'function') { throw TypeError(it + ' is not a function!'); } + return it; + }; + + // optional / simple context binding + + var _ctx = function (fn, that, length) { + _aFunction(fn); + if (that === undefined) { return fn; } + switch (length) { + case 1: return function (a) { + return fn.call(that, a); + }; + case 2: return function (a, b) { + return fn.call(that, a, b); + }; + case 3: return function (a, b, c) { + return fn.call(that, a, b, c); + }; + } + return function (/* ...args */) { + return fn.apply(that, arguments); + }; + }; + + var PROTOTYPE = 'prototype'; + + var $export = function (type, name, source) { + var IS_FORCED = type & $export.F; + var IS_GLOBAL = type & $export.G; + var IS_STATIC = type & $export.S; + var IS_PROTO = type & $export.P; + var IS_BIND = type & $export.B; + var target = IS_GLOBAL ? _global : IS_STATIC ? _global[name] || (_global[name] = {}) : (_global[name] || {})[PROTOTYPE]; + var exports = IS_GLOBAL ? _core : _core[name] || (_core[name] = {}); + var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}); + var key, own, out, exp; + if (IS_GLOBAL) { source = name; } + for (key in source) { + // contains in native + own = !IS_FORCED && target && target[key] !== undefined; + // export native or passed + out = (own ? target : source)[key]; + // bind timers to global for call from export context + exp = IS_BIND && own ? _ctx(out, _global) : IS_PROTO && typeof out == 'function' ? _ctx(Function.call, out) : out; + // extend global + if (target) { _redefine(target, key, out, type & $export.U); } + // export + if (exports[key] != out) { _hide(exports, key, exp); } + if (IS_PROTO && expProto[key] != out) { expProto[key] = out; } + } + }; + _global.core = _core; + // type bitmap + $export.F = 1; // forced + $export.G = 2; // global + $export.S = 4; // static + $export.P = 8; // proto + $export.B = 16; // bind + $export.W = 32; // wrap + $export.U = 64; // safe + $export.R = 128; // real proto method for `library` + var _export = $export; + + // 7.1.4 ToInteger + var ceil = Math.ceil; + var floor = Math.floor; + var _toInteger = function (it) { + return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); + }; + + // 7.2.1 RequireObjectCoercible(argument) + var _defined = function (it) { + if (it == undefined) { throw TypeError("Can't call method on " + it); } + return it; + }; + + // true -> String#at + // false -> String#codePointAt + var _stringAt = function (TO_STRING) { + return function (that, pos) { + var s = String(_defined(that)); + var i = _toInteger(pos); + var l = s.length; + var a, b; + if (i < 0 || i >= l) { return TO_STRING ? '' : undefined; } + a = s.charCodeAt(i); + return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff + ? TO_STRING ? s.charAt(i) : a + : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; + }; + }; + + var $at = _stringAt(false); + _export(_export.P, 'String', { + // 21.1.3.3 String.prototype.codePointAt(pos) + codePointAt: function codePointAt(pos) { + return $at(this, pos); + } + }); + + var codePointAt = _core.String.codePointAt; + + var max = Math.max; + var min = Math.min; + var _toAbsoluteIndex = function (index, length) { + index = _toInteger(index); + return index < 0 ? max(index + length, 0) : min(index, length); + }; + + var fromCharCode = String.fromCharCode; + var $fromCodePoint = String.fromCodePoint; + + // length should be 1, old FF problem + _export(_export.S + _export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', { + // 21.1.2.2 String.fromCodePoint(...codePoints) + fromCodePoint: function fromCodePoint(x) { + var arguments$1 = arguments; + // eslint-disable-line no-unused-vars + var res = []; + var aLen = arguments.length; + var i = 0; + var code; + while (aLen > i) { + code = +arguments$1[i++]; + if (_toAbsoluteIndex(code, 0x10ffff) !== code) { throw RangeError(code + ' is not a valid code point'); } + res.push(code < 0x10000 + ? fromCharCode(code) + : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) + ); + } return res.join(''); + } + }); + + var fromCodePoint = _core.String.fromCodePoint; + + // This is a generated file. Do not edit. + var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/; + var ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7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72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/; + var ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\u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\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\u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\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/; + + var unicode = { + Space_Separator: Space_Separator, + ID_Start: ID_Start, + ID_Continue: ID_Continue + }; + + var util = { + isSpaceSeparator: function isSpaceSeparator (c) { + return typeof c === 'string' && unicode.Space_Separator.test(c) + }, + + isIdStartChar: function isIdStartChar (c) { + return typeof c === 'string' && ( + (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c === '$') || (c === '_') || + unicode.ID_Start.test(c) + ) + }, + + isIdContinueChar: function isIdContinueChar (c) { + return typeof c === 'string' && ( + (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || + (c === '$') || (c === '_') || + (c === '\u200C') || (c === '\u200D') || + unicode.ID_Continue.test(c) + ) + }, + + isDigit: function isDigit (c) { + return typeof c === 'string' && /[0-9]/.test(c) + }, + + isHexDigit: function isHexDigit (c) { + return typeof c === 'string' && /[0-9A-Fa-f]/.test(c) + }, + }; + + var source; + var parseState; + var stack; + var pos; + var line; + var column; + var token; + var key; + var root; + + var parse = function parse (text, reviver) { + source = String(text); + parseState = 'start'; + stack = []; + pos = 0; + line = 1; + column = 0; + token = undefined; + key = undefined; + root = undefined; + + do { + token = lex(); + + // This code is unreachable. + // if (!parseStates[parseState]) { + // throw invalidParseState() + // } + + parseStates[parseState](); + } while (token.type !== 'eof') + + if (typeof reviver === 'function') { + return internalize({'': root}, '', reviver) + } + + return root + }; + + function internalize (holder, name, reviver) { + var value = holder[name]; + if (value != null && typeof value === 'object') { + if (Array.isArray(value)) { + for (var i = 0; i < value.length; i++) { + var key = String(i); + var replacement = internalize(value, key, reviver); + if (replacement === undefined) { + delete value[key]; + } else { + Object.defineProperty(value, key, { + value: replacement, + writable: true, + enumerable: true, + configurable: true, + }); + } + } + } else { + for (var key$1 in value) { + var replacement$1 = internalize(value, key$1, reviver); + if (replacement$1 === undefined) { + delete value[key$1]; + } else { + Object.defineProperty(value, key$1, { + value: replacement$1, + writable: true, + enumerable: true, + configurable: true, + }); + } + } + } + } + + return reviver.call(holder, name, value) + } + + var lexState; + var buffer; + var doubleQuote; + var sign; + var c; + + function lex () { + lexState = 'default'; + buffer = ''; + doubleQuote = false; + sign = 1; + + for (;;) { + c = peek(); + + // This code is unreachable. + // if (!lexStates[lexState]) { + // throw invalidLexState(lexState) + // } + + var token = lexStates[lexState](); + if (token) { + return token + } + } + } + + function peek () { + if (source[pos]) { + return String.fromCodePoint(source.codePointAt(pos)) + } + } + + function read () { + var c = peek(); + + if (c === '\n') { + line++; + column = 0; + } else if (c) { + column += c.length; + } else { + column++; + } + + if (c) { + pos += c.length; + } + + return c + } + + var lexStates = { + default: function default$1 () { + switch (c) { + case '\t': + case '\v': + case '\f': + case ' ': + case '\u00A0': + case '\uFEFF': + case '\n': + case '\r': + case '\u2028': + case '\u2029': + read(); + return + + case '/': + read(); + lexState = 'comment'; + return + + case undefined: + read(); + return newToken('eof') + } + + if (util.isSpaceSeparator(c)) { + read(); + return + } + + // This code is unreachable. + // if (!lexStates[parseState]) { + // throw invalidLexState(parseState) + // } + + return lexStates[parseState]() + }, + + comment: function comment () { + switch (c) { + case '*': + read(); + lexState = 'multiLineComment'; + return + + case '/': + read(); + lexState = 'singleLineComment'; + return + } + + throw invalidChar(read()) + }, + + multiLineComment: function multiLineComment () { + switch (c) { + case '*': + read(); + lexState = 'multiLineCommentAsterisk'; + return + + case undefined: + throw invalidChar(read()) + } + + read(); + }, + + multiLineCommentAsterisk: function multiLineCommentAsterisk () { + switch (c) { + case '*': + read(); + return + + case '/': + read(); + lexState = 'default'; + return + + case undefined: + throw invalidChar(read()) + } + + read(); + lexState = 'multiLineComment'; + }, + + singleLineComment: function singleLineComment () { + switch (c) { + case '\n': + case '\r': + case '\u2028': + case '\u2029': + read(); + lexState = 'default'; + return + + case undefined: + read(); + return newToken('eof') + } + + read(); + }, + + value: function value () { + switch (c) { + case '{': + case '[': + return newToken('punctuator', read()) + + case 'n': + read(); + literal('ull'); + return newToken('null', null) + + case 't': + read(); + literal('rue'); + return newToken('boolean', true) + + case 'f': + read(); + literal('alse'); + return newToken('boolean', false) + + case '-': + case '+': + if (read() === '-') { + sign = -1; + } + + lexState = 'sign'; + return + + case '.': + buffer = read(); + lexState = 'decimalPointLeading'; + return + + case '0': + buffer = read(); + lexState = 'zero'; + return + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + buffer = read(); + lexState = 'decimalInteger'; + return + + case 'I': + read(); + literal('nfinity'); + return newToken('numeric', Infinity) + + case 'N': + read(); + literal('aN'); + return newToken('numeric', NaN) + + case '"': + case "'": + doubleQuote = (read() === '"'); + buffer = ''; + lexState = 'string'; + return + } + + throw invalidChar(read()) + }, + + identifierNameStartEscape: function identifierNameStartEscape () { + if (c !== 'u') { + throw invalidChar(read()) + } + + read(); + var u = unicodeEscape(); + switch (u) { + case '$': + case '_': + break + + default: + if (!util.isIdStartChar(u)) { + throw invalidIdentifier() + } + + break + } + + buffer += u; + lexState = 'identifierName'; + }, + + identifierName: function identifierName () { + switch (c) { + case '$': + case '_': + case '\u200C': + case '\u200D': + buffer += read(); + return + + case '\\': + read(); + lexState = 'identifierNameEscape'; + return + } + + if (util.isIdContinueChar(c)) { + buffer += read(); + return + } + + return newToken('identifier', buffer) + }, + + identifierNameEscape: function identifierNameEscape () { + if (c !== 'u') { + throw invalidChar(read()) + } + + read(); + var u = unicodeEscape(); + switch (u) { + case '$': + case '_': + case '\u200C': + case '\u200D': + break + + default: + if (!util.isIdContinueChar(u)) { + throw invalidIdentifier() + } + + break + } + + buffer += u; + lexState = 'identifierName'; + }, + + sign: function sign$1 () { + switch (c) { + case '.': + buffer = read(); + lexState = 'decimalPointLeading'; + return + + case '0': + buffer = read(); + lexState = 'zero'; + return + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + buffer = read(); + lexState = 'decimalInteger'; + return + + case 'I': + read(); + literal('nfinity'); + return newToken('numeric', sign * Infinity) + + case 'N': + read(); + literal('aN'); + return newToken('numeric', NaN) + } + + throw invalidChar(read()) + }, + + zero: function zero () { + switch (c) { + case '.': + buffer += read(); + lexState = 'decimalPoint'; + return + + case 'e': + case 'E': + buffer += read(); + lexState = 'decimalExponent'; + return + + case 'x': + case 'X': + buffer += read(); + lexState = 'hexadecimal'; + return + } + + return newToken('numeric', sign * 0) + }, + + decimalInteger: function decimalInteger () { + switch (c) { + case '.': + buffer += read(); + lexState = 'decimalPoint'; + return + + case 'e': + case 'E': + buffer += read(); + lexState = 'decimalExponent'; + return + } + + if (util.isDigit(c)) { + buffer += read(); + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + decimalPointLeading: function decimalPointLeading () { + if (util.isDigit(c)) { + buffer += read(); + lexState = 'decimalFraction'; + return + } + + throw invalidChar(read()) + }, + + decimalPoint: function decimalPoint () { + switch (c) { + case 'e': + case 'E': + buffer += read(); + lexState = 'decimalExponent'; + return + } + + if (util.isDigit(c)) { + buffer += read(); + lexState = 'decimalFraction'; + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + decimalFraction: function decimalFraction () { + switch (c) { + case 'e': + case 'E': + buffer += read(); + lexState = 'decimalExponent'; + return + } + + if (util.isDigit(c)) { + buffer += read(); + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + decimalExponent: function decimalExponent () { + switch (c) { + case '+': + case '-': + buffer += read(); + lexState = 'decimalExponentSign'; + return + } + + if (util.isDigit(c)) { + buffer += read(); + lexState = 'decimalExponentInteger'; + return + } + + throw invalidChar(read()) + }, + + decimalExponentSign: function decimalExponentSign () { + if (util.isDigit(c)) { + buffer += read(); + lexState = 'decimalExponentInteger'; + return + } + + throw invalidChar(read()) + }, + + decimalExponentInteger: function decimalExponentInteger () { + if (util.isDigit(c)) { + buffer += read(); + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + hexadecimal: function hexadecimal () { + if (util.isHexDigit(c)) { + buffer += read(); + lexState = 'hexadecimalInteger'; + return + } + + throw invalidChar(read()) + }, + + hexadecimalInteger: function hexadecimalInteger () { + if (util.isHexDigit(c)) { + buffer += read(); + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + string: function string () { + switch (c) { + case '\\': + read(); + buffer += escape(); + return + + case '"': + if (doubleQuote) { + read(); + return newToken('string', buffer) + } + + buffer += read(); + return + + case "'": + if (!doubleQuote) { + read(); + return newToken('string', buffer) + } + + buffer += read(); + return + + case '\n': + case '\r': + throw invalidChar(read()) + + case '\u2028': + case '\u2029': + separatorChar(c); + break + + case undefined: + throw invalidChar(read()) + } + + buffer += read(); + }, + + start: function start () { + switch (c) { + case '{': + case '[': + return newToken('punctuator', read()) + + // This code is unreachable since the default lexState handles eof. + // case undefined: + // return newToken('eof') + } + + lexState = 'value'; + }, + + beforePropertyName: function beforePropertyName () { + switch (c) { + case '$': + case '_': + buffer = read(); + lexState = 'identifierName'; + return + + case '\\': + read(); + lexState = 'identifierNameStartEscape'; + return + + case '}': + return newToken('punctuator', read()) + + case '"': + case "'": + doubleQuote = (read() === '"'); + lexState = 'string'; + return + } + + if (util.isIdStartChar(c)) { + buffer += read(); + lexState = 'identifierName'; + return + } + + throw invalidChar(read()) + }, + + afterPropertyName: function afterPropertyName () { + if (c === ':') { + return newToken('punctuator', read()) + } + + throw invalidChar(read()) + }, + + beforePropertyValue: function beforePropertyValue () { + lexState = 'value'; + }, + + afterPropertyValue: function afterPropertyValue () { + switch (c) { + case ',': + case '}': + return newToken('punctuator', read()) + } + + throw invalidChar(read()) + }, + + beforeArrayValue: function beforeArrayValue () { + if (c === ']') { + return newToken('punctuator', read()) + } + + lexState = 'value'; + }, + + afterArrayValue: function afterArrayValue () { + switch (c) { + case ',': + case ']': + return newToken('punctuator', read()) + } + + throw invalidChar(read()) + }, + + end: function end () { + // This code is unreachable since it's handled by the default lexState. + // if (c === undefined) { + // read() + // return newToken('eof') + // } + + throw invalidChar(read()) + }, + }; + + function newToken (type, value) { + return { + type: type, + value: value, + line: line, + column: column, + } + } + + function literal (s) { + for (var i = 0, list = s; i < list.length; i += 1) { + var c = list[i]; + + var p = peek(); + + if (p !== c) { + throw invalidChar(read()) + } + + read(); + } + } + + function escape () { + var c = peek(); + switch (c) { + case 'b': + read(); + return '\b' + + case 'f': + read(); + return '\f' + + case 'n': + read(); + return '\n' + + case 'r': + read(); + return '\r' + + case 't': + read(); + return '\t' + + case 'v': + read(); + return '\v' + + case '0': + read(); + if (util.isDigit(peek())) { + throw invalidChar(read()) + } + + return '\0' + + case 'x': + read(); + return hexEscape() + + case 'u': + read(); + return unicodeEscape() + + case '\n': + case '\u2028': + case '\u2029': + read(); + return '' + + case '\r': + read(); + if (peek() === '\n') { + read(); + } + + return '' + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + throw invalidChar(read()) + + case undefined: + throw invalidChar(read()) + } + + return read() + } + + function hexEscape () { + var buffer = ''; + var c = peek(); + + if (!util.isHexDigit(c)) { + throw invalidChar(read()) + } + + buffer += read(); + + c = peek(); + if (!util.isHexDigit(c)) { + throw invalidChar(read()) + } + + buffer += read(); + + return String.fromCodePoint(parseInt(buffer, 16)) + } + + function unicodeEscape () { + var buffer = ''; + var count = 4; + + while (count-- > 0) { + var c = peek(); + if (!util.isHexDigit(c)) { + throw invalidChar(read()) + } + + buffer += read(); + } + + return String.fromCodePoint(parseInt(buffer, 16)) + } + + var parseStates = { + start: function start () { + if (token.type === 'eof') { + throw invalidEOF() + } + + push(); + }, + + beforePropertyName: function beforePropertyName () { + switch (token.type) { + case 'identifier': + case 'string': + key = token.value; + parseState = 'afterPropertyName'; + return + + case 'punctuator': + // This code is unreachable since it's handled by the lexState. + // if (token.value !== '}') { + // throw invalidToken() + // } + + pop(); + return + + case 'eof': + throw invalidEOF() + } + + // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + }, + + afterPropertyName: function afterPropertyName () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator' || token.value !== ':') { + // throw invalidToken() + // } + + if (token.type === 'eof') { + throw invalidEOF() + } + + parseState = 'beforePropertyValue'; + }, + + beforePropertyValue: function beforePropertyValue () { + if (token.type === 'eof') { + throw invalidEOF() + } + + push(); + }, + + beforeArrayValue: function beforeArrayValue () { + if (token.type === 'eof') { + throw invalidEOF() + } + + if (token.type === 'punctuator' && token.value === ']') { + pop(); + return + } + + push(); + }, + + afterPropertyValue: function afterPropertyValue () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator') { + // throw invalidToken() + // } + + if (token.type === 'eof') { + throw invalidEOF() + } + + switch (token.value) { + case ',': + parseState = 'beforePropertyName'; + return + + case '}': + pop(); + } + + // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + }, + + afterArrayValue: function afterArrayValue () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator') { + // throw invalidToken() + // } + + if (token.type === 'eof') { + throw invalidEOF() + } + + switch (token.value) { + case ',': + parseState = 'beforeArrayValue'; + return + + case ']': + pop(); + } + + // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + }, + + end: function end () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'eof') { + // throw invalidToken() + // } + }, + }; + + function push () { + var value; + + switch (token.type) { + case 'punctuator': + switch (token.value) { + case '{': + value = {}; + break + + case '[': + value = []; + break + } + + break + + case 'null': + case 'boolean': + case 'numeric': + case 'string': + value = token.value; + break + + // This code is unreachable. + // default: + // throw invalidToken() + } + + if (root === undefined) { + root = value; + } else { + var parent = stack[stack.length - 1]; + if (Array.isArray(parent)) { + parent.push(value); + } else { + Object.defineProperty(parent, key, { + value: value, + writable: true, + enumerable: true, + configurable: true, + }); + } + } + + if (value !== null && typeof value === 'object') { + stack.push(value); + + if (Array.isArray(value)) { + parseState = 'beforeArrayValue'; + } else { + parseState = 'beforePropertyName'; + } + } else { + var current = stack[stack.length - 1]; + if (current == null) { + parseState = 'end'; + } else if (Array.isArray(current)) { + parseState = 'afterArrayValue'; + } else { + parseState = 'afterPropertyValue'; + } + } + } + + function pop () { + stack.pop(); + + var current = stack[stack.length - 1]; + if (current == null) { + parseState = 'end'; + } else if (Array.isArray(current)) { + parseState = 'afterArrayValue'; + } else { + parseState = 'afterPropertyValue'; + } + } + + // This code is unreachable. + // function invalidParseState () { + // return new Error(`JSON5: invalid parse state '${parseState}'`) + // } + + // This code is unreachable. + // function invalidLexState (state) { + // return new Error(`JSON5: invalid lex state '${state}'`) + // } + + function invalidChar (c) { + if (c === undefined) { + return syntaxError(("JSON5: invalid end of input at " + line + ":" + column)) + } + + return syntaxError(("JSON5: invalid character '" + (formatChar(c)) + "' at " + line + ":" + column)) + } + + function invalidEOF () { + return syntaxError(("JSON5: invalid end of input at " + line + ":" + column)) + } + + // This code is unreachable. + // function invalidToken () { + // if (token.type === 'eof') { + // return syntaxError(`JSON5: invalid end of input at ${line}:${column}`) + // } + + // const c = String.fromCodePoint(token.value.codePointAt(0)) + // return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`) + // } + + function invalidIdentifier () { + column -= 5; + return syntaxError(("JSON5: invalid identifier character at " + line + ":" + column)) + } + + function separatorChar (c) { + console.warn(("JSON5: '" + (formatChar(c)) + "' in strings is not valid ECMAScript; consider escaping")); + } + + function formatChar (c) { + var replacements = { + "'": "\\'", + '"': '\\"', + '\\': '\\\\', + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t', + '\v': '\\v', + '\0': '\\0', + '\u2028': '\\u2028', + '\u2029': '\\u2029', + }; + + if (replacements[c]) { + return replacements[c] + } + + if (c < ' ') { + var hexString = c.charCodeAt(0).toString(16); + return '\\x' + ('00' + hexString).substring(hexString.length) + } + + return c + } + + function syntaxError (message) { + var err = new SyntaxError(message); + err.lineNumber = line; + err.columnNumber = column; + return err + } + + var stringify = function stringify (value, replacer, space) { + var stack = []; + var indent = ''; + var propertyList; + var replacerFunc; + var gap = ''; + var quote; + + if ( + replacer != null && + typeof replacer === 'object' && + !Array.isArray(replacer) + ) { + space = replacer.space; + quote = replacer.quote; + replacer = replacer.replacer; + } + + if (typeof replacer === 'function') { + replacerFunc = replacer; + } else if (Array.isArray(replacer)) { + propertyList = []; + for (var i = 0, list = replacer; i < list.length; i += 1) { + var v = list[i]; + + var item = (void 0); + + if (typeof v === 'string') { + item = v; + } else if ( + typeof v === 'number' || + v instanceof String || + v instanceof Number + ) { + item = String(v); + } + + if (item !== undefined && propertyList.indexOf(item) < 0) { + propertyList.push(item); + } + } + } + + if (space instanceof Number) { + space = Number(space); + } else if (space instanceof String) { + space = String(space); + } + + if (typeof space === 'number') { + if (space > 0) { + space = Math.min(10, Math.floor(space)); + gap = ' '.substr(0, space); + } + } else if (typeof space === 'string') { + gap = space.substr(0, 10); + } + + return serializeProperty('', {'': value}) + + function serializeProperty (key, holder) { + var value = holder[key]; + if (value != null) { + if (typeof value.toJSON5 === 'function') { + value = value.toJSON5(key); + } else if (typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + } + + if (replacerFunc) { + value = replacerFunc.call(holder, key, value); + } + + if (value instanceof Number) { + value = Number(value); + } else if (value instanceof String) { + value = String(value); + } else if (value instanceof Boolean) { + value = value.valueOf(); + } + + switch (value) { + case null: return 'null' + case true: return 'true' + case false: return 'false' + } + + if (typeof value === 'string') { + return quoteString(value, false) + } + + if (typeof value === 'number') { + return String(value) + } + + if (typeof value === 'object') { + return Array.isArray(value) ? serializeArray(value) : serializeObject(value) + } + + return undefined + } + + function quoteString (value) { + var quotes = { + "'": 0.1, + '"': 0.2, + }; + + var replacements = { + "'": "\\'", + '"': '\\"', + '\\': '\\\\', + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t', + '\v': '\\v', + '\0': '\\0', + '\u2028': '\\u2028', + '\u2029': '\\u2029', + }; + + var product = ''; + + for (var i = 0; i < value.length; i++) { + var c = value[i]; + switch (c) { + case "'": + case '"': + quotes[c]++; + product += c; + continue + + case '\0': + if (util.isDigit(value[i + 1])) { + product += '\\x00'; + continue + } + } + + if (replacements[c]) { + product += replacements[c]; + continue + } + + if (c < ' ') { + var hexString = c.charCodeAt(0).toString(16); + product += '\\x' + ('00' + hexString).substring(hexString.length); + continue + } + + product += c; + } + + var quoteChar = quote || Object.keys(quotes).reduce(function (a, b) { return (quotes[a] < quotes[b]) ? a : b; }); + + product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]); + + return quoteChar + product + quoteChar + } + + function serializeObject (value) { + if (stack.indexOf(value) >= 0) { + throw TypeError('Converting circular structure to JSON5') + } + + stack.push(value); + + var stepback = indent; + indent = indent + gap; + + var keys = propertyList || Object.keys(value); + var partial = []; + for (var i = 0, list = keys; i < list.length; i += 1) { + var key = list[i]; + + var propertyString = serializeProperty(key, value); + if (propertyString !== undefined) { + var member = serializeKey(key) + ':'; + if (gap !== '') { + member += ' '; + } + member += propertyString; + partial.push(member); + } + } + + var final; + if (partial.length === 0) { + final = '{}'; + } else { + var properties; + if (gap === '') { + properties = partial.join(','); + final = '{' + properties + '}'; + } else { + var separator = ',\n' + indent; + properties = partial.join(separator); + final = '{\n' + indent + properties + ',\n' + stepback + '}'; + } + } + + stack.pop(); + indent = stepback; + return final + } + + function serializeKey (key) { + if (key.length === 0) { + return quoteString(key, true) + } + + var firstChar = String.fromCodePoint(key.codePointAt(0)); + if (!util.isIdStartChar(firstChar)) { + return quoteString(key, true) + } + + for (var i = firstChar.length; i < key.length; i++) { + if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) { + return quoteString(key, true) + } + } + + return key + } + + function serializeArray (value) { + if (stack.indexOf(value) >= 0) { + throw TypeError('Converting circular structure to JSON5') + } + + stack.push(value); + + var stepback = indent; + indent = indent + gap; + + var partial = []; + for (var i = 0; i < value.length; i++) { + var propertyString = serializeProperty(String(i), value); + partial.push((propertyString !== undefined) ? propertyString : 'null'); + } + + var final; + if (partial.length === 0) { + final = '[]'; + } else { + if (gap === '') { + var properties = partial.join(','); + final = '[' + properties + ']'; + } else { + var separator = ',\n' + indent; + var properties$1 = partial.join(separator); + final = '[\n' + indent + properties$1 + ',\n' + stepback + ']'; + } + } + + stack.pop(); + indent = stepback; + return final + } + }; + + var JSON5 = { + parse: parse, + stringify: stringify, + }; + + var lib = JSON5; + + var es5 = lib; + + return es5; + +}))); diff --git a/node_modules/json5/dist/index.min.js b/node_modules/json5/dist/index.min.js new file mode 100644 index 0000000..ddce3e2 --- /dev/null +++ b/node_modules/json5/dist/index.min.js @@ -0,0 +1 @@ +!function(u,D){"object"==typeof exports&&"undefined"!=typeof module?module.exports=D():"function"==typeof define&&define.amd?define(D):u.JSON5=D()}(this,function(){"use strict";function u(u,D){return u(D={exports:{}},D.exports),D.exports}var D=u(function(u){var D=u.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=D)}),e=u(function(u){var D=u.exports={version:"2.6.5"};"number"==typeof __e&&(__e=D)}),r=(e.version,function(u){return"object"==typeof u?null!==u:"function"==typeof u}),t=function(u){if(!r(u))throw TypeError(u+" is not an object!");return u},n=function(u){try{return!!u()}catch(u){return!0}},F=!n(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),C=D.document,A=r(C)&&r(C.createElement),i=!F&&!n(function(){return 7!=Object.defineProperty((u="div",A?C.createElement(u):{}),"a",{get:function(){return 7}}).a;var u}),E=Object.defineProperty,o={f:F?Object.defineProperty:function(u,D,e){if(t(u),D=function(u,D){if(!r(u))return u;var e,t;if(D&&"function"==typeof(e=u.toString)&&!r(t=e.call(u)))return t;if("function"==typeof(e=u.valueOf)&&!r(t=e.call(u)))return t;if(!D&&"function"==typeof(e=u.toString)&&!r(t=e.call(u)))return t;throw TypeError("Can't convert object to primitive value")}(D,!0),t(e),i)try{return E(u,D,e)}catch(u){}if("get"in e||"set"in e)throw TypeError("Accessors not supported!");return"value"in e&&(u[D]=e.value),u}},a=F?function(u,D,e){return o.f(u,D,function(u,D){return{enumerable:!(1&u),configurable:!(2&u),writable:!(4&u),value:D}}(1,e))}:function(u,D,e){return u[D]=e,u},c={}.hasOwnProperty,B=function(u,D){return c.call(u,D)},s=0,f=Math.random(),l=u(function(u){var r=D["__core-js_shared__"]||(D["__core-js_shared__"]={});(u.exports=function(u,D){return r[u]||(r[u]=void 0!==D?D:{})})("versions",[]).push({version:e.version,mode:"global",copyright:"© 2019 Denis Pushkarev (zloirock.ru)"})})("native-function-to-string",Function.toString),d=u(function(u){var r,t="Symbol(".concat(void 0===(r="src")?"":r,")_",(++s+f).toString(36)),n=(""+l).split("toString");e.inspectSource=function(u){return l.call(u)},(u.exports=function(u,e,r,F){var C="function"==typeof r;C&&(B(r,"name")||a(r,"name",e)),u[e]!==r&&(C&&(B(r,t)||a(r,t,u[e]?""+u[e]:n.join(String(e)))),u===D?u[e]=r:F?u[e]?u[e]=r:a(u,e,r):(delete u[e],a(u,e,r)))})(Function.prototype,"toString",function(){return"function"==typeof this&&this[t]||l.call(this)})}),v=function(u,D,e){if(function(u){if("function"!=typeof u)throw TypeError(u+" is not a function!")}(u),void 0===D)return u;switch(e){case 1:return function(e){return u.call(D,e)};case 2:return function(e,r){return u.call(D,e,r)};case 3:return function(e,r,t){return u.call(D,e,r,t)}}return function(){return u.apply(D,arguments)}},p=function(u,r,t){var n,F,C,A,i=u&p.F,E=u&p.G,o=u&p.S,c=u&p.P,B=u&p.B,s=E?D:o?D[r]||(D[r]={}):(D[r]||{}).prototype,f=E?e:e[r]||(e[r]={}),l=f.prototype||(f.prototype={});for(n in E&&(t=r),t)C=((F=!i&&s&&void 0!==s[n])?s:t)[n],A=B&&F?v(C,D):c&&"function"==typeof C?v(Function.call,C):C,s&&d(s,n,C,u&p.U),f[n]!=C&&a(f,n,A),c&&l[n]!=C&&(l[n]=C)};D.core=e,p.F=1,p.G=2,p.S=4,p.P=8,p.B=16,p.W=32,p.U=64,p.R=128;var h,m=p,g=Math.ceil,y=Math.floor,w=function(u){return isNaN(u=+u)?0:(u>0?y:g)(u)},b=(h=!1,function(u,D){var e,r,t=String(function(u){if(null==u)throw TypeError("Can't call method on "+u);return u}(u)),n=w(D),F=t.length;return n<0||n>=F?h?"":void 0:(e=t.charCodeAt(n))<55296||e>56319||n+1===F||(r=t.charCodeAt(n+1))<56320||r>57343?h?t.charAt(n):e:h?t.slice(n,n+2):r-56320+(e-55296<<10)+65536});m(m.P,"String",{codePointAt:function(u){return b(this,u)}});e.String.codePointAt;var S=Math.max,x=Math.min,N=String.fromCharCode,P=String.fromCodePoint;m(m.S+m.F*(!!P&&1!=P.length),"String",{fromCodePoint:function(u){for(var D,e,r,t=arguments,n=[],F=arguments.length,C=0;F>C;){if(D=+t[C++],r=1114111,((e=w(e=D))<0?S(e+r,0):x(e,r))!==D)throw RangeError(D+" is not a valid code point");n.push(D<65536?N(D):N(55296+((D-=65536)>>10),D%1024+56320))}return n.join("")}});e.String.fromCodePoint;var _,O,j,I,V,J,M,k,L,T,z,H,$,R,G={Space_Separator:/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,ID_Start:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u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C-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB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\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,ID_Continue:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3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4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42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\uDD00-\uDDEF]/},U={isSpaceSeparator:function(u){return"string"==typeof u&&G.Space_Separator.test(u)},isIdStartChar:function(u){return"string"==typeof u&&(u>="a"&&u<="z"||u>="A"&&u<="Z"||"$"===u||"_"===u||G.ID_Start.test(u))},isIdContinueChar:function(u){return"string"==typeof u&&(u>="a"&&u<="z"||u>="A"&&u<="Z"||u>="0"&&u<="9"||"$"===u||"_"===u||"‌"===u||"‍"===u||G.ID_Continue.test(u))},isDigit:function(u){return"string"==typeof u&&/[0-9]/.test(u)},isHexDigit:function(u){return"string"==typeof u&&/[0-9A-Fa-f]/.test(u)}};function Z(){for(T="default",z="",H=!1,$=1;;){R=q();var u=X[T]();if(u)return u}}function q(){if(_[I])return String.fromCodePoint(_.codePointAt(I))}function W(){var u=q();return"\n"===u?(V++,J=0):u?J+=u.length:J++,u&&(I+=u.length),u}var X={default:function(){switch(R){case"\t":case"\v":case"\f":case" ":case" ":case"\ufeff":case"\n":case"\r":case"\u2028":case"\u2029":return void W();case"/":return W(),void(T="comment");case void 0:return W(),K("eof")}if(!U.isSpaceSeparator(R))return X[O]();W()},comment:function(){switch(R){case"*":return W(),void(T="multiLineComment");case"/":return W(),void(T="singleLineComment")}throw ru(W())},multiLineComment:function(){switch(R){case"*":return W(),void(T="multiLineCommentAsterisk");case void 0:throw ru(W())}W()},multiLineCommentAsterisk:function(){switch(R){case"*":return void W();case"/":return W(),void(T="default");case void 0:throw ru(W())}W(),T="multiLineComment"},singleLineComment:function(){switch(R){case"\n":case"\r":case"\u2028":case"\u2029":return W(),void(T="default");case void 0:return W(),K("eof")}W()},value:function(){switch(R){case"{":case"[":return K("punctuator",W());case"n":return W(),Q("ull"),K("null",null);case"t":return W(),Q("rue"),K("boolean",!0);case"f":return W(),Q("alse"),K("boolean",!1);case"-":case"+":return"-"===W()&&($=-1),void(T="sign");case".":return z=W(),void(T="decimalPointLeading");case"0":return z=W(),void(T="zero");case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":return z=W(),void(T="decimalInteger");case"I":return W(),Q("nfinity"),K("numeric",1/0);case"N":return W(),Q("aN"),K("numeric",NaN);case'"':case"'":return H='"'===W(),z="",void(T="string")}throw ru(W())},identifierNameStartEscape:function(){if("u"!==R)throw ru(W());W();var u=Y();switch(u){case"$":case"_":break;default:if(!U.isIdStartChar(u))throw nu()}z+=u,T="identifierName"},identifierName:function(){switch(R){case"$":case"_":case"‌":case"‍":return void(z+=W());case"\\":return W(),void(T="identifierNameEscape")}if(!U.isIdContinueChar(R))return K("identifier",z);z+=W()},identifierNameEscape:function(){if("u"!==R)throw ru(W());W();var u=Y();switch(u){case"$":case"_":case"‌":case"‍":break;default:if(!U.isIdContinueChar(u))throw nu()}z+=u,T="identifierName"},sign:function(){switch(R){case".":return z=W(),void(T="decimalPointLeading");case"0":return z=W(),void(T="zero");case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":return z=W(),void(T="decimalInteger");case"I":return W(),Q("nfinity"),K("numeric",$*(1/0));case"N":return W(),Q("aN"),K("numeric",NaN)}throw ru(W())},zero:function(){switch(R){case".":return z+=W(),void(T="decimalPoint");case"e":case"E":return z+=W(),void(T="decimalExponent");case"x":case"X":return z+=W(),void(T="hexadecimal")}return K("numeric",0*$)},decimalInteger:function(){switch(R){case".":return z+=W(),void(T="decimalPoint");case"e":case"E":return z+=W(),void(T="decimalExponent")}if(!U.isDigit(R))return K("numeric",$*Number(z));z+=W()},decimalPointLeading:function(){if(U.isDigit(R))return z+=W(),void(T="decimalFraction");throw ru(W())},decimalPoint:function(){switch(R){case"e":case"E":return z+=W(),void(T="decimalExponent")}return U.isDigit(R)?(z+=W(),void(T="decimalFraction")):K("numeric",$*Number(z))},decimalFraction:function(){switch(R){case"e":case"E":return z+=W(),void(T="decimalExponent")}if(!U.isDigit(R))return K("numeric",$*Number(z));z+=W()},decimalExponent:function(){switch(R){case"+":case"-":return z+=W(),void(T="decimalExponentSign")}if(U.isDigit(R))return z+=W(),void(T="decimalExponentInteger");throw ru(W())},decimalExponentSign:function(){if(U.isDigit(R))return z+=W(),void(T="decimalExponentInteger");throw ru(W())},decimalExponentInteger:function(){if(!U.isDigit(R))return K("numeric",$*Number(z));z+=W()},hexadecimal:function(){if(U.isHexDigit(R))return z+=W(),void(T="hexadecimalInteger");throw ru(W())},hexadecimalInteger:function(){if(!U.isHexDigit(R))return K("numeric",$*Number(z));z+=W()},string:function(){switch(R){case"\\":return W(),void(z+=function(){switch(q()){case"b":return W(),"\b";case"f":return W(),"\f";case"n":return W(),"\n";case"r":return W(),"\r";case"t":return W(),"\t";case"v":return W(),"\v";case"0":if(W(),U.isDigit(q()))throw ru(W());return"\0";case"x":return W(),function(){var u="",D=q();if(!U.isHexDigit(D))throw ru(W());if(u+=W(),D=q(),!U.isHexDigit(D))throw ru(W());return u+=W(),String.fromCodePoint(parseInt(u,16))}();case"u":return W(),Y();case"\n":case"\u2028":case"\u2029":return W(),"";case"\r":return W(),"\n"===q()&&W(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case void 0:throw ru(W())}return W()}());case'"':return H?(W(),K("string",z)):void(z+=W());case"'":return H?void(z+=W()):(W(),K("string",z));case"\n":case"\r":throw ru(W());case"\u2028":case"\u2029":!function(u){console.warn("JSON5: '"+Fu(u)+"' in strings is not valid ECMAScript; consider escaping")}(R);break;case void 0:throw ru(W())}z+=W()},start:function(){switch(R){case"{":case"[":return K("punctuator",W())}T="value"},beforePropertyName:function(){switch(R){case"$":case"_":return z=W(),void(T="identifierName");case"\\":return W(),void(T="identifierNameStartEscape");case"}":return K("punctuator",W());case'"':case"'":return H='"'===W(),void(T="string")}if(U.isIdStartChar(R))return z+=W(),void(T="identifierName");throw ru(W())},afterPropertyName:function(){if(":"===R)return K("punctuator",W());throw ru(W())},beforePropertyValue:function(){T="value"},afterPropertyValue:function(){switch(R){case",":case"}":return K("punctuator",W())}throw ru(W())},beforeArrayValue:function(){if("]"===R)return K("punctuator",W());T="value"},afterArrayValue:function(){switch(R){case",":case"]":return K("punctuator",W())}throw ru(W())},end:function(){throw ru(W())}};function K(u,D){return{type:u,value:D,line:V,column:J}}function Q(u){for(var D=0,e=u;D0;){var e=q();if(!U.isHexDigit(e))throw ru(W());u+=W()}return String.fromCodePoint(parseInt(u,16))}var uu={start:function(){if("eof"===M.type)throw tu();Du()},beforePropertyName:function(){switch(M.type){case"identifier":case"string":return k=M.value,void(O="afterPropertyName");case"punctuator":return void eu();case"eof":throw tu()}},afterPropertyName:function(){if("eof"===M.type)throw tu();O="beforePropertyValue"},beforePropertyValue:function(){if("eof"===M.type)throw tu();Du()},beforeArrayValue:function(){if("eof"===M.type)throw tu();"punctuator"!==M.type||"]"!==M.value?Du():eu()},afterPropertyValue:function(){if("eof"===M.type)throw tu();switch(M.value){case",":return void(O="beforePropertyName");case"}":eu()}},afterArrayValue:function(){if("eof"===M.type)throw tu();switch(M.value){case",":return void(O="beforeArrayValue");case"]":eu()}},end:function(){}};function Du(){var u;switch(M.type){case"punctuator":switch(M.value){case"{":u={};break;case"[":u=[]}break;case"null":case"boolean":case"numeric":case"string":u=M.value}if(void 0===L)L=u;else{var D=j[j.length-1];Array.isArray(D)?D.push(u):Object.defineProperty(D,k,{value:u,writable:!0,enumerable:!0,configurable:!0})}if(null!==u&&"object"==typeof u)j.push(u),O=Array.isArray(u)?"beforeArrayValue":"beforePropertyName";else{var e=j[j.length-1];O=null==e?"end":Array.isArray(e)?"afterArrayValue":"afterPropertyValue"}}function eu(){j.pop();var u=j[j.length-1];O=null==u?"end":Array.isArray(u)?"afterArrayValue":"afterPropertyValue"}function ru(u){return Cu(void 0===u?"JSON5: invalid end of input at "+V+":"+J:"JSON5: invalid character '"+Fu(u)+"' at "+V+":"+J)}function tu(){return Cu("JSON5: invalid end of input at "+V+":"+J)}function nu(){return Cu("JSON5: invalid identifier character at "+V+":"+(J-=5))}function Fu(u){var D={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(D[u])return D[u];if(u<" "){var e=u.charCodeAt(0).toString(16);return"\\x"+("00"+e).substring(e.length)}return u}function Cu(u){var D=new SyntaxError(u);return D.lineNumber=V,D.columnNumber=J,D}return{parse:function(u,D){_=String(u),O="start",j=[],I=0,V=1,J=0,M=void 0,k=void 0,L=void 0;do{M=Z(),uu[O]()}while("eof"!==M.type);return"function"==typeof D?function u(D,e,r){var t=D[e];if(null!=t&&"object"==typeof t)if(Array.isArray(t))for(var n=0;n0&&(e=Math.min(10,Math.floor(e)),A=" ".substr(0,e)):"string"==typeof e&&(A=e.substr(0,10)),c("",{"":u});function c(u,D){var e=D[u];switch(null!=e&&("function"==typeof e.toJSON5?e=e.toJSON5(u):"function"==typeof e.toJSON&&(e=e.toJSON(u))),t&&(e=t.call(D,u,e)),e instanceof Number?e=Number(e):e instanceof String?e=String(e):e instanceof Boolean&&(e=e.valueOf()),e){case null:return"null";case!0:return"true";case!1:return"false"}return"string"==typeof e?B(e):"number"==typeof e?String(e):"object"==typeof e?Array.isArray(e)?function(u){if(F.indexOf(u)>=0)throw TypeError("Converting circular structure to JSON5");F.push(u);var D=C;C+=A;for(var e,r=[],t=0;t=0)throw TypeError("Converting circular structure to JSON5");F.push(u);var D=C;C+=A;for(var e,t,n=r||Object.keys(u),i=[],E=0,o=n;E"string"==typeof u&&unicode.Space_Separator.test(u),isIdStartChar:u=>"string"==typeof u&&(u>="a"&&u<="z"||u>="A"&&u<="Z"||"$"===u||"_"===u||unicode.ID_Start.test(u)),isIdContinueChar:u=>"string"==typeof u&&(u>="a"&&u<="z"||u>="A"&&u<="Z"||u>="0"&&u<="9"||"$"===u||"_"===u||"‌"===u||"‍"===u||unicode.ID_Continue.test(u)),isDigit:u=>"string"==typeof u&&/[0-9]/.test(u),isHexDigit:u=>"string"==typeof u&&/[0-9A-Fa-f]/.test(u)};let source,parseState,stack,pos,line,column,token,key,root;var parse=function(u,D){source=String(u),parseState="start",stack=[],pos=0,line=1,column=0,token=void 0,key=void 0,root=void 0;do{token=lex(),parseStates[parseState]()}while("eof"!==token.type);return"function"==typeof D?internalize({"":root},"",D):root};function internalize(u,D,e){const r=u[D];if(null!=r&&"object"==typeof r)if(Array.isArray(r))for(let u=0;u0;){const D=peek();if(!util.isHexDigit(D))throw invalidChar(read());u+=read()}return String.fromCodePoint(parseInt(u,16))}const parseStates={start(){if("eof"===token.type)throw invalidEOF();push()},beforePropertyName(){switch(token.type){case"identifier":case"string":return key=token.value,void(parseState="afterPropertyName");case"punctuator":return void pop();case"eof":throw invalidEOF()}},afterPropertyName(){if("eof"===token.type)throw invalidEOF();parseState="beforePropertyValue"},beforePropertyValue(){if("eof"===token.type)throw invalidEOF();push()},beforeArrayValue(){if("eof"===token.type)throw invalidEOF();"punctuator"!==token.type||"]"!==token.value?push():pop()},afterPropertyValue(){if("eof"===token.type)throw invalidEOF();switch(token.value){case",":return void(parseState="beforePropertyName");case"}":pop()}},afterArrayValue(){if("eof"===token.type)throw invalidEOF();switch(token.value){case",":return void(parseState="beforeArrayValue");case"]":pop()}},end(){}};function push(){let u;switch(token.type){case"punctuator":switch(token.value){case"{":u={};break;case"[":u=[]}break;case"null":case"boolean":case"numeric":case"string":u=token.value}if(void 0===root)root=u;else{const D=stack[stack.length-1];Array.isArray(D)?D.push(u):Object.defineProperty(D,key,{value:u,writable:!0,enumerable:!0,configurable:!0})}if(null!==u&&"object"==typeof u)stack.push(u),parseState=Array.isArray(u)?"beforeArrayValue":"beforePropertyName";else{const u=stack[stack.length-1];parseState=null==u?"end":Array.isArray(u)?"afterArrayValue":"afterPropertyValue"}}function pop(){stack.pop();const u=stack[stack.length-1];parseState=null==u?"end":Array.isArray(u)?"afterArrayValue":"afterPropertyValue"}function invalidChar(u){return syntaxError(void 0===u?`JSON5: invalid end of input at ${line}:${column}`:`JSON5: invalid character '${formatChar(u)}' at ${line}:${column}`)}function invalidEOF(){return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)}function invalidIdentifier(){return syntaxError(`JSON5: invalid identifier character at ${line}:${column-=5}`)}function separatorChar(u){console.warn(`JSON5: '${formatChar(u)}' in strings is not valid ECMAScript; consider escaping`)}function formatChar(u){const D={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(D[u])return D[u];if(u<" "){const D=u.charCodeAt(0).toString(16);return"\\x"+("00"+D).substring(D.length)}return u}function syntaxError(u){const D=new SyntaxError(u);return D.lineNumber=line,D.columnNumber=column,D}var stringify=function(u,D,e){const r=[];let t,F,C,a="",A="";if(null==D||"object"!=typeof D||Array.isArray(D)||(e=D.space,C=D.quote,D=D.replacer),"function"==typeof D)F=D;else if(Array.isArray(D)){t=[];for(const u of D){let D;"string"==typeof u?D=u:("number"==typeof u||u instanceof String||u instanceof Number)&&(D=String(u)),void 0!==D&&t.indexOf(D)<0&&t.push(D)}}return e instanceof Number?e=Number(e):e instanceof String&&(e=String(e)),"number"==typeof e?e>0&&(e=Math.min(10,Math.floor(e)),A=" ".substr(0,e)):"string"==typeof e&&(A=e.substr(0,10)),n("",{"":u});function n(u,D){let e=D[u];switch(null!=e&&("function"==typeof e.toJSON5?e=e.toJSON5(u):"function"==typeof e.toJSON&&(e=e.toJSON(u))),F&&(e=F.call(D,u,e)),e instanceof Number?e=Number(e):e instanceof String?e=String(e):e instanceof Boolean&&(e=e.valueOf()),e){case null:return"null";case!0:return"true";case!1:return"false"}return"string"==typeof e?E(e):"number"==typeof e?String(e):"object"==typeof e?Array.isArray(e)?function(u){if(r.indexOf(u)>=0)throw TypeError("Converting circular structure to JSON5");r.push(u);let D=a;a+=A;let e,t=[];for(let D=0;D=0)throw TypeError("Converting circular structure to JSON5");r.push(u);let D=a;a+=A;let e,F=t||Object.keys(u),C=[];for(const D of F){const e=n(D,u);if(void 0!==e){let u=i(D)+":";""!==A&&(u+=" "),u+=e,C.push(u)}}if(0===C.length)e="{}";else{let u;if(""===A)u=C.join(","),e="{"+u+"}";else{let r=",\n"+a;u=C.join(r),e="{\n"+a+u+",\n"+D+"}"}}return r.pop(),a=D,e}(e):void 0}function E(u){const D={"'":.1,'"':.2},e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};let r="";for(let t=0;tD[u]= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c === '$') || (c === '_') || + unicode.ID_Start.test(c) + ) + }, + + isIdContinueChar (c) { + return typeof c === 'string' && ( + (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || + (c === '$') || (c === '_') || + (c === '\u200C') || (c === '\u200D') || + unicode.ID_Continue.test(c) + ) + }, + + isDigit (c) { + return typeof c === 'string' && /[0-9]/.test(c) + }, + + isHexDigit (c) { + return typeof c === 'string' && /[0-9A-Fa-f]/.test(c) + }, +}; + +let source; +let parseState; +let stack; +let pos; +let line; +let column; +let token; +let key; +let root; + +var parse = function parse (text, reviver) { + source = String(text); + parseState = 'start'; + stack = []; + pos = 0; + line = 1; + column = 0; + token = undefined; + key = undefined; + root = undefined; + + do { + token = lex(); + + // This code is unreachable. + // if (!parseStates[parseState]) { + // throw invalidParseState() + // } + + parseStates[parseState](); + } while (token.type !== 'eof') + + if (typeof reviver === 'function') { + return internalize({'': root}, '', reviver) + } + + return root +}; + +function internalize (holder, name, reviver) { + const value = holder[name]; + if (value != null && typeof value === 'object') { + if (Array.isArray(value)) { + for (let i = 0; i < value.length; i++) { + const key = String(i); + const replacement = internalize(value, key, reviver); + if (replacement === undefined) { + delete value[key]; + } else { + Object.defineProperty(value, key, { + value: replacement, + writable: true, + enumerable: true, + configurable: true, + }); + } + } + } else { + for (const key in value) { + const replacement = internalize(value, key, reviver); + if (replacement === undefined) { + delete value[key]; + } else { + Object.defineProperty(value, key, { + value: replacement, + writable: true, + enumerable: true, + configurable: true, + }); + } + } + } + } + + return reviver.call(holder, name, value) +} + +let lexState; +let buffer; +let doubleQuote; +let sign; +let c; + +function lex () { + lexState = 'default'; + buffer = ''; + doubleQuote = false; + sign = 1; + + for (;;) { + c = peek(); + + // This code is unreachable. + // if (!lexStates[lexState]) { + // throw invalidLexState(lexState) + // } + + const token = lexStates[lexState](); + if (token) { + return token + } + } +} + +function peek () { + if (source[pos]) { + return String.fromCodePoint(source.codePointAt(pos)) + } +} + +function read () { + const c = peek(); + + if (c === '\n') { + line++; + column = 0; + } else if (c) { + column += c.length; + } else { + column++; + } + + if (c) { + pos += c.length; + } + + return c +} + +const lexStates = { + default () { + switch (c) { + case '\t': + case '\v': + case '\f': + case ' ': + case '\u00A0': + case '\uFEFF': + case '\n': + case '\r': + case '\u2028': + case '\u2029': + read(); + return + + case '/': + read(); + lexState = 'comment'; + return + + case undefined: + read(); + return newToken('eof') + } + + if (util.isSpaceSeparator(c)) { + read(); + return + } + + // This code is unreachable. + // if (!lexStates[parseState]) { + // throw invalidLexState(parseState) + // } + + return lexStates[parseState]() + }, + + comment () { + switch (c) { + case '*': + read(); + lexState = 'multiLineComment'; + return + + case '/': + read(); + lexState = 'singleLineComment'; + return + } + + throw invalidChar(read()) + }, + + multiLineComment () { + switch (c) { + case '*': + read(); + lexState = 'multiLineCommentAsterisk'; + return + + case undefined: + throw invalidChar(read()) + } + + read(); + }, + + multiLineCommentAsterisk () { + switch (c) { + case '*': + read(); + return + + case '/': + read(); + lexState = 'default'; + return + + case undefined: + throw invalidChar(read()) + } + + read(); + lexState = 'multiLineComment'; + }, + + singleLineComment () { + switch (c) { + case '\n': + case '\r': + case '\u2028': + case '\u2029': + read(); + lexState = 'default'; + return + + case undefined: + read(); + return newToken('eof') + } + + read(); + }, + + value () { + switch (c) { + case '{': + case '[': + return newToken('punctuator', read()) + + case 'n': + read(); + literal('ull'); + return newToken('null', null) + + case 't': + read(); + literal('rue'); + return newToken('boolean', true) + + case 'f': + read(); + literal('alse'); + return newToken('boolean', false) + + case '-': + case '+': + if (read() === '-') { + sign = -1; + } + + lexState = 'sign'; + return + + case '.': + buffer = read(); + lexState = 'decimalPointLeading'; + return + + case '0': + buffer = read(); + lexState = 'zero'; + return + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + buffer = read(); + lexState = 'decimalInteger'; + return + + case 'I': + read(); + literal('nfinity'); + return newToken('numeric', Infinity) + + case 'N': + read(); + literal('aN'); + return newToken('numeric', NaN) + + case '"': + case "'": + doubleQuote = (read() === '"'); + buffer = ''; + lexState = 'string'; + return + } + + throw invalidChar(read()) + }, + + identifierNameStartEscape () { + if (c !== 'u') { + throw invalidChar(read()) + } + + read(); + const u = unicodeEscape(); + switch (u) { + case '$': + case '_': + break + + default: + if (!util.isIdStartChar(u)) { + throw invalidIdentifier() + } + + break + } + + buffer += u; + lexState = 'identifierName'; + }, + + identifierName () { + switch (c) { + case '$': + case '_': + case '\u200C': + case '\u200D': + buffer += read(); + return + + case '\\': + read(); + lexState = 'identifierNameEscape'; + return + } + + if (util.isIdContinueChar(c)) { + buffer += read(); + return + } + + return newToken('identifier', buffer) + }, + + identifierNameEscape () { + if (c !== 'u') { + throw invalidChar(read()) + } + + read(); + const u = unicodeEscape(); + switch (u) { + case '$': + case '_': + case '\u200C': + case '\u200D': + break + + default: + if (!util.isIdContinueChar(u)) { + throw invalidIdentifier() + } + + break + } + + buffer += u; + lexState = 'identifierName'; + }, + + sign () { + switch (c) { + case '.': + buffer = read(); + lexState = 'decimalPointLeading'; + return + + case '0': + buffer = read(); + lexState = 'zero'; + return + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + buffer = read(); + lexState = 'decimalInteger'; + return + + case 'I': + read(); + literal('nfinity'); + return newToken('numeric', sign * Infinity) + + case 'N': + read(); + literal('aN'); + return newToken('numeric', NaN) + } + + throw invalidChar(read()) + }, + + zero () { + switch (c) { + case '.': + buffer += read(); + lexState = 'decimalPoint'; + return + + case 'e': + case 'E': + buffer += read(); + lexState = 'decimalExponent'; + return + + case 'x': + case 'X': + buffer += read(); + lexState = 'hexadecimal'; + return + } + + return newToken('numeric', sign * 0) + }, + + decimalInteger () { + switch (c) { + case '.': + buffer += read(); + lexState = 'decimalPoint'; + return + + case 'e': + case 'E': + buffer += read(); + lexState = 'decimalExponent'; + return + } + + if (util.isDigit(c)) { + buffer += read(); + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + decimalPointLeading () { + if (util.isDigit(c)) { + buffer += read(); + lexState = 'decimalFraction'; + return + } + + throw invalidChar(read()) + }, + + decimalPoint () { + switch (c) { + case 'e': + case 'E': + buffer += read(); + lexState = 'decimalExponent'; + return + } + + if (util.isDigit(c)) { + buffer += read(); + lexState = 'decimalFraction'; + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + decimalFraction () { + switch (c) { + case 'e': + case 'E': + buffer += read(); + lexState = 'decimalExponent'; + return + } + + if (util.isDigit(c)) { + buffer += read(); + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + decimalExponent () { + switch (c) { + case '+': + case '-': + buffer += read(); + lexState = 'decimalExponentSign'; + return + } + + if (util.isDigit(c)) { + buffer += read(); + lexState = 'decimalExponentInteger'; + return + } + + throw invalidChar(read()) + }, + + decimalExponentSign () { + if (util.isDigit(c)) { + buffer += read(); + lexState = 'decimalExponentInteger'; + return + } + + throw invalidChar(read()) + }, + + decimalExponentInteger () { + if (util.isDigit(c)) { + buffer += read(); + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + hexadecimal () { + if (util.isHexDigit(c)) { + buffer += read(); + lexState = 'hexadecimalInteger'; + return + } + + throw invalidChar(read()) + }, + + hexadecimalInteger () { + if (util.isHexDigit(c)) { + buffer += read(); + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + string () { + switch (c) { + case '\\': + read(); + buffer += escape(); + return + + case '"': + if (doubleQuote) { + read(); + return newToken('string', buffer) + } + + buffer += read(); + return + + case "'": + if (!doubleQuote) { + read(); + return newToken('string', buffer) + } + + buffer += read(); + return + + case '\n': + case '\r': + throw invalidChar(read()) + + case '\u2028': + case '\u2029': + separatorChar(c); + break + + case undefined: + throw invalidChar(read()) + } + + buffer += read(); + }, + + start () { + switch (c) { + case '{': + case '[': + return newToken('punctuator', read()) + + // This code is unreachable since the default lexState handles eof. + // case undefined: + // return newToken('eof') + } + + lexState = 'value'; + }, + + beforePropertyName () { + switch (c) { + case '$': + case '_': + buffer = read(); + lexState = 'identifierName'; + return + + case '\\': + read(); + lexState = 'identifierNameStartEscape'; + return + + case '}': + return newToken('punctuator', read()) + + case '"': + case "'": + doubleQuote = (read() === '"'); + lexState = 'string'; + return + } + + if (util.isIdStartChar(c)) { + buffer += read(); + lexState = 'identifierName'; + return + } + + throw invalidChar(read()) + }, + + afterPropertyName () { + if (c === ':') { + return newToken('punctuator', read()) + } + + throw invalidChar(read()) + }, + + beforePropertyValue () { + lexState = 'value'; + }, + + afterPropertyValue () { + switch (c) { + case ',': + case '}': + return newToken('punctuator', read()) + } + + throw invalidChar(read()) + }, + + beforeArrayValue () { + if (c === ']') { + return newToken('punctuator', read()) + } + + lexState = 'value'; + }, + + afterArrayValue () { + switch (c) { + case ',': + case ']': + return newToken('punctuator', read()) + } + + throw invalidChar(read()) + }, + + end () { + // This code is unreachable since it's handled by the default lexState. + // if (c === undefined) { + // read() + // return newToken('eof') + // } + + throw invalidChar(read()) + }, +}; + +function newToken (type, value) { + return { + type, + value, + line, + column, + } +} + +function literal (s) { + for (const c of s) { + const p = peek(); + + if (p !== c) { + throw invalidChar(read()) + } + + read(); + } +} + +function escape () { + const c = peek(); + switch (c) { + case 'b': + read(); + return '\b' + + case 'f': + read(); + return '\f' + + case 'n': + read(); + return '\n' + + case 'r': + read(); + return '\r' + + case 't': + read(); + return '\t' + + case 'v': + read(); + return '\v' + + case '0': + read(); + if (util.isDigit(peek())) { + throw invalidChar(read()) + } + + return '\0' + + case 'x': + read(); + return hexEscape() + + case 'u': + read(); + return unicodeEscape() + + case '\n': + case '\u2028': + case '\u2029': + read(); + return '' + + case '\r': + read(); + if (peek() === '\n') { + read(); + } + + return '' + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + throw invalidChar(read()) + + case undefined: + throw invalidChar(read()) + } + + return read() +} + +function hexEscape () { + let buffer = ''; + let c = peek(); + + if (!util.isHexDigit(c)) { + throw invalidChar(read()) + } + + buffer += read(); + + c = peek(); + if (!util.isHexDigit(c)) { + throw invalidChar(read()) + } + + buffer += read(); + + return String.fromCodePoint(parseInt(buffer, 16)) +} + +function unicodeEscape () { + let buffer = ''; + let count = 4; + + while (count-- > 0) { + const c = peek(); + if (!util.isHexDigit(c)) { + throw invalidChar(read()) + } + + buffer += read(); + } + + return String.fromCodePoint(parseInt(buffer, 16)) +} + +const parseStates = { + start () { + if (token.type === 'eof') { + throw invalidEOF() + } + + push(); + }, + + beforePropertyName () { + switch (token.type) { + case 'identifier': + case 'string': + key = token.value; + parseState = 'afterPropertyName'; + return + + case 'punctuator': + // This code is unreachable since it's handled by the lexState. + // if (token.value !== '}') { + // throw invalidToken() + // } + + pop(); + return + + case 'eof': + throw invalidEOF() + } + + // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + }, + + afterPropertyName () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator' || token.value !== ':') { + // throw invalidToken() + // } + + if (token.type === 'eof') { + throw invalidEOF() + } + + parseState = 'beforePropertyValue'; + }, + + beforePropertyValue () { + if (token.type === 'eof') { + throw invalidEOF() + } + + push(); + }, + + beforeArrayValue () { + if (token.type === 'eof') { + throw invalidEOF() + } + + if (token.type === 'punctuator' && token.value === ']') { + pop(); + return + } + + push(); + }, + + afterPropertyValue () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator') { + // throw invalidToken() + // } + + if (token.type === 'eof') { + throw invalidEOF() + } + + switch (token.value) { + case ',': + parseState = 'beforePropertyName'; + return + + case '}': + pop(); + } + + // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + }, + + afterArrayValue () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator') { + // throw invalidToken() + // } + + if (token.type === 'eof') { + throw invalidEOF() + } + + switch (token.value) { + case ',': + parseState = 'beforeArrayValue'; + return + + case ']': + pop(); + } + + // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + }, + + end () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'eof') { + // throw invalidToken() + // } + }, +}; + +function push () { + let value; + + switch (token.type) { + case 'punctuator': + switch (token.value) { + case '{': + value = {}; + break + + case '[': + value = []; + break + } + + break + + case 'null': + case 'boolean': + case 'numeric': + case 'string': + value = token.value; + break + + // This code is unreachable. + // default: + // throw invalidToken() + } + + if (root === undefined) { + root = value; + } else { + const parent = stack[stack.length - 1]; + if (Array.isArray(parent)) { + parent.push(value); + } else { + Object.defineProperty(parent, key, { + value, + writable: true, + enumerable: true, + configurable: true, + }); + } + } + + if (value !== null && typeof value === 'object') { + stack.push(value); + + if (Array.isArray(value)) { + parseState = 'beforeArrayValue'; + } else { + parseState = 'beforePropertyName'; + } + } else { + const current = stack[stack.length - 1]; + if (current == null) { + parseState = 'end'; + } else if (Array.isArray(current)) { + parseState = 'afterArrayValue'; + } else { + parseState = 'afterPropertyValue'; + } + } +} + +function pop () { + stack.pop(); + + const current = stack[stack.length - 1]; + if (current == null) { + parseState = 'end'; + } else if (Array.isArray(current)) { + parseState = 'afterArrayValue'; + } else { + parseState = 'afterPropertyValue'; + } +} + +// This code is unreachable. +// function invalidParseState () { +// return new Error(`JSON5: invalid parse state '${parseState}'`) +// } + +// This code is unreachable. +// function invalidLexState (state) { +// return new Error(`JSON5: invalid lex state '${state}'`) +// } + +function invalidChar (c) { + if (c === undefined) { + return syntaxError(`JSON5: invalid end of input at ${line}:${column}`) + } + + return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`) +} + +function invalidEOF () { + return syntaxError(`JSON5: invalid end of input at ${line}:${column}`) +} + +// This code is unreachable. +// function invalidToken () { +// if (token.type === 'eof') { +// return syntaxError(`JSON5: invalid end of input at ${line}:${column}`) +// } + +// const c = String.fromCodePoint(token.value.codePointAt(0)) +// return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`) +// } + +function invalidIdentifier () { + column -= 5; + return syntaxError(`JSON5: invalid identifier character at ${line}:${column}`) +} + +function separatorChar (c) { + console.warn(`JSON5: '${formatChar(c)}' in strings is not valid ECMAScript; consider escaping`); +} + +function formatChar (c) { + const replacements = { + "'": "\\'", + '"': '\\"', + '\\': '\\\\', + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t', + '\v': '\\v', + '\0': '\\0', + '\u2028': '\\u2028', + '\u2029': '\\u2029', + }; + + if (replacements[c]) { + return replacements[c] + } + + if (c < ' ') { + const hexString = c.charCodeAt(0).toString(16); + return '\\x' + ('00' + hexString).substring(hexString.length) + } + + return c +} + +function syntaxError (message) { + const err = new SyntaxError(message); + err.lineNumber = line; + err.columnNumber = column; + return err +} + +var stringify = function stringify (value, replacer, space) { + const stack = []; + let indent = ''; + let propertyList; + let replacerFunc; + let gap = ''; + let quote; + + if ( + replacer != null && + typeof replacer === 'object' && + !Array.isArray(replacer) + ) { + space = replacer.space; + quote = replacer.quote; + replacer = replacer.replacer; + } + + if (typeof replacer === 'function') { + replacerFunc = replacer; + } else if (Array.isArray(replacer)) { + propertyList = []; + for (const v of replacer) { + let item; + + if (typeof v === 'string') { + item = v; + } else if ( + typeof v === 'number' || + v instanceof String || + v instanceof Number + ) { + item = String(v); + } + + if (item !== undefined && propertyList.indexOf(item) < 0) { + propertyList.push(item); + } + } + } + + if (space instanceof Number) { + space = Number(space); + } else if (space instanceof String) { + space = String(space); + } + + if (typeof space === 'number') { + if (space > 0) { + space = Math.min(10, Math.floor(space)); + gap = ' '.substr(0, space); + } + } else if (typeof space === 'string') { + gap = space.substr(0, 10); + } + + return serializeProperty('', {'': value}) + + function serializeProperty (key, holder) { + let value = holder[key]; + if (value != null) { + if (typeof value.toJSON5 === 'function') { + value = value.toJSON5(key); + } else if (typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + } + + if (replacerFunc) { + value = replacerFunc.call(holder, key, value); + } + + if (value instanceof Number) { + value = Number(value); + } else if (value instanceof String) { + value = String(value); + } else if (value instanceof Boolean) { + value = value.valueOf(); + } + + switch (value) { + case null: return 'null' + case true: return 'true' + case false: return 'false' + } + + if (typeof value === 'string') { + return quoteString(value, false) + } + + if (typeof value === 'number') { + return String(value) + } + + if (typeof value === 'object') { + return Array.isArray(value) ? serializeArray(value) : serializeObject(value) + } + + return undefined + } + + function quoteString (value) { + const quotes = { + "'": 0.1, + '"': 0.2, + }; + + const replacements = { + "'": "\\'", + '"': '\\"', + '\\': '\\\\', + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t', + '\v': '\\v', + '\0': '\\0', + '\u2028': '\\u2028', + '\u2029': '\\u2029', + }; + + let product = ''; + + for (let i = 0; i < value.length; i++) { + const c = value[i]; + switch (c) { + case "'": + case '"': + quotes[c]++; + product += c; + continue + + case '\0': + if (util.isDigit(value[i + 1])) { + product += '\\x00'; + continue + } + } + + if (replacements[c]) { + product += replacements[c]; + continue + } + + if (c < ' ') { + let hexString = c.charCodeAt(0).toString(16); + product += '\\x' + ('00' + hexString).substring(hexString.length); + continue + } + + product += c; + } + + const quoteChar = quote || Object.keys(quotes).reduce((a, b) => (quotes[a] < quotes[b]) ? a : b); + + product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]); + + return quoteChar + product + quoteChar + } + + function serializeObject (value) { + if (stack.indexOf(value) >= 0) { + throw TypeError('Converting circular structure to JSON5') + } + + stack.push(value); + + let stepback = indent; + indent = indent + gap; + + let keys = propertyList || Object.keys(value); + let partial = []; + for (const key of keys) { + const propertyString = serializeProperty(key, value); + if (propertyString !== undefined) { + let member = serializeKey(key) + ':'; + if (gap !== '') { + member += ' '; + } + member += propertyString; + partial.push(member); + } + } + + let final; + if (partial.length === 0) { + final = '{}'; + } else { + let properties; + if (gap === '') { + properties = partial.join(','); + final = '{' + properties + '}'; + } else { + let separator = ',\n' + indent; + properties = partial.join(separator); + final = '{\n' + indent + properties + ',\n' + stepback + '}'; + } + } + + stack.pop(); + indent = stepback; + return final + } + + function serializeKey (key) { + if (key.length === 0) { + return quoteString(key, true) + } + + const firstChar = String.fromCodePoint(key.codePointAt(0)); + if (!util.isIdStartChar(firstChar)) { + return quoteString(key, true) + } + + for (let i = firstChar.length; i < key.length; i++) { + if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) { + return quoteString(key, true) + } + } + + return key + } + + function serializeArray (value) { + if (stack.indexOf(value) >= 0) { + throw TypeError('Converting circular structure to JSON5') + } + + stack.push(value); + + let stepback = indent; + indent = indent + gap; + + let partial = []; + for (let i = 0; i < value.length; i++) { + const propertyString = serializeProperty(String(i), value); + partial.push((propertyString !== undefined) ? propertyString : 'null'); + } + + let final; + if (partial.length === 0) { + final = '[]'; + } else { + if (gap === '') { + let properties = partial.join(','); + final = '[' + properties + ']'; + } else { + let separator = ',\n' + indent; + let properties = partial.join(separator); + final = '[\n' + indent + properties + ',\n' + stepback + ']'; + } + } + + stack.pop(); + indent = stepback; + return final + } +}; + +const JSON5 = { + parse, + stringify, +}; + +var lib = JSON5; + +export default lib; diff --git a/node_modules/json5/lib/cli.js b/node_modules/json5/lib/cli.js new file mode 100755 index 0000000..93cb809 --- /dev/null +++ b/node_modules/json5/lib/cli.js @@ -0,0 +1,152 @@ +#!/usr/bin/env node + +const fs = require('fs') +const path = require('path') +const pkg = require('../package.json') +const JSON5 = require('./') + +const argv = parseArgs() + +if (argv.version) { + version() +} else if (argv.help) { + usage() +} else { + const inFilename = argv.defaults[0] + + let readStream + if (inFilename) { + readStream = fs.createReadStream(inFilename) + } else { + readStream = process.stdin + } + + let json5 = '' + readStream.on('data', data => { + json5 += data + }) + + readStream.on('end', () => { + let space + if (argv.space === 't' || argv.space === 'tab') { + space = '\t' + } else { + space = Number(argv.space) + } + + let value + try { + value = JSON5.parse(json5) + if (!argv.validate) { + const json = JSON.stringify(value, null, space) + + let writeStream + + // --convert is for backward compatibility with v0.5.1. If + // specified with and not --out-file, then a file with + // the same name but with a .json extension will be written. + if (argv.convert && inFilename && !argv.outFile) { + const parsedFilename = path.parse(inFilename) + const outFilename = path.format( + Object.assign( + parsedFilename, + {base: path.basename(parsedFilename.base, parsedFilename.ext) + '.json'} + ) + ) + + writeStream = fs.createWriteStream(outFilename) + } else if (argv.outFile) { + writeStream = fs.createWriteStream(argv.outFile) + } else { + writeStream = process.stdout + } + + writeStream.write(json) + } + } catch (err) { + console.error(err.message) + process.exit(1) + } + }) +} + +function parseArgs () { + let convert + let space + let validate + let outFile + let version + let help + const defaults = [] + + const args = process.argv.slice(2) + for (let i = 0; i < args.length; i++) { + const arg = args[i] + switch (arg) { + case '--convert': + case '-c': + convert = true + break + + case '--space': + case '-s': + space = args[++i] + break + + case '--validate': + case '-v': + validate = true + break + + case '--out-file': + case '-o': + outFile = args[++i] + break + + case '--version': + case '-V': + version = true + break + + case '--help': + case '-h': + help = true + break + + default: + defaults.push(arg) + break + } + } + + return { + convert, + space, + validate, + outFile, + version, + help, + defaults, + } +} + +function version () { + console.log(pkg.version) +} + +function usage () { + console.log( + ` + Usage: json5 [options] + + If is not provided, then STDIN is used. + + Options: + + -s, --space The number of spaces to indent or 't' for tabs + -o, --out-file [file] Output to the specified file, otherwise STDOUT + -v, --validate Validate JSON5 but do not output JSON + -V, --version Output the version number + -h, --help Output usage information` + ) +} diff --git a/node_modules/json5/lib/index.d.ts b/node_modules/json5/lib/index.d.ts new file mode 100644 index 0000000..1c45bca --- /dev/null +++ b/node_modules/json5/lib/index.d.ts @@ -0,0 +1,4 @@ +import parse = require('./parse') +import stringify = require('./stringify') + +export {parse, stringify} diff --git a/node_modules/json5/lib/index.js b/node_modules/json5/lib/index.js new file mode 100644 index 0000000..3679638 --- /dev/null +++ b/node_modules/json5/lib/index.js @@ -0,0 +1,9 @@ +const parse = require('./parse') +const stringify = require('./stringify') + +const JSON5 = { + parse, + stringify, +} + +module.exports = JSON5 diff --git a/node_modules/json5/lib/parse.d.ts b/node_modules/json5/lib/parse.d.ts new file mode 100644 index 0000000..8c8d883 --- /dev/null +++ b/node_modules/json5/lib/parse.d.ts @@ -0,0 +1,15 @@ +/** + * Parses a JSON5 string, constructing the JavaScript value or object described + * by the string. + * @template T The type of the return value. + * @param text The string to parse as JSON5. + * @param reviver A function that prescribes how the value originally produced + * by parsing is transformed before being returned. + * @returns The JavaScript value converted from the JSON5 string. + */ +declare function parse( + text: string, + reviver?: ((this: any, key: string, value: any) => any) | null, +): T + +export = parse diff --git a/node_modules/json5/lib/parse.js b/node_modules/json5/lib/parse.js new file mode 100644 index 0000000..da2078a --- /dev/null +++ b/node_modules/json5/lib/parse.js @@ -0,0 +1,1114 @@ +const util = require('./util') + +let source +let parseState +let stack +let pos +let line +let column +let token +let key +let root + +module.exports = function parse (text, reviver) { + source = String(text) + parseState = 'start' + stack = [] + pos = 0 + line = 1 + column = 0 + token = undefined + key = undefined + root = undefined + + do { + token = lex() + + // This code is unreachable. + // if (!parseStates[parseState]) { + // throw invalidParseState() + // } + + parseStates[parseState]() + } while (token.type !== 'eof') + + if (typeof reviver === 'function') { + return internalize({'': root}, '', reviver) + } + + return root +} + +function internalize (holder, name, reviver) { + const value = holder[name] + if (value != null && typeof value === 'object') { + if (Array.isArray(value)) { + for (let i = 0; i < value.length; i++) { + const key = String(i) + const replacement = internalize(value, key, reviver) + if (replacement === undefined) { + delete value[key] + } else { + Object.defineProperty(value, key, { + value: replacement, + writable: true, + enumerable: true, + configurable: true, + }) + } + } + } else { + for (const key in value) { + const replacement = internalize(value, key, reviver) + if (replacement === undefined) { + delete value[key] + } else { + Object.defineProperty(value, key, { + value: replacement, + writable: true, + enumerable: true, + configurable: true, + }) + } + } + } + } + + return reviver.call(holder, name, value) +} + +let lexState +let buffer +let doubleQuote +let sign +let c + +function lex () { + lexState = 'default' + buffer = '' + doubleQuote = false + sign = 1 + + for (;;) { + c = peek() + + // This code is unreachable. + // if (!lexStates[lexState]) { + // throw invalidLexState(lexState) + // } + + const token = lexStates[lexState]() + if (token) { + return token + } + } +} + +function peek () { + if (source[pos]) { + return String.fromCodePoint(source.codePointAt(pos)) + } +} + +function read () { + const c = peek() + + if (c === '\n') { + line++ + column = 0 + } else if (c) { + column += c.length + } else { + column++ + } + + if (c) { + pos += c.length + } + + return c +} + +const lexStates = { + default () { + switch (c) { + case '\t': + case '\v': + case '\f': + case ' ': + case '\u00A0': + case '\uFEFF': + case '\n': + case '\r': + case '\u2028': + case '\u2029': + read() + return + + case '/': + read() + lexState = 'comment' + return + + case undefined: + read() + return newToken('eof') + } + + if (util.isSpaceSeparator(c)) { + read() + return + } + + // This code is unreachable. + // if (!lexStates[parseState]) { + // throw invalidLexState(parseState) + // } + + return lexStates[parseState]() + }, + + comment () { + switch (c) { + case '*': + read() + lexState = 'multiLineComment' + return + + case '/': + read() + lexState = 'singleLineComment' + return + } + + throw invalidChar(read()) + }, + + multiLineComment () { + switch (c) { + case '*': + read() + lexState = 'multiLineCommentAsterisk' + return + + case undefined: + throw invalidChar(read()) + } + + read() + }, + + multiLineCommentAsterisk () { + switch (c) { + case '*': + read() + return + + case '/': + read() + lexState = 'default' + return + + case undefined: + throw invalidChar(read()) + } + + read() + lexState = 'multiLineComment' + }, + + singleLineComment () { + switch (c) { + case '\n': + case '\r': + case '\u2028': + case '\u2029': + read() + lexState = 'default' + return + + case undefined: + read() + return newToken('eof') + } + + read() + }, + + value () { + switch (c) { + case '{': + case '[': + return newToken('punctuator', read()) + + case 'n': + read() + literal('ull') + return newToken('null', null) + + case 't': + read() + literal('rue') + return newToken('boolean', true) + + case 'f': + read() + literal('alse') + return newToken('boolean', false) + + case '-': + case '+': + if (read() === '-') { + sign = -1 + } + + lexState = 'sign' + return + + case '.': + buffer = read() + lexState = 'decimalPointLeading' + return + + case '0': + buffer = read() + lexState = 'zero' + return + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + buffer = read() + lexState = 'decimalInteger' + return + + case 'I': + read() + literal('nfinity') + return newToken('numeric', Infinity) + + case 'N': + read() + literal('aN') + return newToken('numeric', NaN) + + case '"': + case "'": + doubleQuote = (read() === '"') + buffer = '' + lexState = 'string' + return + } + + throw invalidChar(read()) + }, + + identifierNameStartEscape () { + if (c !== 'u') { + throw invalidChar(read()) + } + + read() + const u = unicodeEscape() + switch (u) { + case '$': + case '_': + break + + default: + if (!util.isIdStartChar(u)) { + throw invalidIdentifier() + } + + break + } + + buffer += u + lexState = 'identifierName' + }, + + identifierName () { + switch (c) { + case '$': + case '_': + case '\u200C': + case '\u200D': + buffer += read() + return + + case '\\': + read() + lexState = 'identifierNameEscape' + return + } + + if (util.isIdContinueChar(c)) { + buffer += read() + return + } + + return newToken('identifier', buffer) + }, + + identifierNameEscape () { + if (c !== 'u') { + throw invalidChar(read()) + } + + read() + const u = unicodeEscape() + switch (u) { + case '$': + case '_': + case '\u200C': + case '\u200D': + break + + default: + if (!util.isIdContinueChar(u)) { + throw invalidIdentifier() + } + + break + } + + buffer += u + lexState = 'identifierName' + }, + + sign () { + switch (c) { + case '.': + buffer = read() + lexState = 'decimalPointLeading' + return + + case '0': + buffer = read() + lexState = 'zero' + return + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + buffer = read() + lexState = 'decimalInteger' + return + + case 'I': + read() + literal('nfinity') + return newToken('numeric', sign * Infinity) + + case 'N': + read() + literal('aN') + return newToken('numeric', NaN) + } + + throw invalidChar(read()) + }, + + zero () { + switch (c) { + case '.': + buffer += read() + lexState = 'decimalPoint' + return + + case 'e': + case 'E': + buffer += read() + lexState = 'decimalExponent' + return + + case 'x': + case 'X': + buffer += read() + lexState = 'hexadecimal' + return + } + + return newToken('numeric', sign * 0) + }, + + decimalInteger () { + switch (c) { + case '.': + buffer += read() + lexState = 'decimalPoint' + return + + case 'e': + case 'E': + buffer += read() + lexState = 'decimalExponent' + return + } + + if (util.isDigit(c)) { + buffer += read() + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + decimalPointLeading () { + if (util.isDigit(c)) { + buffer += read() + lexState = 'decimalFraction' + return + } + + throw invalidChar(read()) + }, + + decimalPoint () { + switch (c) { + case 'e': + case 'E': + buffer += read() + lexState = 'decimalExponent' + return + } + + if (util.isDigit(c)) { + buffer += read() + lexState = 'decimalFraction' + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + decimalFraction () { + switch (c) { + case 'e': + case 'E': + buffer += read() + lexState = 'decimalExponent' + return + } + + if (util.isDigit(c)) { + buffer += read() + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + decimalExponent () { + switch (c) { + case '+': + case '-': + buffer += read() + lexState = 'decimalExponentSign' + return + } + + if (util.isDigit(c)) { + buffer += read() + lexState = 'decimalExponentInteger' + return + } + + throw invalidChar(read()) + }, + + decimalExponentSign () { + if (util.isDigit(c)) { + buffer += read() + lexState = 'decimalExponentInteger' + return + } + + throw invalidChar(read()) + }, + + decimalExponentInteger () { + if (util.isDigit(c)) { + buffer += read() + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + hexadecimal () { + if (util.isHexDigit(c)) { + buffer += read() + lexState = 'hexadecimalInteger' + return + } + + throw invalidChar(read()) + }, + + hexadecimalInteger () { + if (util.isHexDigit(c)) { + buffer += read() + return + } + + return newToken('numeric', sign * Number(buffer)) + }, + + string () { + switch (c) { + case '\\': + read() + buffer += escape() + return + + case '"': + if (doubleQuote) { + read() + return newToken('string', buffer) + } + + buffer += read() + return + + case "'": + if (!doubleQuote) { + read() + return newToken('string', buffer) + } + + buffer += read() + return + + case '\n': + case '\r': + throw invalidChar(read()) + + case '\u2028': + case '\u2029': + separatorChar(c) + break + + case undefined: + throw invalidChar(read()) + } + + buffer += read() + }, + + start () { + switch (c) { + case '{': + case '[': + return newToken('punctuator', read()) + + // This code is unreachable since the default lexState handles eof. + // case undefined: + // return newToken('eof') + } + + lexState = 'value' + }, + + beforePropertyName () { + switch (c) { + case '$': + case '_': + buffer = read() + lexState = 'identifierName' + return + + case '\\': + read() + lexState = 'identifierNameStartEscape' + return + + case '}': + return newToken('punctuator', read()) + + case '"': + case "'": + doubleQuote = (read() === '"') + lexState = 'string' + return + } + + if (util.isIdStartChar(c)) { + buffer += read() + lexState = 'identifierName' + return + } + + throw invalidChar(read()) + }, + + afterPropertyName () { + if (c === ':') { + return newToken('punctuator', read()) + } + + throw invalidChar(read()) + }, + + beforePropertyValue () { + lexState = 'value' + }, + + afterPropertyValue () { + switch (c) { + case ',': + case '}': + return newToken('punctuator', read()) + } + + throw invalidChar(read()) + }, + + beforeArrayValue () { + if (c === ']') { + return newToken('punctuator', read()) + } + + lexState = 'value' + }, + + afterArrayValue () { + switch (c) { + case ',': + case ']': + return newToken('punctuator', read()) + } + + throw invalidChar(read()) + }, + + end () { + // This code is unreachable since it's handled by the default lexState. + // if (c === undefined) { + // read() + // return newToken('eof') + // } + + throw invalidChar(read()) + }, +} + +function newToken (type, value) { + return { + type, + value, + line, + column, + } +} + +function literal (s) { + for (const c of s) { + const p = peek() + + if (p !== c) { + throw invalidChar(read()) + } + + read() + } +} + +function escape () { + const c = peek() + switch (c) { + case 'b': + read() + return '\b' + + case 'f': + read() + return '\f' + + case 'n': + read() + return '\n' + + case 'r': + read() + return '\r' + + case 't': + read() + return '\t' + + case 'v': + read() + return '\v' + + case '0': + read() + if (util.isDigit(peek())) { + throw invalidChar(read()) + } + + return '\0' + + case 'x': + read() + return hexEscape() + + case 'u': + read() + return unicodeEscape() + + case '\n': + case '\u2028': + case '\u2029': + read() + return '' + + case '\r': + read() + if (peek() === '\n') { + read() + } + + return '' + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + throw invalidChar(read()) + + case undefined: + throw invalidChar(read()) + } + + return read() +} + +function hexEscape () { + let buffer = '' + let c = peek() + + if (!util.isHexDigit(c)) { + throw invalidChar(read()) + } + + buffer += read() + + c = peek() + if (!util.isHexDigit(c)) { + throw invalidChar(read()) + } + + buffer += read() + + return String.fromCodePoint(parseInt(buffer, 16)) +} + +function unicodeEscape () { + let buffer = '' + let count = 4 + + while (count-- > 0) { + const c = peek() + if (!util.isHexDigit(c)) { + throw invalidChar(read()) + } + + buffer += read() + } + + return String.fromCodePoint(parseInt(buffer, 16)) +} + +const parseStates = { + start () { + if (token.type === 'eof') { + throw invalidEOF() + } + + push() + }, + + beforePropertyName () { + switch (token.type) { + case 'identifier': + case 'string': + key = token.value + parseState = 'afterPropertyName' + return + + case 'punctuator': + // This code is unreachable since it's handled by the lexState. + // if (token.value !== '}') { + // throw invalidToken() + // } + + pop() + return + + case 'eof': + throw invalidEOF() + } + + // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + }, + + afterPropertyName () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator' || token.value !== ':') { + // throw invalidToken() + // } + + if (token.type === 'eof') { + throw invalidEOF() + } + + parseState = 'beforePropertyValue' + }, + + beforePropertyValue () { + if (token.type === 'eof') { + throw invalidEOF() + } + + push() + }, + + beforeArrayValue () { + if (token.type === 'eof') { + throw invalidEOF() + } + + if (token.type === 'punctuator' && token.value === ']') { + pop() + return + } + + push() + }, + + afterPropertyValue () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator') { + // throw invalidToken() + // } + + if (token.type === 'eof') { + throw invalidEOF() + } + + switch (token.value) { + case ',': + parseState = 'beforePropertyName' + return + + case '}': + pop() + } + + // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + }, + + afterArrayValue () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator') { + // throw invalidToken() + // } + + if (token.type === 'eof') { + throw invalidEOF() + } + + switch (token.value) { + case ',': + parseState = 'beforeArrayValue' + return + + case ']': + pop() + } + + // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + }, + + end () { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'eof') { + // throw invalidToken() + // } + }, +} + +function push () { + let value + + switch (token.type) { + case 'punctuator': + switch (token.value) { + case '{': + value = {} + break + + case '[': + value = [] + break + } + + break + + case 'null': + case 'boolean': + case 'numeric': + case 'string': + value = token.value + break + + // This code is unreachable. + // default: + // throw invalidToken() + } + + if (root === undefined) { + root = value + } else { + const parent = stack[stack.length - 1] + if (Array.isArray(parent)) { + parent.push(value) + } else { + Object.defineProperty(parent, key, { + value, + writable: true, + enumerable: true, + configurable: true, + }) + } + } + + if (value !== null && typeof value === 'object') { + stack.push(value) + + if (Array.isArray(value)) { + parseState = 'beforeArrayValue' + } else { + parseState = 'beforePropertyName' + } + } else { + const current = stack[stack.length - 1] + if (current == null) { + parseState = 'end' + } else if (Array.isArray(current)) { + parseState = 'afterArrayValue' + } else { + parseState = 'afterPropertyValue' + } + } +} + +function pop () { + stack.pop() + + const current = stack[stack.length - 1] + if (current == null) { + parseState = 'end' + } else if (Array.isArray(current)) { + parseState = 'afterArrayValue' + } else { + parseState = 'afterPropertyValue' + } +} + +// This code is unreachable. +// function invalidParseState () { +// return new Error(`JSON5: invalid parse state '${parseState}'`) +// } + +// This code is unreachable. +// function invalidLexState (state) { +// return new Error(`JSON5: invalid lex state '${state}'`) +// } + +function invalidChar (c) { + if (c === undefined) { + return syntaxError(`JSON5: invalid end of input at ${line}:${column}`) + } + + return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`) +} + +function invalidEOF () { + return syntaxError(`JSON5: invalid end of input at ${line}:${column}`) +} + +// This code is unreachable. +// function invalidToken () { +// if (token.type === 'eof') { +// return syntaxError(`JSON5: invalid end of input at ${line}:${column}`) +// } + +// const c = String.fromCodePoint(token.value.codePointAt(0)) +// return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`) +// } + +function invalidIdentifier () { + column -= 5 + return syntaxError(`JSON5: invalid identifier character at ${line}:${column}`) +} + +function separatorChar (c) { + console.warn(`JSON5: '${formatChar(c)}' in strings is not valid ECMAScript; consider escaping`) +} + +function formatChar (c) { + const replacements = { + "'": "\\'", + '"': '\\"', + '\\': '\\\\', + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t', + '\v': '\\v', + '\0': '\\0', + '\u2028': '\\u2028', + '\u2029': '\\u2029', + } + + if (replacements[c]) { + return replacements[c] + } + + if (c < ' ') { + const hexString = c.charCodeAt(0).toString(16) + return '\\x' + ('00' + hexString).substring(hexString.length) + } + + return c +} + +function syntaxError (message) { + const err = new SyntaxError(message) + err.lineNumber = line + err.columnNumber = column + return err +} diff --git a/node_modules/json5/lib/register.js b/node_modules/json5/lib/register.js new file mode 100644 index 0000000..935cdba --- /dev/null +++ b/node_modules/json5/lib/register.js @@ -0,0 +1,13 @@ +const fs = require('fs') +const JSON5 = require('./') + +// eslint-disable-next-line node/no-deprecated-api +require.extensions['.json5'] = function (module, filename) { + const content = fs.readFileSync(filename, 'utf8') + try { + module.exports = JSON5.parse(content) + } catch (err) { + err.message = filename + ': ' + err.message + throw err + } +} diff --git a/node_modules/json5/lib/require.js b/node_modules/json5/lib/require.js new file mode 100644 index 0000000..3aa29be --- /dev/null +++ b/node_modules/json5/lib/require.js @@ -0,0 +1,4 @@ +// This file is for backward compatibility with v0.5.1. +require('./register') + +console.warn("'json5/require' is deprecated. Please use 'json5/register' instead.") diff --git a/node_modules/json5/lib/stringify.d.ts b/node_modules/json5/lib/stringify.d.ts new file mode 100644 index 0000000..3c34838 --- /dev/null +++ b/node_modules/json5/lib/stringify.d.ts @@ -0,0 +1,89 @@ +declare type StringifyOptions = { + /** + * A function that alters the behavior of the stringification process, or an + * array of String and Number objects that serve as a allowlist for + * selecting/filtering the properties of the value object to be included in + * the JSON5 string. If this value is null or not provided, all properties + * of the object are included in the resulting JSON5 string. + */ + replacer?: + | ((this: any, key: string, value: any) => any) + | (string | number)[] + | null + + /** + * A String or Number object that's used to insert white space into the + * output JSON5 string for readability purposes. If this is a Number, it + * indicates the number of space characters to use as white space; this + * number is capped at 10 (if it is greater, the value is just 10). Values + * less than 1 indicate that no space should be used. If this is a String, + * the string (or the first 10 characters of the string, if it's longer than + * that) is used as white space. If this parameter is not provided (or is + * null), no white space is used. If white space is used, trailing commas + * will be used in objects and arrays. + */ + space?: string | number | null + + /** + * A String representing the quote character to use when serializing + * strings. + */ + quote?: string | null +} + +/** + * Converts a JavaScript value to a JSON5 string. + * @param value The value to convert to a JSON5 string. + * @param replacer A function that alters the behavior of the stringification + * process. If this value is null or not provided, all properties of the object + * are included in the resulting JSON5 string. + * @param space A String or Number object that's used to insert white space into + * the output JSON5 string for readability purposes. If this is a Number, it + * indicates the number of space characters to use as white space; this number + * is capped at 10 (if it is greater, the value is just 10). Values less than 1 + * indicate that no space should be used. If this is a String, the string (or + * the first 10 characters of the string, if it's longer than that) is used as + * white space. If this parameter is not provided (or is null), no white space + * is used. If white space is used, trailing commas will be used in objects and + * arrays. + * @returns The JSON5 string converted from the JavaScript value. + */ +declare function stringify( + value: any, + replacer?: ((this: any, key: string, value: any) => any) | null, + space?: string | number | null, +): string + +/** + * Converts a JavaScript value to a JSON5 string. + * @param value The value to convert to a JSON5 string. + * @param replacer An array of String and Number objects that serve as a + * allowlist for selecting/filtering the properties of the value object to be + * included in the JSON5 string. If this value is null or not provided, all + * properties of the object are included in the resulting JSON5 string. + * @param space A String or Number object that's used to insert white space into + * the output JSON5 string for readability purposes. If this is a Number, it + * indicates the number of space characters to use as white space; this number + * is capped at 10 (if it is greater, the value is just 10). Values less than 1 + * indicate that no space should be used. If this is a String, the string (or + * the first 10 characters of the string, if it's longer than that) is used as + * white space. If this parameter is not provided (or is null), no white space + * is used. If white space is used, trailing commas will be used in objects and + * arrays. + * @returns The JSON5 string converted from the JavaScript value. + */ +declare function stringify( + value: any, + replacer: (string | number)[], + space?: string | number | null, +): string + +/** + * Converts a JavaScript value to a JSON5 string. + * @param value The value to convert to a JSON5 string. + * @param options An object specifying options. + * @returns The JSON5 string converted from the JavaScript value. + */ +declare function stringify(value: any, options: StringifyOptions): string + +export = stringify diff --git a/node_modules/json5/lib/stringify.js b/node_modules/json5/lib/stringify.js new file mode 100644 index 0000000..7cb3b0e --- /dev/null +++ b/node_modules/json5/lib/stringify.js @@ -0,0 +1,261 @@ +const util = require('./util') + +module.exports = function stringify (value, replacer, space) { + const stack = [] + let indent = '' + let propertyList + let replacerFunc + let gap = '' + let quote + + if ( + replacer != null && + typeof replacer === 'object' && + !Array.isArray(replacer) + ) { + space = replacer.space + quote = replacer.quote + replacer = replacer.replacer + } + + if (typeof replacer === 'function') { + replacerFunc = replacer + } else if (Array.isArray(replacer)) { + propertyList = [] + for (const v of replacer) { + let item + + if (typeof v === 'string') { + item = v + } else if ( + typeof v === 'number' || + v instanceof String || + v instanceof Number + ) { + item = String(v) + } + + if (item !== undefined && propertyList.indexOf(item) < 0) { + propertyList.push(item) + } + } + } + + if (space instanceof Number) { + space = Number(space) + } else if (space instanceof String) { + space = String(space) + } + + if (typeof space === 'number') { + if (space > 0) { + space = Math.min(10, Math.floor(space)) + gap = ' '.substr(0, space) + } + } else if (typeof space === 'string') { + gap = space.substr(0, 10) + } + + return serializeProperty('', {'': value}) + + function serializeProperty (key, holder) { + let value = holder[key] + if (value != null) { + if (typeof value.toJSON5 === 'function') { + value = value.toJSON5(key) + } else if (typeof value.toJSON === 'function') { + value = value.toJSON(key) + } + } + + if (replacerFunc) { + value = replacerFunc.call(holder, key, value) + } + + if (value instanceof Number) { + value = Number(value) + } else if (value instanceof String) { + value = String(value) + } else if (value instanceof Boolean) { + value = value.valueOf() + } + + switch (value) { + case null: return 'null' + case true: return 'true' + case false: return 'false' + } + + if (typeof value === 'string') { + return quoteString(value, false) + } + + if (typeof value === 'number') { + return String(value) + } + + if (typeof value === 'object') { + return Array.isArray(value) ? serializeArray(value) : serializeObject(value) + } + + return undefined + } + + function quoteString (value) { + const quotes = { + "'": 0.1, + '"': 0.2, + } + + const replacements = { + "'": "\\'", + '"': '\\"', + '\\': '\\\\', + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t', + '\v': '\\v', + '\0': '\\0', + '\u2028': '\\u2028', + '\u2029': '\\u2029', + } + + let product = '' + + for (let i = 0; i < value.length; i++) { + const c = value[i] + switch (c) { + case "'": + case '"': + quotes[c]++ + product += c + continue + + case '\0': + if (util.isDigit(value[i + 1])) { + product += '\\x00' + continue + } + } + + if (replacements[c]) { + product += replacements[c] + continue + } + + if (c < ' ') { + let hexString = c.charCodeAt(0).toString(16) + product += '\\x' + ('00' + hexString).substring(hexString.length) + continue + } + + product += c + } + + const quoteChar = quote || Object.keys(quotes).reduce((a, b) => (quotes[a] < quotes[b]) ? a : b) + + product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]) + + return quoteChar + product + quoteChar + } + + function serializeObject (value) { + if (stack.indexOf(value) >= 0) { + throw TypeError('Converting circular structure to JSON5') + } + + stack.push(value) + + let stepback = indent + indent = indent + gap + + let keys = propertyList || Object.keys(value) + let partial = [] + for (const key of keys) { + const propertyString = serializeProperty(key, value) + if (propertyString !== undefined) { + let member = serializeKey(key) + ':' + if (gap !== '') { + member += ' ' + } + member += propertyString + partial.push(member) + } + } + + let final + if (partial.length === 0) { + final = '{}' + } else { + let properties + if (gap === '') { + properties = partial.join(',') + final = '{' + properties + '}' + } else { + let separator = ',\n' + indent + properties = partial.join(separator) + final = '{\n' + indent + properties + ',\n' + stepback + '}' + } + } + + stack.pop() + indent = stepback + return final + } + + function serializeKey (key) { + if (key.length === 0) { + return quoteString(key, true) + } + + const firstChar = String.fromCodePoint(key.codePointAt(0)) + if (!util.isIdStartChar(firstChar)) { + return quoteString(key, true) + } + + for (let i = firstChar.length; i < key.length; i++) { + if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) { + return quoteString(key, true) + } + } + + return key + } + + function serializeArray (value) { + if (stack.indexOf(value) >= 0) { + throw TypeError('Converting circular structure to JSON5') + } + + stack.push(value) + + let stepback = indent + indent = indent + gap + + let partial = [] + for (let i = 0; i < value.length; i++) { + const propertyString = serializeProperty(String(i), value) + partial.push((propertyString !== undefined) ? propertyString : 'null') + } + + let final + if (partial.length === 0) { + final = '[]' + } else { + if (gap === '') { + let properties = partial.join(',') + final = '[' + properties + ']' + } else { + let separator = ',\n' + indent + let properties = partial.join(separator) + final = '[\n' + indent + properties + ',\n' + stepback + ']' + } + } + + stack.pop() + indent = stepback + return final + } +} diff --git a/node_modules/json5/lib/unicode.d.ts b/node_modules/json5/lib/unicode.d.ts new file mode 100644 index 0000000..610f805 --- /dev/null +++ b/node_modules/json5/lib/unicode.d.ts @@ -0,0 +1,3 @@ +export declare const Space_Separator: RegExp +export declare const ID_Start: RegExp +export declare const ID_Continue: RegExp diff --git a/node_modules/json5/lib/unicode.js b/node_modules/json5/lib/unicode.js new file mode 100644 index 0000000..215ccd8 --- /dev/null +++ b/node_modules/json5/lib/unicode.js @@ -0,0 +1,4 @@ +// This is a generated file. Do not edit. +module.exports.Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/ +module.exports.ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-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DE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/ +module.exports.ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\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DF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\u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\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ diff --git a/node_modules/json5/lib/util.d.ts b/node_modules/json5/lib/util.d.ts new file mode 100644 index 0000000..a940cea --- /dev/null +++ b/node_modules/json5/lib/util.d.ts @@ -0,0 +1,5 @@ +export declare function isSpaceSeparator(c?: string): boolean +export declare function isIdStartChar(c?: string): boolean +export declare function isIdContinueChar(c?: string): boolean +export declare function isDigit(c?: string): boolean +export declare function isHexDigit(c?: string): boolean diff --git a/node_modules/json5/lib/util.js b/node_modules/json5/lib/util.js new file mode 100644 index 0000000..40bfe2f --- /dev/null +++ b/node_modules/json5/lib/util.js @@ -0,0 +1,35 @@ +const unicode = require('../lib/unicode') + +module.exports = { + isSpaceSeparator (c) { + return typeof c === 'string' && unicode.Space_Separator.test(c) + }, + + isIdStartChar (c) { + return typeof c === 'string' && ( + (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c === '$') || (c === '_') || + unicode.ID_Start.test(c) + ) + }, + + isIdContinueChar (c) { + return typeof c === 'string' && ( + (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || + (c === '$') || (c === '_') || + (c === '\u200C') || (c === '\u200D') || + unicode.ID_Continue.test(c) + ) + }, + + isDigit (c) { + return typeof c === 'string' && /[0-9]/.test(c) + }, + + isHexDigit (c) { + return typeof c === 'string' && /[0-9A-Fa-f]/.test(c) + }, +} diff --git a/node_modules/json5/package.json b/node_modules/json5/package.json new file mode 100644 index 0000000..60c51d9 --- /dev/null +++ b/node_modules/json5/package.json @@ -0,0 +1,72 @@ +{ + "name": "json5", + "version": "2.2.3", + "description": "JSON for Humans", + "main": "lib/index.js", + "module": "dist/index.mjs", + "bin": "lib/cli.js", + "browser": "dist/index.js", + "types": "lib/index.d.ts", + "files": [ + "lib/", + "dist/" + ], + "engines": { + "node": ">=6" + }, + "scripts": { + "build": "rollup -c", + "build-package": "node build/package.js", + "build-unicode": "node build/unicode.js", + "coverage": "tap --coverage-report html test", + "lint": "eslint --fix .", + "lint-report": "eslint .", + "prepublishOnly": "npm run production", + "preversion": "npm run production", + "production": "run-s test build", + "tap": "tap -Rspec --100 test", + "test": "run-s lint-report tap", + "version": "npm run build-package && git add package.json5" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/json5/json5.git" + }, + "keywords": [ + "json", + "json5", + "es5", + "es2015", + "ecmascript" + ], + "author": "Aseem Kishore ", + "contributors": [ + "Max Nanasy ", + "Andrew Eisenberg ", + "Jordan Tucker " + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/json5/json5/issues" + }, + "homepage": "http://json5.org/", + "devDependencies": { + "core-js": "^2.6.5", + "eslint": "^5.15.3", + "eslint-config-standard": "^12.0.0", + "eslint-plugin-import": "^2.16.0", + "eslint-plugin-node": "^8.0.1", + "eslint-plugin-promise": "^4.0.1", + "eslint-plugin-standard": "^4.0.0", + "npm-run-all": "^4.1.5", + "regenerate": "^1.4.0", + "rollup": "^0.64.1", + "rollup-plugin-buble": "^0.19.6", + "rollup-plugin-commonjs": "^9.2.1", + "rollup-plugin-node-resolve": "^3.4.0", + "rollup-plugin-terser": "^1.0.1", + "sinon": "^6.3.5", + "tap": "^12.6.0", + "unicode-10.0.0": "^0.7.5" + } +} diff --git a/node_modules/loader-runner/LICENSE b/node_modules/loader-runner/LICENSE new file mode 100644 index 0000000..084338a --- /dev/null +++ b/node_modules/loader-runner/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) Tobias Koppers @sokra + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/loader-runner/README.md b/node_modules/loader-runner/README.md new file mode 100644 index 0000000..f052dd3 --- /dev/null +++ b/node_modules/loader-runner/README.md @@ -0,0 +1,53 @@ +# loader-runner + +``` js +import { runLoaders } from "loader-runner"; + +runLoaders({ + resource: "/abs/path/to/file.txt?query", + // String: Absolute path to the resource (optionally including query string) + + loaders: ["/abs/path/to/loader.js?query"], + // String[]: Absolute paths to the loaders (optionally including query string) + // {loader, options}[]: Absolute paths to the loaders with options object + + context: { minimize: true }, + // Additional loader context which is used as base context + + processResource: (loaderContext, resourcePath, callback) => { ... }, + // Optional: A function to process the resource + // Must have signature function(context, path, function(err, buffer)) + // By default readResource is used and the resource is added a fileDependency + + readResource: fs.readFile.bind(fs) + // Optional: A function to read the resource + // Only used when 'processResource' is not provided + // Must have signature function(path, function(err, buffer)) + // By default fs.readFile is used +}, function(err, result) { + // err: Error? + + // result.result: Buffer | String + // The result + // only available when no error occured + + // result.resourceBuffer: Buffer + // The raw resource as Buffer (useful for SourceMaps) + // only available when no error occured + + // result.cacheable: Bool + // Is the result cacheable or do it require reexecution? + + // result.fileDependencies: String[] + // An array of paths (existing files) on which the result depends on + + // result.missingDependencies: String[] + // An array of paths (not existing files) on which the result depends on + + // result.contextDependencies: String[] + // An array of paths (directories) on which the result depends on +}) +``` + +More documentation following... + diff --git a/node_modules/loader-runner/lib/LoaderLoadingError.js b/node_modules/loader-runner/lib/LoaderLoadingError.js new file mode 100644 index 0000000..fa1e54d --- /dev/null +++ b/node_modules/loader-runner/lib/LoaderLoadingError.js @@ -0,0 +1,11 @@ +"use strict"; + +class LoadingLoaderError extends Error { + constructor(message) { + super(message); + this.name = "LoaderRunnerError"; + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = LoadingLoaderError; diff --git a/node_modules/loader-runner/lib/LoaderRunner.js b/node_modules/loader-runner/lib/LoaderRunner.js new file mode 100644 index 0000000..5909261 --- /dev/null +++ b/node_modules/loader-runner/lib/LoaderRunner.js @@ -0,0 +1,416 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +var fs = require("fs"); +var readFile = fs.readFile.bind(fs); +var loadLoader = require("./loadLoader"); + +function utf8BufferToString(buf) { + var str = buf.toString("utf-8"); + if(str.charCodeAt(0) === 0xFEFF) { + return str.substr(1); + } else { + return str; + } +} + +const PATH_QUERY_FRAGMENT_REGEXP = /^((?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/; + +/** + * @param {string} str the path with query and fragment + * @returns {{ path: string, query: string, fragment: string }} parsed parts + */ +function parsePathQueryFragment(str) { + var match = PATH_QUERY_FRAGMENT_REGEXP.exec(str); + return { + path: match[1].replace(/\0(.)/g, "$1"), + query: match[2] ? match[2].replace(/\0(.)/g, "$1") : "", + fragment: match[3] || "" + }; +} + +function dirname(path) { + if(path === "/") return "/"; + var i = path.lastIndexOf("/"); + var j = path.lastIndexOf("\\"); + var i2 = path.indexOf("/"); + var j2 = path.indexOf("\\"); + var idx = i > j ? i : j; + var idx2 = i > j ? i2 : j2; + if(idx < 0) return path; + if(idx === idx2) return path.substr(0, idx + 1); + return path.substr(0, idx); +} + +function createLoaderObject(loader) { + var obj = { + path: null, + query: null, + fragment: null, + options: null, + ident: null, + normal: null, + pitch: null, + raw: null, + data: null, + pitchExecuted: false, + normalExecuted: false + }; + Object.defineProperty(obj, "request", { + enumerable: true, + get: function() { + return obj.path.replace(/#/g, "\0#") + obj.query.replace(/#/g, "\0#") + obj.fragment; + }, + set: function(value) { + if(typeof value === "string") { + var splittedRequest = parsePathQueryFragment(value); + obj.path = splittedRequest.path; + obj.query = splittedRequest.query; + obj.fragment = splittedRequest.fragment; + obj.options = undefined; + obj.ident = undefined; + } else { + if(!value.loader) + throw new Error("request should be a string or object with loader and options (" + JSON.stringify(value) + ")"); + obj.path = value.loader; + obj.fragment = value.fragment || ""; + obj.type = value.type; + obj.options = value.options; + obj.ident = value.ident; + if(obj.options === null) + obj.query = ""; + else if(obj.options === undefined) + obj.query = ""; + else if(typeof obj.options === "string") + obj.query = "?" + obj.options; + else if(obj.ident) + obj.query = "??" + obj.ident; + else if(typeof obj.options === "object" && obj.options.ident) + obj.query = "??" + obj.options.ident; + else + obj.query = "?" + JSON.stringify(obj.options); + } + } + }); + obj.request = loader; + if(Object.preventExtensions) { + Object.preventExtensions(obj); + } + return obj; +} + +function runSyncOrAsync(fn, context, args, callback) { + var isSync = true; + var isDone = false; + var isError = false; // internal error + var reportedError = false; + context.async = function async() { + if(isDone) { + if(reportedError) return; // ignore + throw new Error("async(): The callback was already called."); + } + isSync = false; + return innerCallback; + }; + var innerCallback = context.callback = function() { + if(isDone) { + if(reportedError) return; // ignore + throw new Error("callback(): The callback was already called."); + } + isDone = true; + isSync = false; + try { + callback.apply(null, arguments); + } catch(e) { + isError = true; + throw e; + } + }; + try { + var result = (function LOADER_EXECUTION() { + return fn.apply(context, args); + }()); + if(isSync) { + isDone = true; + if(result === undefined) + return callback(); + if(result && typeof result === "object" && typeof result.then === "function") { + return result.then(function(r) { + callback(null, r); + }, callback); + } + return callback(null, result); + } + } catch(e) { + if(isError) throw e; + if(isDone) { + // loader is already "done", so we cannot use the callback function + // for better debugging we print the error on the console + if(typeof e === "object" && e.stack) console.error(e.stack); + else console.error(e); + return; + } + isDone = true; + reportedError = true; + callback(e); + } + +} + +function convertArgs(args, raw) { + if(!raw && Buffer.isBuffer(args[0])) + args[0] = utf8BufferToString(args[0]); + else if(raw && typeof args[0] === "string") + args[0] = Buffer.from(args[0], "utf-8"); +} + +function iteratePitchingLoaders(options, loaderContext, callback) { + // abort after last loader + if(loaderContext.loaderIndex >= loaderContext.loaders.length) + return processResource(options, loaderContext, callback); + + var currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex]; + + // iterate + if(currentLoaderObject.pitchExecuted) { + loaderContext.loaderIndex++; + return iteratePitchingLoaders(options, loaderContext, callback); + } + + // load loader module + loadLoader(currentLoaderObject, function(err) { + if(err) { + loaderContext.cacheable(false); + return callback(err); + } + var fn = currentLoaderObject.pitch; + currentLoaderObject.pitchExecuted = true; + if(!fn) return iteratePitchingLoaders(options, loaderContext, callback); + + runSyncOrAsync( + fn, + loaderContext, [loaderContext.remainingRequest, loaderContext.previousRequest, currentLoaderObject.data = {}], + function(err) { + if(err) return callback(err); + var args = Array.prototype.slice.call(arguments, 1); + // Determine whether to continue the pitching process based on + // argument values (as opposed to argument presence) in order + // to support synchronous and asynchronous usages. + var hasArg = args.some(function(value) { + return value !== undefined; + }); + if(hasArg) { + loaderContext.loaderIndex--; + iterateNormalLoaders(options, loaderContext, args, callback); + } else { + iteratePitchingLoaders(options, loaderContext, callback); + } + } + ); + }); +} + +function processResource(options, loaderContext, callback) { + // set loader index to last loader + loaderContext.loaderIndex = loaderContext.loaders.length - 1; + + var resourcePath = loaderContext.resourcePath; + if(resourcePath) { + options.processResource(loaderContext, resourcePath, function(err) { + if(err) return callback(err); + var args = Array.prototype.slice.call(arguments, 1); + options.resourceBuffer = args[0]; + iterateNormalLoaders(options, loaderContext, args, callback); + }); + } else { + iterateNormalLoaders(options, loaderContext, [null], callback); + } +} + +function iterateNormalLoaders(options, loaderContext, args, callback) { + if(loaderContext.loaderIndex < 0) + return callback(null, args); + + var currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex]; + + // iterate + if(currentLoaderObject.normalExecuted) { + loaderContext.loaderIndex--; + return iterateNormalLoaders(options, loaderContext, args, callback); + } + + var fn = currentLoaderObject.normal; + currentLoaderObject.normalExecuted = true; + if(!fn) { + return iterateNormalLoaders(options, loaderContext, args, callback); + } + + convertArgs(args, currentLoaderObject.raw); + + runSyncOrAsync(fn, loaderContext, args, function(err) { + if(err) return callback(err); + + var args = Array.prototype.slice.call(arguments, 1); + iterateNormalLoaders(options, loaderContext, args, callback); + }); +} + +exports.getContext = function getContext(resource) { + var path = parsePathQueryFragment(resource).path; + return dirname(path); +}; + +exports.runLoaders = function runLoaders(options, callback) { + // read options + var resource = options.resource || ""; + var loaders = options.loaders || []; + var loaderContext = options.context || {}; + var processResource = options.processResource || ((readResource, context, resource, callback) => { + context.addDependency(resource); + readResource(resource, callback); + }).bind(null, options.readResource || readFile); + + // + var splittedResource = resource && parsePathQueryFragment(resource); + var resourcePath = splittedResource ? splittedResource.path : undefined; + var resourceQuery = splittedResource ? splittedResource.query : undefined; + var resourceFragment = splittedResource ? splittedResource.fragment : undefined; + var contextDirectory = resourcePath ? dirname(resourcePath) : null; + + // execution state + var requestCacheable = true; + var fileDependencies = []; + var contextDependencies = []; + var missingDependencies = []; + + // prepare loader objects + loaders = loaders.map(createLoaderObject); + + loaderContext.context = contextDirectory; + loaderContext.loaderIndex = 0; + loaderContext.loaders = loaders; + loaderContext.resourcePath = resourcePath; + loaderContext.resourceQuery = resourceQuery; + loaderContext.resourceFragment = resourceFragment; + loaderContext.async = null; + loaderContext.callback = null; + loaderContext.cacheable = function cacheable(flag) { + if(flag === false) { + requestCacheable = false; + } + }; + loaderContext.dependency = loaderContext.addDependency = function addDependency(file) { + fileDependencies.push(file); + }; + loaderContext.addContextDependency = function addContextDependency(context) { + contextDependencies.push(context); + }; + loaderContext.addMissingDependency = function addMissingDependency(context) { + missingDependencies.push(context); + }; + loaderContext.getDependencies = function getDependencies() { + return fileDependencies.slice(); + }; + loaderContext.getContextDependencies = function getContextDependencies() { + return contextDependencies.slice(); + }; + loaderContext.getMissingDependencies = function getMissingDependencies() { + return missingDependencies.slice(); + }; + loaderContext.clearDependencies = function clearDependencies() { + fileDependencies.length = 0; + contextDependencies.length = 0; + missingDependencies.length = 0; + requestCacheable = true; + }; + Object.defineProperty(loaderContext, "resource", { + enumerable: true, + get: function() { + if(loaderContext.resourcePath === undefined) + return undefined; + return loaderContext.resourcePath.replace(/#/g, "\0#") + loaderContext.resourceQuery.replace(/#/g, "\0#") + loaderContext.resourceFragment; + }, + set: function(value) { + var splittedResource = value && parsePathQueryFragment(value); + loaderContext.resourcePath = splittedResource ? splittedResource.path : undefined; + loaderContext.resourceQuery = splittedResource ? splittedResource.query : undefined; + loaderContext.resourceFragment = splittedResource ? splittedResource.fragment : undefined; + } + }); + Object.defineProperty(loaderContext, "request", { + enumerable: true, + get: function() { + return loaderContext.loaders.map(function(o) { + return o.request; + }).concat(loaderContext.resource || "").join("!"); + } + }); + Object.defineProperty(loaderContext, "remainingRequest", { + enumerable: true, + get: function() { + if(loaderContext.loaderIndex >= loaderContext.loaders.length - 1 && !loaderContext.resource) + return ""; + return loaderContext.loaders.slice(loaderContext.loaderIndex + 1).map(function(o) { + return o.request; + }).concat(loaderContext.resource || "").join("!"); + } + }); + Object.defineProperty(loaderContext, "currentRequest", { + enumerable: true, + get: function() { + return loaderContext.loaders.slice(loaderContext.loaderIndex).map(function(o) { + return o.request; + }).concat(loaderContext.resource || "").join("!"); + } + }); + Object.defineProperty(loaderContext, "previousRequest", { + enumerable: true, + get: function() { + return loaderContext.loaders.slice(0, loaderContext.loaderIndex).map(function(o) { + return o.request; + }).join("!"); + } + }); + Object.defineProperty(loaderContext, "query", { + enumerable: true, + get: function() { + var entry = loaderContext.loaders[loaderContext.loaderIndex]; + return entry.options && typeof entry.options === "object" ? entry.options : entry.query; + } + }); + Object.defineProperty(loaderContext, "data", { + enumerable: true, + get: function() { + return loaderContext.loaders[loaderContext.loaderIndex].data; + } + }); + + // finish loader context + if(Object.preventExtensions) { + Object.preventExtensions(loaderContext); + } + + var processOptions = { + resourceBuffer: null, + processResource: processResource + }; + iteratePitchingLoaders(processOptions, loaderContext, function(err, result) { + if(err) { + return callback(err, { + cacheable: requestCacheable, + fileDependencies: fileDependencies, + contextDependencies: contextDependencies, + missingDependencies: missingDependencies + }); + } + callback(null, { + result: result, + resourceBuffer: processOptions.resourceBuffer, + cacheable: requestCacheable, + fileDependencies: fileDependencies, + contextDependencies: contextDependencies, + missingDependencies: missingDependencies + }); + }); +}; diff --git a/node_modules/loader-runner/lib/loadLoader.js b/node_modules/loader-runner/lib/loadLoader.js new file mode 100644 index 0000000..1210353 --- /dev/null +++ b/node_modules/loader-runner/lib/loadLoader.js @@ -0,0 +1,54 @@ +var LoaderLoadingError = require("./LoaderLoadingError"); +var url; + +module.exports = function loadLoader(loader, callback) { + if(loader.type === "module") { + try { + if(url === undefined) url = require("url"); + var loaderUrl = url.pathToFileURL(loader.path); + var modulePromise = eval("import(" + JSON.stringify(loaderUrl.toString()) + ")"); + modulePromise.then(function(module) { + handleResult(loader, module, callback); + }, callback); + return; + } catch(e) { + callback(e); + } + } else { + try { + var module = require(loader.path); + } catch(e) { + // it is possible for node to choke on a require if the FD descriptor + // limit has been reached. give it a chance to recover. + if(e instanceof Error && e.code === "EMFILE") { + var retry = loadLoader.bind(null, loader, callback); + if(typeof setImmediate === "function") { + // node >= 0.9.0 + return setImmediate(retry); + } else { + // node < 0.9.0 + return process.nextTick(retry); + } + } + return callback(e); + } + return handleResult(loader, module, callback); + } +}; + +function handleResult(loader, module, callback) { + if(typeof module !== "function" && typeof module !== "object") { + return callback(new LoaderLoadingError( + "Module '" + loader.path + "' is not a loader (export function or es6 module)" + )); + } + loader.normal = typeof module === "function" ? module : module.default; + loader.pitch = module.pitch; + loader.raw = module.raw; + if(typeof loader.normal !== "function" && typeof loader.pitch !== "function") { + return callback(new LoaderLoadingError( + "Module '" + loader.path + "' is not a loader (must have normal or pitch function)" + )); + } + callback(); +} diff --git a/node_modules/loader-runner/package.json b/node_modules/loader-runner/package.json new file mode 100644 index 0000000..f8db868 --- /dev/null +++ b/node_modules/loader-runner/package.json @@ -0,0 +1,45 @@ +{ + "name": "loader-runner", + "version": "4.3.0", + "description": "Runs (webpack) loaders", + "main": "lib/LoaderRunner.js", + "scripts": { + "lint": "eslint lib test", + "pretest": "npm run lint", + "test": "mocha --reporter spec", + "precover": "npm run lint", + "cover": "istanbul cover node_modules/mocha/bin/_mocha" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/webpack/loader-runner.git" + }, + "keywords": [ + "webpack", + "loader" + ], + "author": "Tobias Koppers @sokra", + "license": "MIT", + "bugs": { + "url": "https://github.com/webpack/loader-runner/issues" + }, + "homepage": "https://github.com/webpack/loader-runner#readme", + "engines": { + "node": ">=6.11.5" + }, + "files": [ + "lib/", + "bin/", + "hot/", + "web_modules/", + "schemas/" + ], + "devDependencies": { + "eslint": "^3.12.2", + "eslint-plugin-node": "^3.0.5", + "eslint-plugin-nodeca": "^1.0.3", + "istanbul": "^0.4.1", + "mocha": "^3.2.0", + "should": "^8.0.2" + } +} diff --git a/node_modules/locate-path/index.d.ts b/node_modules/locate-path/index.d.ts new file mode 100644 index 0000000..4ecf24a --- /dev/null +++ b/node_modules/locate-path/index.d.ts @@ -0,0 +1,92 @@ +export interface Options { + /** + The current working directory. + + @default process.cwd() + */ + readonly cwd?: URL | string; + + /** + The type of path to match. + + @default 'file' + */ + readonly type?: 'file' | 'directory'; + + /** + Allow symbolic links to match if they point to the requested path type. + + @default true + */ + readonly allowSymlinks?: boolean; +} + +export interface AsyncOptions extends Options { + /** + The number of concurrently pending promises. + + Minimum: `1` + + @default Infinity + */ + readonly concurrency?: number; + + /** + Preserve `paths` order when searching. + + Disable this to improve performance if you don't care about the order. + + @default true + */ + readonly preserveOrder?: boolean; +} + +/** +Get the first path that exists on disk of multiple paths. + +@param paths - The paths to check. +@returns The first path that exists or `undefined` if none exists. + +@example +``` +import {locatePath} from 'locate-path'; + +const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' +]; + +console(await locatePath(files)); +//=> 'rainbow' +``` +*/ +export function locatePath( + paths: Iterable, + options?: AsyncOptions +): Promise; + +/** +Synchronously get the first path that exists on disk of multiple paths. + +@param paths - The paths to check. +@returns The first path that exists or `undefined` if none exists. + +@example +``` +import {locatePathSync} from 'locate-path'; + +const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' +]; + +console(locatePathSync(files)); +//=> 'rainbow' +``` +*/ +export function locatePathSync( + paths: Iterable, + options?: Options +): string | undefined; diff --git a/node_modules/locate-path/index.js b/node_modules/locate-path/index.js new file mode 100644 index 0000000..a5fed89 --- /dev/null +++ b/node_modules/locate-path/index.js @@ -0,0 +1,77 @@ +import process from 'node:process'; +import path from 'node:path'; +import fs, {promises as fsPromises} from 'node:fs'; +import {fileURLToPath} from 'node:url'; +import pLocate from 'p-locate'; + +const typeMappings = { + directory: 'isDirectory', + file: 'isFile', +}; + +function checkType(type) { + if (Object.hasOwnProperty.call(typeMappings, type)) { + return; + } + + throw new Error(`Invalid type specified: ${type}`); +} + +const matchType = (type, stat) => stat[typeMappings[type]](); + +const toPath = urlOrPath => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath; + +export async function locatePath( + paths, + { + cwd = process.cwd(), + type = 'file', + allowSymlinks = true, + concurrency, + preserveOrder, + } = {}, +) { + checkType(type); + cwd = toPath(cwd); + + const statFunction = allowSymlinks ? fsPromises.stat : fsPromises.lstat; + + return pLocate(paths, async path_ => { + try { + const stat = await statFunction(path.resolve(cwd, path_)); + return matchType(type, stat); + } catch { + return false; + } + }, {concurrency, preserveOrder}); +} + +export function locatePathSync( + paths, + { + cwd = process.cwd(), + type = 'file', + allowSymlinks = true, + } = {}, +) { + checkType(type); + cwd = toPath(cwd); + + const statFunction = allowSymlinks ? fs.statSync : fs.lstatSync; + + for (const path_ of paths) { + try { + const stat = statFunction(path.resolve(cwd, path_), { + throwIfNoEntry: false, + }); + + if (!stat) { + continue; + } + + if (matchType(type, stat)) { + return path_; + } + } catch {} + } +} diff --git a/node_modules/locate-path/license b/node_modules/locate-path/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/locate-path/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/locate-path/package.json b/node_modules/locate-path/package.json new file mode 100644 index 0000000..28a2bda --- /dev/null +++ b/node_modules/locate-path/package.json @@ -0,0 +1,48 @@ +{ + "name": "locate-path", + "version": "7.2.0", + "description": "Get the first path that exists on disk of multiple paths", + "license": "MIT", + "repository": "sindresorhus/locate-path", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": "./index.js", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "locate", + "path", + "paths", + "file", + "files", + "exists", + "find", + "finder", + "search", + "searcher", + "array", + "iterable", + "iterator" + ], + "dependencies": { + "p-locate": "^6.0.0" + }, + "devDependencies": { + "ava": "^3.15.0", + "tsd": "^0.17.0", + "xo": "^0.44.0" + } +} diff --git a/node_modules/locate-path/readme.md b/node_modules/locate-path/readme.md new file mode 100644 index 0000000..ea871fd --- /dev/null +++ b/node_modules/locate-path/readme.md @@ -0,0 +1,123 @@ +# locate-path + +> Get the first path that exists on disk of multiple paths + +## Install + +``` +$ npm install locate-path +``` + +## Usage + +Here we find the first file that exists on disk, in array order. + +```js +import {locatePath} from 'locate-path'; + +const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' +]; + +console(await locatePath(files)); +//=> 'rainbow' +``` + +## API + +### locatePath(paths, options?) + +Returns a `Promise` for the first path that exists or `undefined` if none exists. + +#### paths + +Type: `Iterable` + +The paths to check. + +#### options + +Type: `object` + +##### concurrency + +Type: `number`\ +Default: `Infinity`\ +Minimum: `1` + +The number of concurrently pending promises. + +##### preserveOrder + +Type: `boolean`\ +Default: `true` + +Preserve `paths` order when searching. + +Disable this to improve performance if you don't care about the order. + +##### cwd + +Type: `URL | string`\ +Default: `process.cwd()` + +The current working directory. + +##### type + +Type: `string`\ +Default: `'file'`\ +Values: `'file' | 'directory'` + +The type of paths that can match. + +##### allowSymlinks + +Type: `boolean`\ +Default: `true` + +Allow symbolic links to match if they point to the chosen path type. + +### locatePathSync(paths, options?) + +Returns the first path that exists or `undefined` if none exists. + +#### paths + +Type: `Iterable` + +The paths to check. + +#### options + +Type: `object` + +##### cwd + +Same as above. + +##### type + +Same as above. + +##### allowSymlinks + +Same as above. + +## Related + +- [path-exists](https://github.com/sindresorhus/path-exists) - Check if a path exists + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/lru-cache/LICENSE b/node_modules/lru-cache/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/lru-cache/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/lru-cache/README.md b/node_modules/lru-cache/README.md new file mode 100644 index 0000000..435dfeb --- /dev/null +++ b/node_modules/lru-cache/README.md @@ -0,0 +1,166 @@ +# lru cache + +A cache object that deletes the least-recently-used items. + +[![Build Status](https://travis-ci.org/isaacs/node-lru-cache.svg?branch=master)](https://travis-ci.org/isaacs/node-lru-cache) [![Coverage Status](https://coveralls.io/repos/isaacs/node-lru-cache/badge.svg?service=github)](https://coveralls.io/github/isaacs/node-lru-cache) + +## Installation: + +```javascript +npm install lru-cache --save +``` + +## Usage: + +```javascript +var LRU = require("lru-cache") + , options = { max: 500 + , length: function (n, key) { return n * 2 + key.length } + , dispose: function (key, n) { n.close() } + , maxAge: 1000 * 60 * 60 } + , cache = new LRU(options) + , otherCache = new LRU(50) // sets just the max size + +cache.set("key", "value") +cache.get("key") // "value" + +// non-string keys ARE fully supported +// but note that it must be THE SAME object, not +// just a JSON-equivalent object. +var someObject = { a: 1 } +cache.set(someObject, 'a value') +// Object keys are not toString()-ed +cache.set('[object Object]', 'a different value') +assert.equal(cache.get(someObject), 'a value') +// A similar object with same keys/values won't work, +// because it's a different object identity +assert.equal(cache.get({ a: 1 }), undefined) + +cache.reset() // empty the cache +``` + +If you put more stuff in it, then items will fall out. + +If you try to put an oversized thing in it, then it'll fall out right +away. + +## Options + +* `max` The maximum size of the cache, checked by applying the length + function to all values in the cache. Not setting this is kind of + silly, since that's the whole purpose of this lib, but it defaults + to `Infinity`. Setting it to a non-number or negative number will + throw a `TypeError`. Setting it to 0 makes it be `Infinity`. +* `maxAge` Maximum age in ms. Items are not pro-actively pruned out + as they age, but if you try to get an item that is too old, it'll + drop it and return undefined instead of giving it to you. + Setting this to a negative value will make everything seem old! + Setting it to a non-number will throw a `TypeError`. +* `length` Function that is used to calculate the length of stored + items. If you're storing strings or buffers, then you probably want + to do something like `function(n, key){return n.length}`. The default is + `function(){return 1}`, which is fine if you want to store `max` + like-sized things. The item is passed as the first argument, and + the key is passed as the second argumnet. +* `dispose` Function that is called on items when they are dropped + from the cache. This can be handy if you want to close file + descriptors or do other cleanup tasks when items are no longer + accessible. Called with `key, value`. It's called *before* + actually removing the item from the internal cache, so if you want + to immediately put it back in, you'll have to do that in a + `nextTick` or `setTimeout` callback or it won't do anything. +* `stale` By default, if you set a `maxAge`, it'll only actually pull + stale items out of the cache when you `get(key)`. (That is, it's + not pre-emptively doing a `setTimeout` or anything.) If you set + `stale:true`, it'll return the stale value before deleting it. If + you don't set this, then it'll return `undefined` when you try to + get a stale entry, as if it had already been deleted. +* `noDisposeOnSet` By default, if you set a `dispose()` method, then + it'll be called whenever a `set()` operation overwrites an existing + key. If you set this option, `dispose()` will only be called when a + key falls out of the cache, not when it is overwritten. +* `updateAgeOnGet` When using time-expiring entries with `maxAge`, + setting this to `true` will make each item's effective time update + to the current time whenever it is retrieved from cache, causing it + to not expire. (It can still fall out of cache based on recency of + use, of course.) + +## API + +* `set(key, value, maxAge)` +* `get(key) => value` + + Both of these will update the "recently used"-ness of the key. + They do what you think. `maxAge` is optional and overrides the + cache `maxAge` option if provided. + + If the key is not found, `get()` will return `undefined`. + + The key and val can be any value. + +* `peek(key)` + + Returns the key value (or `undefined` if not found) without + updating the "recently used"-ness of the key. + + (If you find yourself using this a lot, you *might* be using the + wrong sort of data structure, but there are some use cases where + it's handy.) + +* `del(key)` + + Deletes a key out of the cache. + +* `reset()` + + Clear the cache entirely, throwing away all values. + +* `has(key)` + + Check if a key is in the cache, without updating the recent-ness + or deleting it for being stale. + +* `forEach(function(value,key,cache), [thisp])` + + Just like `Array.prototype.forEach`. Iterates over all the keys + in the cache, in order of recent-ness. (Ie, more recently used + items are iterated over first.) + +* `rforEach(function(value,key,cache), [thisp])` + + The same as `cache.forEach(...)` but items are iterated over in + reverse order. (ie, less recently used items are iterated over + first.) + +* `keys()` + + Return an array of the keys in the cache. + +* `values()` + + Return an array of the values in the cache. + +* `length` + + Return total length of objects in cache taking into account + `length` options function. + +* `itemCount` + + Return total quantity of objects currently in cache. Note, that + `stale` (see options) items are returned as part of this item + count. + +* `dump()` + + Return an array of the cache entries ready for serialization and usage + with 'destinationCache.load(arr)`. + +* `load(cacheEntriesArray)` + + Loads another cache entries array, obtained with `sourceCache.dump()`, + into the cache. The destination cache is reset before loading new entries + +* `prune()` + + Manually iterates over the entire cache proactively pruning old entries diff --git a/node_modules/lru-cache/index.js b/node_modules/lru-cache/index.js new file mode 100644 index 0000000..573b6b8 --- /dev/null +++ b/node_modules/lru-cache/index.js @@ -0,0 +1,334 @@ +'use strict' + +// A linked list to keep track of recently-used-ness +const Yallist = require('yallist') + +const MAX = Symbol('max') +const LENGTH = Symbol('length') +const LENGTH_CALCULATOR = Symbol('lengthCalculator') +const ALLOW_STALE = Symbol('allowStale') +const MAX_AGE = Symbol('maxAge') +const DISPOSE = Symbol('dispose') +const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') +const LRU_LIST = Symbol('lruList') +const CACHE = Symbol('cache') +const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') + +const naiveLength = () => 1 + +// lruList is a yallist where the head is the youngest +// item, and the tail is the oldest. the list contains the Hit +// objects as the entries. +// Each Hit object has a reference to its Yallist.Node. This +// never changes. +// +// cache is a Map (or PseudoMap) that matches the keys to +// the Yallist.Node object. +class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options } + + if (!options) + options = {} + + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + const max = this[MAX] = options.max || Infinity + + const lc = options.length || naiveLength + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc + this[ALLOW_STALE] = options.stale || false + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0 + this[DISPOSE] = options.dispose + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false + this.reset() + } + + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') + + this[MAX] = mL || Infinity + trim(this) + } + get max () { + return this[MAX] + } + + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale + } + get allowStale () { + return this[ALLOW_STALE] + } + + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') + + this[MAX_AGE] = mA + trim(this) + } + get maxAge () { + return this[MAX_AGE] + } + + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC + this[LENGTH] = 0 + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) + this[LENGTH] += hit.length + }) + } + trim(this) + } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } + + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } + + rforEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev + forEachStep(this, fn, walker, thisp) + walker = prev + } + } + + forEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next + forEachStep(this, fn, walker, thisp) + walker = next + } + } + + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } + + values () { + return this[LRU_LIST].toArray().map(k => k.value) + } + + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) + } + + this[CACHE] = new Map() // hash of items by key + this[LRU_LIST] = new Yallist() // list of items in order of use recency + this[LENGTH] = 0 // length of items in the list + } + + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } + + dumpLru () { + return this[LRU_LIST] + } + + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE] + + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') + + const now = maxAge ? Date.now() : 0 + const len = this[LENGTH_CALCULATOR](value, key) + + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)) + return false + } + + const node = this[CACHE].get(key) + const item = node.value + + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value) + } + + item.now = now + item.maxAge = maxAge + item.value = value + this[LENGTH] += len - item.length + item.length = len + this.get(key) + trim(this) + return true + } + + const hit = new Entry(key, value, len, now, maxAge) + + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value) + + return false + } + + this[LENGTH] += hit.length + this[LRU_LIST].unshift(hit) + this[CACHE].set(key, this[LRU_LIST].head) + trim(this) + return true + } + + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value + return !isStale(this, hit) + } + + get (key) { + return get(this, key, true) + } + + peek (key) { + return get(this, key, false) + } + + pop () { + const node = this[LRU_LIST].tail + if (!node) + return null + + del(this, node) + return node.value + } + + del (key) { + del(this, this[CACHE].get(key)) + } + + load (arr) { + // reset the cache + this.reset() + + const now = Date.now() + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l] + const expiresAt = hit.e || 0 + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v) + else { + const maxAge = expiresAt - now + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge) + } + } + } + } + + prune () { + this[CACHE].forEach((value, key) => get(this, key, false)) + } +} + +const get = (self, key, doUse) => { + const node = self[CACHE].get(key) + if (node) { + const hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now() + self[LRU_LIST].unshiftNode(node) + } + } + return hit.value + } +} + +const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false + + const diff = Date.now() - hit.now + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) +} + +const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev + del(self, walker) + walker = prev + } + } +} + +const del = (self, node) => { + if (node) { + const hit = node.value + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value) + + self[LENGTH] -= hit.length + self[CACHE].delete(hit.key) + self[LRU_LIST].removeNode(node) + } +} + +class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key + this.value = value + this.length = length + this.now = now + this.maxAge = maxAge || 0 + } +} + +const forEachStep = (self, fn, node, thisp) => { + let hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + hit = undefined + } + if (hit) + fn.call(thisp, hit.value, hit.key, self) +} + +module.exports = LRUCache diff --git a/node_modules/lru-cache/package.json b/node_modules/lru-cache/package.json new file mode 100644 index 0000000..d4611f8 --- /dev/null +++ b/node_modules/lru-cache/package.json @@ -0,0 +1,32 @@ +{ + "name": "lru-cache", + "description": "A cache object that deletes the least-recently-used items.", + "version": "5.1.1", + "author": "Isaac Z. Schlueter ", + "keywords": [ + "mru", + "lru", + "cache" + ], + "scripts": { + "test": "tap test/*.js --100 -J", + "snap": "TAP_SNAPSHOT=1 tap test/*.js -J", + "coveragerport": "tap --coverage-report=html", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --all; git push origin --tags" + }, + "main": "index.js", + "repository": "git://github.com/isaacs/node-lru-cache.git", + "devDependencies": { + "benchmark": "^2.1.4", + "tap": "^12.1.0" + }, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + }, + "files": [ + "index.js" + ] +} diff --git a/node_modules/merge-stream/LICENSE b/node_modules/merge-stream/LICENSE new file mode 100644 index 0000000..94a4c0a --- /dev/null +++ b/node_modules/merge-stream/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Stephen Sugden (stephensugden.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/merge-stream/README.md b/node_modules/merge-stream/README.md new file mode 100644 index 0000000..0d54841 --- /dev/null +++ b/node_modules/merge-stream/README.md @@ -0,0 +1,78 @@ +# merge-stream + +Merge (interleave) a bunch of streams. + +[![build status](https://secure.travis-ci.org/grncdr/merge-stream.svg?branch=master)](http://travis-ci.org/grncdr/merge-stream) + +## Synopsis + +```javascript +var stream1 = new Stream(); +var stream2 = new Stream(); + +var merged = mergeStream(stream1, stream2); + +var stream3 = new Stream(); +merged.add(stream3); +merged.isEmpty(); +//=> false +``` + +## Description + +This is adapted from [event-stream](https://github.com/dominictarr/event-stream) separated into a new module, using Streams3. + +## API + +### `mergeStream` + +Type: `function` + +Merges an arbitrary number of streams. Returns a merged stream. + +#### `merged.add` + +A method to dynamically add more sources to the stream. The argument supplied to `add` can be either a source or an array of sources. + +#### `merged.isEmpty` + +A method that tells you if the merged stream is empty. + +When a stream is "empty" (aka. no sources were added), it could not be returned to a gulp task. + +So, we could do something like this: + +```js +stream = require('merge-stream')(); +// Something like a loop to add some streams to the merge stream +// stream.add(streamA); +// stream.add(streamB); +return stream.isEmpty() ? null : stream; +``` + +## Gulp example + +An example use case for **merge-stream** is to combine parts of a task in a project's **gulpfile.js** like this: + +```js +const gulp = require('gulp'); +const htmlValidator = require('gulp-w3c-html-validator'); +const jsHint = require('gulp-jshint'); +const mergeStream = require('merge-stream'); + +function lint() { + return mergeStream( + gulp.src('src/*.html') + .pipe(htmlValidator()) + .pipe(htmlValidator.reporter()), + gulp.src('src/*.js') + .pipe(jsHint()) + .pipe(jsHint.reporter()) + ); +} +gulp.task('lint', lint); +``` + +## License + +MIT diff --git a/node_modules/merge-stream/index.js b/node_modules/merge-stream/index.js new file mode 100644 index 0000000..b1a9e1a --- /dev/null +++ b/node_modules/merge-stream/index.js @@ -0,0 +1,41 @@ +'use strict'; + +const { PassThrough } = require('stream'); + +module.exports = function (/*streams...*/) { + var sources = [] + var output = new PassThrough({objectMode: true}) + + output.setMaxListeners(0) + + output.add = add + output.isEmpty = isEmpty + + output.on('unpipe', remove) + + Array.prototype.slice.call(arguments).forEach(add) + + return output + + function add (source) { + if (Array.isArray(source)) { + source.forEach(add) + return this + } + + sources.push(source); + source.once('end', remove.bind(null, source)) + source.once('error', output.emit.bind(output, 'error')) + source.pipe(output, {end: false}) + return this + } + + function isEmpty () { + return sources.length == 0; + } + + function remove (source) { + sources = sources.filter(function (it) { return it !== source }) + if (!sources.length && output.readable) { output.end() } + } +} diff --git a/node_modules/merge-stream/package.json b/node_modules/merge-stream/package.json new file mode 100644 index 0000000..1a4c54c --- /dev/null +++ b/node_modules/merge-stream/package.json @@ -0,0 +1,19 @@ +{ + "name": "merge-stream", + "version": "2.0.0", + "description": "Create a stream that emits events from multiple other streams", + "files": [ + "index.js" + ], + "scripts": { + "test": "istanbul cover test.js && istanbul check-cover --statements 100 --branches 100" + }, + "repository": "grncdr/merge-stream", + "author": "Stephen Sugden ", + "license": "MIT", + "dependencies": {}, + "devDependencies": { + "from2": "^2.0.3", + "istanbul": "^0.4.5" + } +} diff --git a/node_modules/mime-db/HISTORY.md b/node_modules/mime-db/HISTORY.md new file mode 100644 index 0000000..7436f64 --- /dev/null +++ b/node_modules/mime-db/HISTORY.md @@ -0,0 +1,507 @@ +1.52.0 / 2022-02-21 +=================== + + * Add extensions from IANA for more `image/*` types + * Add extension `.asc` to `application/pgp-keys` + * Add extensions to various XML types + * Add new upstream MIME types + +1.51.0 / 2021-11-08 +=================== + + * Add new upstream MIME types + * Mark `image/vnd.microsoft.icon` as compressible + * Mark `image/vnd.ms-dds` as compressible + +1.50.0 / 2021-09-15 +=================== + + * Add deprecated iWorks mime types and extensions + * Add new upstream MIME types + +1.49.0 / 2021-07-26 +=================== + + * Add extension `.trig` to `application/trig` + * Add new upstream MIME types + +1.48.0 / 2021-05-30 +=================== + + * Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + * Add new upstream MIME types + * Mark `text/yaml` as compressible + +1.47.0 / 2021-04-01 +=================== + + * Add new upstream MIME types + * Remove ambigious extensions from IANA for `application/*+xml` types + * Update primary extension to `.es` for `application/ecmascript` + +1.46.0 / 2021-02-13 +=================== + + * Add extension `.amr` to `audio/amr` + * Add extension `.m4s` to `video/iso.segment` + * Add extension `.opus` to `audio/ogg` + * Add new upstream MIME types + +1.45.0 / 2020-09-22 +=================== + + * Add `application/ubjson` with extension `.ubj` + * Add `image/avif` with extension `.avif` + * Add `image/ktx2` with extension `.ktx2` + * Add extension `.dbf` to `application/vnd.dbf` + * Add extension `.rar` to `application/vnd.rar` + * Add extension `.td` to `application/urc-targetdesc+xml` + * Add new upstream MIME types + * Fix extension of `application/vnd.apple.keynote` to be `.key` + +1.44.0 / 2020-04-22 +=================== + + * Add charsets from IANA + * Add extension `.cjs` to `application/node` + * Add new upstream MIME types + +1.43.0 / 2020-01-05 +=================== + + * Add `application/x-keepass2` with extension `.kdbx` + * Add extension `.mxmf` to `audio/mobile-xmf` + * Add extensions from IANA for `application/*+xml` types + * Add new upstream MIME types + +1.42.0 / 2019-09-25 +=================== + + * Add `image/vnd.ms-dds` with extension `.dds` + * Add new upstream MIME types + * Remove compressible from `multipart/mixed` + +1.41.0 / 2019-08-30 +=================== + + * Add new upstream MIME types + * Add `application/toml` with extension `.toml` + * Mark `font/ttf` as compressible + +1.40.0 / 2019-04-20 +=================== + + * Add extensions from IANA for `model/*` types + * Add `text/mdx` with extension `.mdx` + +1.39.0 / 2019-04-04 +=================== + + * Add extensions `.siv` and `.sieve` to `application/sieve` + * Add new upstream MIME types + +1.38.0 / 2019-02-04 +=================== + + * Add extension `.nq` to `application/n-quads` + * Add extension `.nt` to `application/n-triples` + * Add new upstream MIME types + * Mark `text/less` as compressible + +1.37.0 / 2018-10-19 +=================== + + * Add extensions to HEIC image types + * Add new upstream MIME types + +1.36.0 / 2018-08-20 +=================== + + * Add Apple file extensions from IANA + * Add extensions from IANA for `image/*` types + * Add new upstream MIME types + +1.35.0 / 2018-07-15 +=================== + + * Add extension `.owl` to `application/rdf+xml` + * Add new upstream MIME types + - Removes extension `.woff` from `application/font-woff` + +1.34.0 / 2018-06-03 +=================== + + * Add extension `.csl` to `application/vnd.citationstyles.style+xml` + * Add extension `.es` to `application/ecmascript` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/turtle` + * Mark all XML-derived types as compressible + +1.33.0 / 2018-02-15 +=================== + + * Add extensions from IANA for `message/*` types + * Add new upstream MIME types + * Fix some incorrect OOXML types + * Remove `application/font-woff2` + +1.32.0 / 2017-11-29 +=================== + + * Add new upstream MIME types + * Update `text/hjson` to registered `application/hjson` + * Add `text/shex` with extension `.shex` + +1.31.0 / 2017-10-25 +=================== + + * Add `application/raml+yaml` with extension `.raml` + * Add `application/wasm` with extension `.wasm` + * Add new `font` type from IANA + * Add new upstream font extensions + * Add new upstream MIME types + * Add extensions for JPEG-2000 images + +1.30.0 / 2017-08-27 +=================== + + * Add `application/vnd.ms-outlook` + * Add `application/x-arj` + * Add extension `.mjs` to `application/javascript` + * Add glTF types and extensions + * Add new upstream MIME types + * Add `text/x-org` + * Add VirtualBox MIME types + * Fix `source` records for `video/*` types that are IANA + * Update `font/opentype` to registered `font/otf` + +1.29.0 / 2017-07-10 +=================== + + * Add `application/fido.trusted-apps+json` + * Add extension `.wadl` to `application/vnd.sun.wadl+xml` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/css` + +1.28.0 / 2017-05-14 +=================== + + * Add new upstream MIME types + * Add extension `.gz` to `application/gzip` + * Update extensions `.md` and `.markdown` to be `text/markdown` + +1.27.0 / 2017-03-16 +=================== + + * Add new upstream MIME types + * Add `image/apng` with extension `.apng` + +1.26.0 / 2017-01-14 +=================== + + * Add new upstream MIME types + * Add extension `.geojson` to `application/geo+json` + +1.25.0 / 2016-11-11 +=================== + + * Add new upstream MIME types + +1.24.0 / 2016-09-18 +=================== + + * Add `audio/mp3` + * Add new upstream MIME types + +1.23.0 / 2016-05-01 +=================== + + * Add new upstream MIME types + * Add extension `.3gpp` to `audio/3gpp` + +1.22.0 / 2016-02-15 +=================== + + * Add `text/slim` + * Add extension `.rng` to `application/xml` + * Add new upstream MIME types + * Fix extension of `application/dash+xml` to be `.mpd` + * Update primary extension to `.m4a` for `audio/mp4` + +1.21.0 / 2016-01-06 +=================== + + * Add Google document types + * Add new upstream MIME types + +1.20.0 / 2015-11-10 +=================== + + * Add `text/x-suse-ymp` + * Add new upstream MIME types + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.apple.pkpass` + * Add new upstream MIME types + +1.18.0 / 2015-09-03 +=================== + + * Add new upstream MIME types + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +1.13.0 / 2015-06-07 +=================== + + * Add nginx as a source + * Add `application/x-cocoa` + * Add `application/x-java-archive-diff` + * Add `application/x-makeself` + * Add `application/x-perl` + * Add `application/x-pilot` + * Add `application/x-redhat-package-manager` + * Add `application/x-sea` + * Add `audio/x-m4a` + * Add `audio/x-realaudio` + * Add `image/x-jng` + * Add `text/mathml` + +1.12.0 / 2015-06-05 +=================== + + * Add `application/bdoc` + * Add `application/vnd.hyperdrive+json` + * Add `application/x-bdoc` + * Add extension `.rtf` to `text/rtf` + +1.11.0 / 2015-05-31 +=================== + + * Add `audio/wav` + * Add `audio/wave` + * Add extension `.litcoffee` to `text/coffeescript` + * Add extension `.sfd-hdstx` to `application/vnd.hydrostatix.sof-data` + * Add extension `.n-gage` to `application/vnd.nokia.n-gage.symbian.install` + +1.10.0 / 2015-05-19 +=================== + + * Add `application/vnd.balsamiq.bmpr` + * Add `application/vnd.microsoft.portable-executable` + * Add `application/x-ns-proxy-autoconfig` + +1.9.1 / 2015-04-19 +================== + + * Remove `.json` extension from `application/manifest+json` + - This is causing bugs downstream + +1.9.0 / 2015-04-19 +================== + + * Add `application/manifest+json` + * Add `application/vnd.micro+json` + * Add `image/vnd.zbrush.pcx` + * Add `image/x-ms-bmp` + +1.8.0 / 2015-03-13 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/node_modules/mime-db/LICENSE b/node_modules/mime-db/LICENSE new file mode 100644 index 0000000..0751cb1 --- /dev/null +++ b/node_modules/mime-db/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015-2022 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mime-db/README.md b/node_modules/mime-db/README.md new file mode 100644 index 0000000..5a8fcfe --- /dev/null +++ b/node_modules/mime-db/README.md @@ -0,0 +1,100 @@ +# mime-db + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +This is a large database of mime types and information about them. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +It aggregates data from the following sources: + +- http://www.iana.org/assignments/media-types/media-types.xhtml +- http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types +- http://hg.nginx.org/nginx/raw-file/default/conf/mime.types + +## Installation + +```bash +npm install mime-db +``` + +### Database Download + +If you're crazy enough to use this in the browser, you can just grab the +JSON file using [jsDelivr](https://www.jsdelivr.com/). It is recommended to +replace `master` with [a release tag](https://github.com/jshttp/mime-db/tags) +as the JSON format may change in the future. + +``` +https://cdn.jsdelivr.net/gh/jshttp/mime-db@master/db.json +``` + +## Usage + +```js +var db = require('mime-db') + +// grab data on .js files +var data = db['application/javascript'] +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + If not set, it's probably a custom media type. + - `apache` - [Apache common media types](http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) + - `iana` - [IANA-defined media types](http://www.iana.org/assignments/media-types/media-types.xhtml) + - `nginx` - [nginx media types](http://hg.nginx.org/nginx/raw-file/default/conf/mime.types) +- `.extensions[]` - known extensions associated with this mime type. +- `.compressible` - whether a file of this type can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Contributing + +To edit the database, only make PRs against `src/custom-types.json` or +`src/custom-suffix.json`. + +The `src/custom-types.json` file is a JSON object with the MIME type as the +keys and the values being an object with the following keys: + +- `compressible` - leave out if you don't know, otherwise `true`/`false` to + indicate whether the data represented by the type is typically compressible. +- `extensions` - include an array of file extensions that are associated with + the type. +- `notes` - human-readable notes about the type, typically what the type is. +- `sources` - include an array of URLs of where the MIME type and the associated + extensions are sourced from. This needs to be a [primary source](https://en.wikipedia.org/wiki/Primary_source); + links to type aggregating sites and Wikipedia are _not acceptable_. + +To update the build, run `npm run build`. + +### Adding Custom Media Types + +The best way to get new media types included in this library is to register +them with the IANA. The community registration procedure is outlined in +[RFC 6838 section 5](http://tools.ietf.org/html/rfc6838#section-5). Types +registered with the IANA are automatically pulled into this library. + +If that is not possible / feasible, they can be added directly here as a +"custom" type. To do this, it is required to have a primary source that +definitively lists the media type. If an extension is going to be listed as +associateed with this media type, the source must definitively link the +media type and extension as well. + +[ci-image]: https://badgen.net/github/checks/jshttp/mime-db/master?label=ci +[ci-url]: https://github.com/jshttp/mime-db/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-db/master +[coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master +[node-image]: https://badgen.net/npm/node/mime-db +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mime-db +[npm-url]: https://npmjs.org/package/mime-db +[npm-version-image]: https://badgen.net/npm/v/mime-db diff --git a/node_modules/mime-db/db.json b/node_modules/mime-db/db.json new file mode 100644 index 0000000..eb9c42c --- /dev/null +++ b/node_modules/mime-db/db.json @@ -0,0 +1,8519 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/3gpp-ims+xml": { + "source": "iana", + "compressible": true + }, + "application/3gpphal+json": { + "source": "iana", + "compressible": true + }, + "application/3gpphalforms+json": { + "source": "iana", + "compressible": true + }, + "application/a2l": { + "source": "iana" + }, + "application/ace+cbor": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/activity+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-updatestreamcontrol+json": { + "source": "iana", + "compressible": true + }, + "application/alto-updatestreamparams+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/at+jwt": { + "source": "iana" + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomdeleted"] + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomsvc"] + }, + "application/atsc-dwd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dwd"] + }, + "application/atsc-dynamic-event-message": { + "source": "iana" + }, + "application/atsc-held+xml": { + "source": "iana", + "compressible": true, + "extensions": ["held"] + }, + "application/atsc-rdt+json": { + "source": "iana", + "compressible": true + }, + "application/atsc-rsat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rsat"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana", + "compressible": true + }, + "application/bacnet-xdd+zip": { + "source": "iana", + "compressible": false + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xcs"] + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/captive+json": { + "source": "iana", + "compressible": true + }, + "application/cbor": { + "source": "iana" + }, + "application/cbor-seq": { + "source": "iana" + }, + "application/cccex": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana", + "compressible": true + }, + "application/ccxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ccxml"] + }, + "application/cdfx+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdfx"] + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana", + "compressible": true + }, + "application/cellml+xml": { + "source": "iana", + "compressible": true + }, + "application/cfw": { + "source": "iana" + }, + "application/city+json": { + "source": "iana", + "compressible": true + }, + "application/clr": { + "source": "iana" + }, + "application/clue+xml": { + "source": "iana", + "compressible": true + }, + "application/clue_info+xml": { + "source": "iana", + "compressible": true + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana", + "compressible": true + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/coap-payload": { + "source": "iana" + }, + "application/commonground": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/cose": { + "source": "iana" + }, + "application/cose-key": { + "source": "iana" + }, + "application/cose-key-set": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cpl"] + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana", + "compressible": true + }, + "application/cstadata+xml": { + "source": "iana", + "compressible": true + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cwt": { + "source": "iana" + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpd"] + }, + "application/dash-patch+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpp"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "compressible": true, + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana", + "compressible": true + }, + "application/dicom": { + "source": "iana" + }, + "application/dicom+json": { + "source": "iana", + "compressible": true + }, + "application/dicom+xml": { + "source": "iana", + "compressible": true + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/dns+json": { + "source": "iana", + "compressible": true + }, + "application/dns-message": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dbk"] + }, + "application/dots+cbor": { + "source": "iana" + }, + "application/dskpp+xml": { + "source": "iana", + "compressible": true + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/ecmascript": { + "source": "iana", + "compressible": true, + "extensions": ["es","ecma"] + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/efi": { + "source": "iana" + }, + "application/elm+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/elm+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.cap+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/emergencycalldata.comment+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.control+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.ecall.msd": { + "source": "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.veds+xml": { + "source": "iana", + "compressible": true + }, + "application/emma+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emotionml"] + }, + "application/encaprtp": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana", + "compressible": true + }, + "application/epub+zip": { + "source": "iana", + "compressible": false, + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/expect-ct-report+json": { + "source": "iana", + "compressible": true + }, + "application/express": { + "source": "iana", + "extensions": ["exp"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["fdt"] + }, + "application/fhir+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/fhir+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/fido.trusted-apps+json": { + "compressible": true + }, + "application/fits": { + "source": "iana" + }, + "application/flexfec": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false + }, + "application/framework-attributes+xml": { + "source": "iana", + "compressible": true + }, + "application/geo+json": { + "source": "iana", + "compressible": true, + "extensions": ["geojson"] + }, + "application/geo+json-seq": { + "source": "iana" + }, + "application/geopackage+sqlite3": { + "source": "iana" + }, + "application/geoxacml+xml": { + "source": "iana", + "compressible": true + }, + "application/gltf-buffer": { + "source": "iana" + }, + "application/gml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["gml"] + }, + "application/gpx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["gpx"] + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false, + "extensions": ["gz"] + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana", + "compressible": true + }, + "application/hjson": { + "extensions": ["hjson"] + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pkg-reply+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana", + "compressible": true, + "extensions": ["its"] + }, + "application/java-archive": { + "source": "apache", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js","mjs"] + }, + "application/jf2feed+json": { + "source": "iana", + "compressible": true + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/jscalendar+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana", + "compressible": true + }, + "application/kpml-response+xml": { + "source": "iana", + "compressible": true + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/lgr+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lgr"] + }, + "application/link-format": { + "source": "iana" + }, + "application/load-control+xml": { + "source": "iana", + "compressible": true + }, + "application/lost+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana", + "compressible": true + }, + "application/lpf+zip": { + "source": "iana", + "compressible": false + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mads"] + }, + "application/manifest+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana", + "compressible": true + }, + "application/mathml-presentation+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-deregister+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-envelope+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-protection-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-reception-report+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-schedule+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-user-service-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpf"] + }, + "application/media_control+xml": { + "source": "iana", + "compressible": true + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "compressible": true, + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "compressible": true, + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mipc": { + "source": "iana" + }, + "application/missing-blocks+cbor-seq": { + "source": "iana" + }, + "application/mmt-aei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["maei"] + }, + "application/mmt-usd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musd"] + }, + "application/mods+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana", + "compressible": true + }, + "application/mrb-publish+xml": { + "source": "iana", + "compressible": true + }, + "application/msc-ivr+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/msc-mixer+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mud+json": { + "source": "iana", + "compressible": true + }, + "application/multipart-core": { + "source": "iana" + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/n-quads": { + "source": "iana", + "extensions": ["nq"] + }, + "application/n-triples": { + "source": "iana", + "extensions": ["nt"] + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana", + "charset": "US-ASCII" + }, + "application/news-groupinfo": { + "source": "iana", + "charset": "US-ASCII" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana", + "compressible": true + }, + "application/node": { + "source": "iana", + "extensions": ["cjs"] + }, + "application/nss": { + "source": "iana" + }, + "application/oauth-authz-req+jwt": { + "source": "iana" + }, + "application/oblivious-dns-message": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": false, + "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"] + }, + "application/oda": { + "source": "iana", + "extensions": ["oda"] + }, + "application/odm+xml": { + "source": "iana", + "compressible": true + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/omdoc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg"] + }, + "application/opc-nodeset+xml": { + "source": "iana", + "compressible": true + }, + "application/oscore": { + "source": "iana" + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p21": { + "source": "iana" + }, + "application/p21+zip": { + "source": "iana", + "compressible": false + }, + "application/p2p-overlay+xml": { + "source": "iana", + "compressible": true, + "extensions": ["relo"] + }, + "application/parityfec": { + "source": "iana" + }, + "application/passport": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pem-certificate-chain": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana", + "extensions": ["asc"] + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["asc","sig"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/pidf-diff+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkcs8-encrypted": { + "source": "iana" + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/ppsp-tracker+json": { + "source": "iana", + "compressible": true + }, + "application/problem+json": { + "source": "iana", + "compressible": true + }, + "application/problem+xml": { + "source": "iana", + "compressible": true + }, + "application/provenance+xml": { + "source": "iana", + "compressible": true, + "extensions": ["provx"] + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.cyn": { + "source": "iana", + "charset": "7-BIT" + }, + "application/prs.hpub+zip": { + "source": "iana", + "compressible": false + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana", + "compressible": true + }, + "application/pskc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pskcxml"] + }, + "application/pvd+json": { + "source": "iana", + "compressible": true + }, + "application/qsig": { + "source": "iana" + }, + "application/raml+yaml": { + "compressible": true, + "extensions": ["raml"] + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf","owl"] + }, + "application/reginfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "iana" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resource-lists+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana", + "compressible": true + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana", + "compressible": true + }, + "application/rls-services+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rs"] + }, + "application/route-apd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rapd"] + }, + "application/route-s-tsid+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sls"] + }, + "application/route-usd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rusd"] + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-publication": { + "source": "iana" + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana", + "compressible": true + }, + "application/samlmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/sarif+json": { + "source": "iana", + "compressible": true + }, + "application/sarif-external-properties+json": { + "source": "iana", + "compressible": true + }, + "application/sbe": { + "source": "iana" + }, + "application/sbml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana", + "compressible": true + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/secevent+jwt": { + "source": "iana" + }, + "application/senml+cbor": { + "source": "iana" + }, + "application/senml+json": { + "source": "iana", + "compressible": true + }, + "application/senml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["senmlx"] + }, + "application/senml-etch+cbor": { + "source": "iana" + }, + "application/senml-etch+json": { + "source": "iana", + "compressible": true + }, + "application/senml-exi": { + "source": "iana" + }, + "application/sensml+cbor": { + "source": "iana" + }, + "application/sensml+json": { + "source": "iana", + "compressible": true + }, + "application/sensml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sensmlx"] + }, + "application/sensml-exi": { + "source": "iana" + }, + "application/sep+xml": { + "source": "iana", + "compressible": true + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana", + "extensions": ["siv","sieve"] + }, + "application/simple-filter+xml": { + "source": "iana", + "compressible": true + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/sipc": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "iana" + }, + "application/smil+xml": { + "source": "iana", + "compressible": true, + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "compressible": true, + "extensions": ["srx"] + }, + "application/spdx+json": { + "source": "iana", + "compressible": true + }, + "application/spirits-event+xml": { + "source": "iana", + "compressible": true + }, + "application/sql": { + "source": "iana" + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ssdl"] + }, + "application/ssml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ssml"] + }, + "application/stix+json": { + "source": "iana", + "compressible": true + }, + "application/swid+xml": { + "source": "iana", + "compressible": true, + "extensions": ["swidtag"] + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/taxii+json": { + "source": "iana", + "compressible": true + }, + "application/td+json": { + "source": "iana", + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tei","teicorpus"] + }, + "application/tetra_isi": { + "source": "iana" + }, + "application/thraud+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/tlsrpt+gzip": { + "source": "iana" + }, + "application/tlsrpt+json": { + "source": "iana", + "compressible": true + }, + "application/tnauthlist": { + "source": "iana" + }, + "application/token-introspection+jwt": { + "source": "iana" + }, + "application/toml": { + "compressible": true, + "extensions": ["toml"] + }, + "application/trickle-ice-sdpfrag": { + "source": "iana" + }, + "application/trig": { + "source": "iana", + "extensions": ["trig"] + }, + "application/ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ttml"] + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/tzif": { + "source": "iana" + }, + "application/tzif-leap": { + "source": "iana" + }, + "application/ubjson": { + "compressible": false, + "extensions": ["ubj"] + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/urc-ressheet+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rsheet"] + }, + "application/urc-targetdesc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["td"] + }, + "application/urc-uisocketdesc+xml": { + "source": "iana", + "compressible": true + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana", + "compressible": true + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.1000minds.decision-model+xml": { + "source": "iana", + "compressible": true, + "extensions": ["1km"] + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-v2x-local-service-information": { + "source": "iana" + }, + "application/vnd.3gpp.5gnas": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gmop+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gtpc": { + "source": "iana" + }, + "application/vnd.3gpp.interworking-data": { + "source": "iana" + }, + "application/vnd.3gpp.lpp": { + "source": "iana" + }, + "application/vnd.3gpp.mc-signalling-ear": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-payload": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-signalling": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-floor-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-signed+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-ue-init-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-affiliation-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-transmission-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ngap": { + "source": "iana" + }, + "application/vnd.3gpp.pfcp": { + "source": "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.s1ap": { + "source": "iana" + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.sms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3lightssoftware.imagescal": { + "source": "iana" + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "compressible": false, + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata-pagedef": { + "source": "iana" + }, + "application/vnd.afpc.cmoca-cmresource": { + "source": "iana" + }, + "application/vnd.afpc.foca-charset": { + "source": "iana" + }, + "application/vnd.afpc.foca-codedfont": { + "source": "iana" + }, + "application/vnd.afpc.foca-codepage": { + "source": "iana" + }, + "application/vnd.afpc.modca": { + "source": "iana" + }, + "application/vnd.afpc.modca-cmtable": { + "source": "iana" + }, + "application/vnd.afpc.modca-formdef": { + "source": "iana" + }, + "application/vnd.afpc.modca-mediummap": { + "source": "iana" + }, + "application/vnd.afpc.modca-objectcontainer": { + "source": "iana" + }, + "application/vnd.afpc.modca-overlay": { + "source": "iana" + }, + "application/vnd.afpc.modca-pagesegment": { + "source": "iana" + }, + "application/vnd.age": { + "source": "iana", + "extensions": ["age"] + }, + "application/vnd.ah-barcode": { + "source": "iana" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amadeus+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.amazon.mobi8-ebook": { + "source": "iana" + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.android.ota": { + "source": "iana" + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.arrow.file": { + "source": "iana" + }, + "application/vnd.apache.arrow.stream": { + "source": "iana" + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.aplextor.warrp+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apothekende.reservation+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpkg"] + }, + "application/vnd.apple.keynote": { + "source": "iana", + "extensions": ["key"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.numbers": { + "source": "iana", + "extensions": ["numbers"] + }, + "application/vnd.apple.pages": { + "source": "iana", + "extensions": ["pages"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "iana" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artisan+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avalon+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.avistar+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["bmml"] + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.banana-accounting": { + "source": "iana" + }, + "application/vnd.bbf.usp.error": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bint.med-content": { + "source": "iana" + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.blink-idb-value-wrapper": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.bpf": { + "source": "iana" + }, + "application/vnd.bpf3": { + "source": "iana" + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.byu.uapi+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.capasystems-pg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdxml"] + }, + "application/vnd.chess-pgn": { + "source": "iana" + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.ciedi": { + "source": "iana" + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana", + "compressible": true, + "extensions": ["csl"] + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet-template": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.comicbook+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.comicbook-rar": { + "source": "iana" + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.coreos.ignition+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wbs"] + }, + "application/vnd.cryptii.pipe+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.crypto-shade-file": { + "source": "iana" + }, + "application/vnd.cryptomator.encrypted": { + "source": "iana" + }, + "application/vnd.cryptomator.vault": { + "source": "iana" + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.cyclonedx+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cyclonedx+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.d2l.coursepackage1p0+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.d3m-dataset": { + "source": "iana" + }, + "application/vnd.d3m-problem": { + "source": "iana" + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.datapackage+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dataresource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dbf": { + "source": "iana", + "extensions": ["dbf"] + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume.movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbisl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecip.rlp": { + "source": "iana" + }, + "application/vnd.eclipse.ditto+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.efi.img": { + "source": "iana" + }, + "application/vnd.efi.iso": { + "source": "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.espass-espass+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "compressible": true, + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.cug+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.sci+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eu.kasparian.car+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.evolv.ecig.profile": { + "source": "iana" + }, + "application/vnd.evolv.ecig.settings": { + "source": "iana" + }, + "application/vnd.evolv.ecig.theme": { + "source": "iana" + }, + "application/vnd.exstream-empower+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.exstream-package": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.familysearch.gedcom+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.ficlab.flb+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.frogans.fnc": { + "source": "iana", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "iana", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujifilm.fb.docuworks": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.docuworks.binder": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.jfi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.futoin+cbor": { + "source": "iana" + }, + "application/vnd.futoin+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.gentics.grd+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geo+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.slides": { + "source": "iana" + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "compressible": true, + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.hdt": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hl7cda+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.hl7v2+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyper+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyper-item+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "iana" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "iana", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.imagemeter.folder+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.imagemeter.image+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.informix-visionary": { + "source": "iana" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.iso11783-10+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las": { + "source": "iana" + }, + "application/vnd.las.las+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.las.las+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lasxml"] + }, + "application/vnd.laszip": { + "source": "iana" + }, + "application/vnd.leap+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.liberty-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lbe"] + }, + "application/vnd.logipipe.circuit+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.loom": { + "source": "iana" + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana", + "extensions": ["mvt"] + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxar.archive.3tz+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.microsoft.windows.thumbnail-cache": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-outlook": { + "compressible": false, + "extensions": ["msg"] + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-printschematicket+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.nacamar.ybrid+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nearst.inv+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.nebumind.line": { + "source": "iana" + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nimn": { + "source": "iana" + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ac"] + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "iana", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "iana", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.ocf+cbor": { + "source": "iana" + }, + "application/vnd.oci.image.manifest.v1+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+cbor": { + "source": "iana" + }, + "application/vnd.oma.lwm2m+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+tlv": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.omads-email+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omads-file+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omads-folder+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.onepager": { + "source": "iana" + }, + "application/vnd.onepagertamp": { + "source": "iana" + }, + "application/vnd.onepagertamx": { + "source": "iana" + }, + "application/vnd.onepagertat": { + "source": "iana" + }, + "application/vnd.onepagertatp": { + "source": "iana" + }, + "application/vnd.onepagertatx": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana", + "compressible": true, + "extensions": ["obgx"] + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openstreetmap.data+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osm"] + }, + "application/vnd.opentimestamps.ots": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "iana", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "iana", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "iana", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "iana" + }, + "application/vnd.patentdive": { + "source": "iana" + }, + "application/vnd.patientecommsdoc": { + "source": "iana" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.psfs": { + "source": "iana" + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quarantainenet": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.rar": { + "source": "iana", + "extensions": ["rar"] + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.resilient.logic": { + "source": "iana" + }, + "application/vnd.restful+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "compressible": true, + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sar": { + "source": "iana" + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.seis+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shade-save-file": { + "source": "iana" + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.shootproof+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.shopkick+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.shp": { + "source": "iana" + }, + "application/vnd.shx": { + "source": "iana" + }, + "application/vnd.sigrok.session": { + "source": "iana" + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.snesdev-page-table": { + "source": "iana" + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana", + "compressible": true, + "extensions": ["fo"] + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sqlite3": { + "source": "iana" + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wadl"] + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.sycle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.syft+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["ddf"] + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tableschema+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.think-cell.ppttc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.tri.onesource": { + "source": "iana" + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uoml"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.vel+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.veritone.aion+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.veryant.thin": { + "source": "iana" + }, + "application/vnd.ves.encrypted": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.dpp": { + "source": "iana" + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.wv.ssp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.youtube.yt": { + "source": "iana" + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["vxml"] + }, + "application/voucher-cms+json": { + "source": "iana", + "compressible": true + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/wasm": { + "source": "iana", + "compressible": true, + "extensions": ["wasm"] + }, + "application/watcherinfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wif"] + }, + "application/webpush-options+json": { + "source": "iana", + "compressible": true + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-arj": { + "compressible": false, + "extensions": ["arj"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "compressible": true, + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-iwork-keynote-sffkey": { + "extensions": ["key"] + }, + "application/x-iwork-numbers-sffnumbers": { + "extensions": ["numbers"] + }, + "application/x-iwork-pages-sffpages": { + "extensions": ["pages"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-keepass2": { + "extensions": ["kdbx"] + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "source": "apache", + "extensions": ["nc","cdf"] + }, + "application/x-ns-proxy-autoconfig": { + "compressible": true, + "extensions": ["pac"] + }, + "application/x-nzb": { + "source": "apache", + "extensions": ["nzb"] + }, + "application/x-perl": { + "source": "nginx", + "extensions": ["pl","pm"] + }, + "application/x-pilot": { + "source": "nginx", + "extensions": ["prc","pdb"] + }, + "application/x-pkcs12": { + "source": "apache", + "compressible": false, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-pki-message": { + "source": "iana" + }, + "application/x-rar-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["rar"] + }, + "application/x-redhat-package-manager": { + "source": "nginx", + "extensions": ["rpm"] + }, + "application/x-research-info-systems": { + "source": "apache", + "extensions": ["ris"] + }, + "application/x-sea": { + "source": "nginx", + "extensions": ["sea"] + }, + "application/x-sh": { + "source": "apache", + "compressible": true, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-virtualbox-hdd": { + "compressible": true, + "extensions": ["hdd"] + }, + "application/x-virtualbox-ova": { + "compressible": true, + "extensions": ["ova"] + }, + "application/x-virtualbox-ovf": { + "compressible": true, + "extensions": ["ovf"] + }, + "application/x-virtualbox-vbox": { + "compressible": true, + "extensions": ["vbox"] + }, + "application/x-virtualbox-vbox-extpack": { + "compressible": false, + "extensions": ["vbox-extpack"] + }, + "application/x-virtualbox-vdi": { + "compressible": true, + "extensions": ["vdi"] + }, + "application/x-virtualbox-vhd": { + "compressible": true, + "extensions": ["vhd"] + }, + "application/x-virtualbox-vmdk": { + "compressible": true, + "extensions": ["vmdk"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "iana", + "extensions": ["der","crt","pem"] + }, + "application/x-x509-ca-ra-cert": { + "source": "iana" + }, + "application/x-x509-next-ca-cert": { + "source": "iana" + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana", + "compressible": true + }, + "application/xaml+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xav"] + }, + "application/xcap-caps+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xca"] + }, + "application/xcap-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xel"] + }, + "application/xcap-error+xml": { + "source": "iana", + "compressible": true + }, + "application/xcap-ns+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xns"] + }, + "application/xcon-conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana", + "compressible": true + }, + "application/xenc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xenc"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache", + "compressible": true + }, + "application/xliff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xlf"] + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd","rng"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/xmpp+xml": { + "source": "iana", + "compressible": true + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xsl","xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yang-data+json": { + "source": "iana", + "compressible": true + }, + "application/yang-data+xml": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+json": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/yin+xml": { + "source": "iana", + "compressible": true, + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zlib": { + "source": "iana" + }, + "application/zstd": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana", + "compressible": false, + "extensions": ["3gpp"] + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/aac": { + "source": "iana" + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana", + "extensions": ["amr"] + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/flexfec": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/melp": { + "source": "iana" + }, + "audio/melp1200": { + "source": "iana" + }, + "audio/melp2400": { + "source": "iana" + }, + "audio/melp600": { + "source": "iana" + }, + "audio/mhas": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/mobile-xmf": { + "source": "iana", + "extensions": ["mxmf"] + }, + "audio/mp3": { + "compressible": false, + "extensions": ["mp3"] + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["m4a","mp4a"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx","opus"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/scip": { + "source": "iana" + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sofa": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tetra_acelp": { + "source": "iana" + }, + "audio/tetra_acelp_bb": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/tsvcis": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/usac": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dts.uhd": { + "source": "iana" + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.presonus.multitrack": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/collection": { + "source": "iana", + "extensions": ["ttc"] + }, + "font/otf": { + "source": "iana", + "compressible": true, + "extensions": ["otf"] + }, + "font/sfnt": { + "source": "iana" + }, + "font/ttf": { + "source": "iana", + "compressible": true, + "extensions": ["ttf"] + }, + "font/woff": { + "source": "iana", + "extensions": ["woff"] + }, + "font/woff2": { + "source": "iana", + "extensions": ["woff2"] + }, + "image/aces": { + "source": "iana", + "extensions": ["exr"] + }, + "image/apng": { + "compressible": false, + "extensions": ["apng"] + }, + "image/avci": { + "source": "iana", + "extensions": ["avci"] + }, + "image/avcs": { + "source": "iana", + "extensions": ["avcs"] + }, + "image/avif": { + "source": "iana", + "compressible": false, + "extensions": ["avif"] + }, + "image/bmp": { + "source": "iana", + "compressible": true, + "extensions": ["bmp"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/dicom-rle": { + "source": "iana", + "extensions": ["drle"] + }, + "image/emf": { + "source": "iana", + "extensions": ["emf"] + }, + "image/fits": { + "source": "iana", + "extensions": ["fits"] + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/heic": { + "source": "iana", + "extensions": ["heic"] + }, + "image/heic-sequence": { + "source": "iana", + "extensions": ["heics"] + }, + "image/heif": { + "source": "iana", + "extensions": ["heif"] + }, + "image/heif-sequence": { + "source": "iana", + "extensions": ["heifs"] + }, + "image/hej2k": { + "source": "iana", + "extensions": ["hej2"] + }, + "image/hsj2": { + "source": "iana", + "extensions": ["hsj2"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/jls": { + "source": "iana", + "extensions": ["jls"] + }, + "image/jp2": { + "source": "iana", + "compressible": false, + "extensions": ["jp2","jpg2"] + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpeg","jpg","jpe"] + }, + "image/jph": { + "source": "iana", + "extensions": ["jph"] + }, + "image/jphc": { + "source": "iana", + "extensions": ["jhc"] + }, + "image/jpm": { + "source": "iana", + "compressible": false, + "extensions": ["jpm"] + }, + "image/jpx": { + "source": "iana", + "compressible": false, + "extensions": ["jpx","jpf"] + }, + "image/jxr": { + "source": "iana", + "extensions": ["jxr"] + }, + "image/jxra": { + "source": "iana", + "extensions": ["jxra"] + }, + "image/jxrs": { + "source": "iana", + "extensions": ["jxrs"] + }, + "image/jxs": { + "source": "iana", + "extensions": ["jxs"] + }, + "image/jxsc": { + "source": "iana", + "extensions": ["jxsc"] + }, + "image/jxsi": { + "source": "iana", + "extensions": ["jxsi"] + }, + "image/jxss": { + "source": "iana", + "extensions": ["jxss"] + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/ktx2": { + "source": "iana", + "extensions": ["ktx2"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif"] + }, + "image/prs.pti": { + "source": "iana", + "extensions": ["pti"] + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana", + "extensions": ["t38"] + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tif","tiff"] + }, + "image/tiff-fx": { + "source": "iana", + "extensions": ["tfx"] + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana", + "extensions": ["azv"] + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana", + "compressible": true, + "extensions": ["ico"] + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-dds": { + "compressible": true, + "extensions": ["dds"] + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.pco.b16": { + "source": "iana", + "extensions": ["b16"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana", + "extensions": ["tap"] + }, + "image/vnd.valve.source.texture": { + "source": "iana", + "extensions": ["vtf"] + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana", + "extensions": ["pcx"] + }, + "image/webp": { + "source": "apache", + "extensions": ["webp"] + }, + "image/wmf": { + "source": "iana", + "extensions": ["wmf"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "compressible": true, + "extensions": ["ico"] + }, + "image/x-jng": { + "source": "nginx", + "extensions": ["jng"] + }, + "image/x-mrsid-image": { + "source": "apache", + "extensions": ["sid"] + }, + "image/x-ms-bmp": { + "source": "nginx", + "compressible": true, + "extensions": ["bmp"] + }, + "image/x-pcx": { + "source": "apache", + "extensions": ["pcx"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana", + "extensions": [ + "disposition-notification" + ] + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana", + "extensions": ["u8msg"] + }, + "message/global-delivery-status": { + "source": "iana", + "extensions": ["u8dsn"] + }, + "message/global-disposition-notification": { + "source": "iana", + "extensions": ["u8mdn"] + }, + "message/global-headers": { + "source": "iana", + "extensions": ["u8hdr"] + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/news": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime"] + }, + "message/s-http": { + "source": "iana" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "iana" + }, + "message/vnd.wfa.wsc": { + "source": "iana", + "extensions": ["wsc"] + }, + "model/3mf": { + "source": "iana", + "extensions": ["3mf"] + }, + "model/e57": { + "source": "iana" + }, + "model/gltf+json": { + "source": "iana", + "compressible": true, + "extensions": ["gltf"] + }, + "model/gltf-binary": { + "source": "iana", + "compressible": true, + "extensions": ["glb"] + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/mtl": { + "source": "iana", + "extensions": ["mtl"] + }, + "model/obj": { + "source": "iana", + "extensions": ["obj"] + }, + "model/step": { + "source": "iana" + }, + "model/step+xml": { + "source": "iana", + "compressible": true, + "extensions": ["stpx"] + }, + "model/step+zip": { + "source": "iana", + "compressible": false, + "extensions": ["stpz"] + }, + "model/step-xml+zip": { + "source": "iana", + "compressible": false, + "extensions": ["stpxz"] + }, + "model/stl": { + "source": "iana", + "extensions": ["stl"] + }, + "model/vnd.collada+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana", + "compressible": true + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana", + "extensions": ["ogex"] + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana", + "extensions": ["x_b"] + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana", + "extensions": ["x_t"] + }, + "model/vnd.pytha.pyox": { + "source": "iana" + }, + "model/vnd.rosette.annotated-data-model": { + "source": "iana" + }, + "model/vnd.sap.vds": { + "source": "iana", + "extensions": ["vds"] + }, + "model/vnd.usdz+zip": { + "source": "iana", + "compressible": false, + "extensions": ["usdz"] + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana", + "extensions": ["bsp"] + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana", + "extensions": ["x3db"] + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana", + "extensions": ["x3dv"] + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana" + }, + "multipart/multilingual": { + "source": "iana" + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/vnd.bint.med-plus": { + "source": "iana" + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/cql": { + "source": "iana" + }, + "text/cql-expression": { + "source": "iana" + }, + "text/cql-identifier": { + "source": "iana" + }, + "text/css": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "iana" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fhirpath": { + "source": "iana" + }, + "text/flexfec": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/gff3": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "compressible": true + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "compressible": true, + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana", + "compressible": true, + "extensions": ["markdown","md"] + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mdx": { + "compressible": true, + "extensions": ["mdx"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana", + "charset": "UTF-8" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana", + "charset": "UTF-8" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/prs.prop.logic": { + "source": "iana" + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/shaclc": { + "source": "iana" + }, + "text/shex": { + "source": "iana", + "extensions": ["shex"] + }, + "text/slim": { + "extensions": ["slim","slm"] + }, + "text/spdx": { + "source": "iana", + "extensions": ["spdx"] + }, + "text/strings": { + "source": "iana" + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.ascii-art": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.familysearch.gedcom": { + "source": "iana", + "extensions": ["ged"] + }, + "text/vnd.ficlab.flt": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.gml": { + "source": "iana" + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.hans": { + "source": "iana" + }, + "text/vnd.hgl": { + "source": "iana" + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.senx.warpscript": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "iana" + }, + "text/vnd.sosi": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vtt": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-org": { + "compressible": true, + "extensions": ["org"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "compressible": true, + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "iana" + }, + "video/3gpp": { + "source": "iana", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "iana" + }, + "video/3gpp2": { + "source": "iana", + "extensions": ["3g2"] + }, + "video/av1": { + "source": "iana" + }, + "video/bmpeg": { + "source": "iana" + }, + "video/bt656": { + "source": "iana" + }, + "video/celb": { + "source": "iana" + }, + "video/dv": { + "source": "iana" + }, + "video/encaprtp": { + "source": "iana" + }, + "video/ffv1": { + "source": "iana" + }, + "video/flexfec": { + "source": "iana" + }, + "video/h261": { + "source": "iana", + "extensions": ["h261"] + }, + "video/h263": { + "source": "iana", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "iana" + }, + "video/h263-2000": { + "source": "iana" + }, + "video/h264": { + "source": "iana", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "iana" + }, + "video/h264-svc": { + "source": "iana" + }, + "video/h265": { + "source": "iana" + }, + "video/iso.segment": { + "source": "iana", + "extensions": ["m4s"] + }, + "video/jpeg": { + "source": "iana", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "iana" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/jxsv": { + "source": "iana" + }, + "video/mj2": { + "source": "iana", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "iana" + }, + "video/mp2p": { + "source": "iana" + }, + "video/mp2t": { + "source": "iana", + "extensions": ["ts"] + }, + "video/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "iana" + }, + "video/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "iana" + }, + "video/mpv": { + "source": "iana" + }, + "video/nv": { + "source": "iana" + }, + "video/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "iana" + }, + "video/pointer": { + "source": "iana" + }, + "video/quicktime": { + "source": "iana", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raptorfec": { + "source": "iana" + }, + "video/raw": { + "source": "iana" + }, + "video/rtp-enc-aescm128": { + "source": "iana" + }, + "video/rtploopback": { + "source": "iana" + }, + "video/rtx": { + "source": "iana" + }, + "video/scip": { + "source": "iana" + }, + "video/smpte291": { + "source": "iana" + }, + "video/smpte292m": { + "source": "iana" + }, + "video/ulpfec": { + "source": "iana" + }, + "video/vc1": { + "source": "iana" + }, + "video/vc2": { + "source": "iana" + }, + "video/vnd.cctv": { + "source": "iana" + }, + "video/vnd.dece.hd": { + "source": "iana", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "iana", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "iana" + }, + "video/vnd.dece.pd": { + "source": "iana", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "iana", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "iana", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "iana" + }, + "video/vnd.directv.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dvb.file": { + "source": "iana", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "iana", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "iana" + }, + "video/vnd.motorola.video": { + "source": "iana" + }, + "video/vnd.motorola.videop": { + "source": "iana" + }, + "video/vnd.mpegurl": { + "source": "iana", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "iana", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "iana" + }, + "video/vnd.nokia.mp4vr": { + "source": "iana" + }, + "video/vnd.nokia.videovoip": { + "source": "iana" + }, + "video/vnd.objectvideo": { + "source": "iana" + }, + "video/vnd.radgamettools.bink": { + "source": "iana" + }, + "video/vnd.radgamettools.smacker": { + "source": "iana" + }, + "video/vnd.sealed.mpeg1": { + "source": "iana" + }, + "video/vnd.sealed.mpeg4": { + "source": "iana" + }, + "video/vnd.sealed.swf": { + "source": "iana" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "iana" + }, + "video/vnd.uvvu.mp4": { + "source": "iana", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "iana", + "extensions": ["viv"] + }, + "video/vnd.youtube.yt": { + "source": "iana" + }, + "video/vp8": { + "source": "iana" + }, + "video/vp9": { + "source": "iana" + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/node_modules/mime-db/index.js b/node_modules/mime-db/index.js new file mode 100644 index 0000000..ec2be30 --- /dev/null +++ b/node_modules/mime-db/index.js @@ -0,0 +1,12 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/node_modules/mime-db/package.json b/node_modules/mime-db/package.json new file mode 100644 index 0000000..32c14b8 --- /dev/null +++ b/node_modules/mime-db/package.json @@ -0,0 +1,60 @@ +{ + "name": "mime-db", + "description": "Media Type Database", + "version": "1.52.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)", + "Robert Kieffer (http://github.com/broofa)" + ], + "license": "MIT", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "repository": "jshttp/mime-db", + "devDependencies": { + "bluebird": "3.7.2", + "co": "4.6.0", + "cogent": "1.0.1", + "csv-parse": "4.16.3", + "eslint": "7.32.0", + "eslint-config-standard": "15.0.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.1.1", + "eslint-plugin-standard": "4.1.0", + "gnode": "0.1.2", + "media-typer": "1.1.0", + "mocha": "9.2.1", + "nyc": "15.1.0", + "raw-body": "2.5.0", + "stream-to-array": "2.3.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build", + "fetch": "node scripts/fetch-apache && gnode scripts/fetch-iana && node scripts/fetch-nginx", + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "update": "npm run fetch && npm run build", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/mime-types/HISTORY.md b/node_modules/mime-types/HISTORY.md new file mode 100644 index 0000000..c5043b7 --- /dev/null +++ b/node_modules/mime-types/HISTORY.md @@ -0,0 +1,397 @@ +2.1.35 / 2022-03-12 +=================== + + * deps: mime-db@1.52.0 + - Add extensions from IANA for more `image/*` types + - Add extension `.asc` to `application/pgp-keys` + - Add extensions to various XML types + - Add new upstream MIME types + +2.1.34 / 2021-11-08 +=================== + + * deps: mime-db@1.51.0 + - Add new upstream MIME types + +2.1.33 / 2021-10-01 +=================== + + * deps: mime-db@1.50.0 + - Add deprecated iWorks mime types and extensions + - Add new upstream MIME types + +2.1.32 / 2021-07-27 +=================== + + * deps: mime-db@1.49.0 + - Add extension `.trig` to `application/trig` + - Add new upstream MIME types + +2.1.31 / 2021-06-01 +=================== + + * deps: mime-db@1.48.0 + - Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + - Add new upstream MIME types + +2.1.30 / 2021-04-02 +=================== + + * deps: mime-db@1.47.0 + - Add extension `.amr` to `audio/amr` + - Remove ambigious extensions from IANA for `application/*+xml` types + - Update primary extension to `.es` for `application/ecmascript` + +2.1.29 / 2021-02-17 +=================== + + * deps: mime-db@1.46.0 + - Add extension `.amr` to `audio/amr` + - Add extension `.m4s` to `video/iso.segment` + - Add extension `.opus` to `audio/ogg` + - Add new upstream MIME types + +2.1.28 / 2021-01-01 +=================== + + * deps: mime-db@1.45.0 + - Add `application/ubjson` with extension `.ubj` + - Add `image/avif` with extension `.avif` + - Add `image/ktx2` with extension `.ktx2` + - Add extension `.dbf` to `application/vnd.dbf` + - Add extension `.rar` to `application/vnd.rar` + - Add extension `.td` to `application/urc-targetdesc+xml` + - Add new upstream MIME types + - Fix extension of `application/vnd.apple.keynote` to be `.key` + +2.1.27 / 2020-04-23 +=================== + + * deps: mime-db@1.44.0 + - Add charsets from IANA + - Add extension `.cjs` to `application/node` + - Add new upstream MIME types + +2.1.26 / 2020-01-05 +=================== + + * deps: mime-db@1.43.0 + - Add `application/x-keepass2` with extension `.kdbx` + - Add extension `.mxmf` to `audio/mobile-xmf` + - Add extensions from IANA for `application/*+xml` types + - Add new upstream MIME types + +2.1.25 / 2019-11-12 +=================== + + * deps: mime-db@1.42.0 + - Add new upstream MIME types + - Add `application/toml` with extension `.toml` + - Add `image/vnd.ms-dds` with extension `.dds` + +2.1.24 / 2019-04-20 +=================== + + * deps: mime-db@1.40.0 + - Add extensions from IANA for `model/*` types + - Add `text/mdx` with extension `.mdx` + +2.1.23 / 2019-04-17 +=================== + + * deps: mime-db@~1.39.0 + - Add extensions `.siv` and `.sieve` to `application/sieve` + - Add new upstream MIME types + +2.1.22 / 2019-02-14 +=================== + + * deps: mime-db@~1.38.0 + - Add extension `.nq` to `application/n-quads` + - Add extension `.nt` to `application/n-triples` + - Add new upstream MIME types + +2.1.21 / 2018-10-19 +=================== + + * deps: mime-db@~1.37.0 + - Add extensions to HEIC image types + - Add new upstream MIME types + +2.1.20 / 2018-08-26 +=================== + + * deps: mime-db@~1.36.0 + - Add Apple file extensions from IANA + - Add extensions from IANA for `image/*` types + - Add new upstream MIME types + +2.1.19 / 2018-07-17 +=================== + + * deps: mime-db@~1.35.0 + - Add extension `.csl` to `application/vnd.citationstyles.style+xml` + - Add extension `.es` to `application/ecmascript` + - Add extension `.owl` to `application/rdf+xml` + - Add new upstream MIME types + - Add UTF-8 as default charset for `text/turtle` + +2.1.18 / 2018-02-16 +=================== + + * deps: mime-db@~1.33.0 + - Add `application/raml+yaml` with extension `.raml` + - Add `application/wasm` with extension `.wasm` + - Add `text/shex` with extension `.shex` + - Add extensions for JPEG-2000 images + - Add extensions from IANA for `message/*` types + - Add new upstream MIME types + - Update font MIME types + - Update `text/hjson` to registered `application/hjson` + +2.1.17 / 2017-09-01 +=================== + + * deps: mime-db@~1.30.0 + - Add `application/vnd.ms-outlook` + - Add `application/x-arj` + - Add extension `.mjs` to `application/javascript` + - Add glTF types and extensions + - Add new upstream MIME types + - Add `text/x-org` + - Add VirtualBox MIME types + - Fix `source` records for `video/*` types that are IANA + - Update `font/opentype` to registered `font/otf` + +2.1.16 / 2017-07-24 +=================== + + * deps: mime-db@~1.29.0 + - Add `application/fido.trusted-apps+json` + - Add extension `.wadl` to `application/vnd.sun.wadl+xml` + - Add extension `.gz` to `application/gzip` + - Add new upstream MIME types + - Update extensions `.md` and `.markdown` to be `text/markdown` + +2.1.15 / 2017-03-23 +=================== + + * deps: mime-db@~1.27.0 + - Add new mime types + - Add `image/apng` + +2.1.14 / 2017-01-14 +=================== + + * deps: mime-db@~1.26.0 + - Add new mime types + +2.1.13 / 2016-11-18 +=================== + + * deps: mime-db@~1.25.0 + - Add new mime types + +2.1.12 / 2016-09-18 +=================== + + * deps: mime-db@~1.24.0 + - Add new mime types + - Add `audio/mp3` + +2.1.11 / 2016-05-01 +=================== + + * deps: mime-db@~1.23.0 + - Add new mime types + +2.1.10 / 2016-02-15 +=================== + + * deps: mime-db@~1.22.0 + - Add new mime types + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +2.1.1 / 2015-06-08 +================== + + * perf: fix deopt during mapping + +2.1.0 / 2015-06-07 +================== + + * Fix incorrectly treating extension-less file name as extension + - i.e. `'path/to/json'` will no longer return `application/json` + * Fix `.charset(type)` to accept parameters + * Fix `.charset(type)` to match case-insensitive + * Improve generation of extension to MIME mapping + * Refactor internals for readability and no argument reassignment + * Prefer `application/*` MIME types from the same source + * Prefer any type over `application/octet-stream` + * deps: mime-db@~1.13.0 + - Add nginx as a source + - Add new mime types + +2.0.14 / 2015-06-06 +=================== + + * deps: mime-db@~1.12.0 + - Add new mime types + +2.0.13 / 2015-05-31 +=================== + + * deps: mime-db@~1.11.0 + - Add new mime types + +2.0.12 / 2015-05-19 +=================== + + * deps: mime-db@~1.10.0 + - Add new mime types + +2.0.11 / 2015-05-05 +=================== + + * deps: mime-db@~1.9.1 + - Add new mime types + +2.0.10 / 2015-03-13 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/node_modules/mime-types/LICENSE b/node_modules/mime-types/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/node_modules/mime-types/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mime-types/README.md b/node_modules/mime-types/README.md new file mode 100644 index 0000000..48d2fb4 --- /dev/null +++ b/node_modules/mime-types/README.md @@ -0,0 +1,113 @@ +# mime-types + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +The ultimate javascript content-type utility. + +Similar to [the `mime@1.x` module](https://www.npmjs.com/package/mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, + `mime-types` simply returns `false`, so do + `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- No `.define()` functionality +- Bug fixes for `.lookup(path)` + +Otherwise, the API is compatible with `mime` 1.x. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install mime-types +``` + +## Adding Types + +All mime types are based on [mime-db](https://www.npmjs.com/package/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. +When given an extension, `mime.lookup` is used to get the matching +content-type, otherwise the given content-type is used. Then if the +content-type does not already have a `charset` parameter, `mime.charset` +is used to get the default charset and add to the returned content-type. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' +mime.contentType('text/html') // 'text/html; charset=utf-8' +mime.contentType('text/html; charset=iso-8859-1') // 'text/html; charset=iso-8859-1' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/mime-types/master?label=ci +[ci-url]: https://github.com/jshttp/mime-types/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-types/master +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types?branch=master +[node-version-image]: https://badgen.net/npm/node/mime-types +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mime-types +[npm-url]: https://npmjs.org/package/mime-types +[npm-version-image]: https://badgen.net/npm/v/mime-types diff --git a/node_modules/mime-types/index.js b/node_modules/mime-types/index.js new file mode 100644 index 0000000..b9f34d5 --- /dev/null +++ b/node_modules/mime-types/index.js @@ -0,0 +1,188 @@ +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var db = require('mime-db') +var extname = require('path').extname + +/** + * Module variables. + * @private + */ + +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i + +/** + * Module exports. + * @public + */ + +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] + + if (mime && mime.charset) { + return mime.charset + } + + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ + +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } + + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str + + if (!mime) { + return false + } + + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } + + return mime +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] + + if (!exts || !exts.length) { + return false + } + + return exts[0] +} + +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ + +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } + + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) + + if (!extension) { + return false + } + + return exports.types[extension] || false +} + +/** + * Populate the extensions and types maps. + * @private + */ + +function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] + + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions + + if (!exts || !exts.length) { + return + } + + // mime -> extensions + extensions[type] = exts + + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] + + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) + + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} diff --git a/node_modules/mime-types/package.json b/node_modules/mime-types/package.json new file mode 100644 index 0000000..bbef696 --- /dev/null +++ b/node_modules/mime-types/package.json @@ -0,0 +1,44 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "2.1.35", + "contributors": [ + "Douglas Christopher Wilson ", + "Jeremiah Senkpiel (https://searchbeam.jit.su)", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "mime", + "types" + ], + "repository": "jshttp/mime-types", + "dependencies": { + "mime-db": "1.52.0" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.2", + "nyc": "15.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec test/test.js", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/ms/index.js b/node_modules/ms/index.js new file mode 100644 index 0000000..ea734fb --- /dev/null +++ b/node_modules/ms/index.js @@ -0,0 +1,162 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function (val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} diff --git a/node_modules/ms/license.md b/node_modules/ms/license.md new file mode 100644 index 0000000..fa5d39b --- /dev/null +++ b/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Vercel, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/ms/package.json b/node_modules/ms/package.json new file mode 100644 index 0000000..4997189 --- /dev/null +++ b/node_modules/ms/package.json @@ -0,0 +1,38 @@ +{ + "name": "ms", + "version": "2.1.3", + "description": "Tiny millisecond conversion utility", + "repository": "vercel/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "4.18.2", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1", + "prettier": "2.0.5" + } +} diff --git a/node_modules/ms/readme.md b/node_modules/ms/readme.md new file mode 100644 index 0000000..0fc1abb --- /dev/null +++ b/node_modules/ms/readme.md @@ -0,0 +1,59 @@ +# ms + +![CI](https://github.com/vercel/ms/workflows/CI/badge.svg) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +ms('-3 days') // -259200000 +ms('-1h') // -3600000 +ms('-200') // -200 +``` + +### Convert from Milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(-3 * 60000) // "-3m" +ms(ms('10 hours')) // "10h" +``` + +### Time Format Written-Out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(-3 * 60000, { long: true }) // "-3 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [Node.js](https://nodejs.org) and in the browser +- If a number is supplied to `ms`, a string with a unit is returned +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) +- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned + +## Related Packages + +- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. + +## Caught a Bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/neo-async/LICENSE b/node_modules/neo-async/LICENSE new file mode 100644 index 0000000..4ec13d1 --- /dev/null +++ b/node_modules/neo-async/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-2018 Suguru Motegi +Based on Async.js, Copyright Caolan McMahon + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/neo-async/README.md b/node_modules/neo-async/README.md new file mode 100644 index 0000000..d49e93c --- /dev/null +++ b/node_modules/neo-async/README.md @@ -0,0 +1,273 @@ +

Neo-Async

+ +

+ +

+ +

+ npm + Travis Status + Coverage Status + download + Code Quality: Javascript + Total Alerts + FOSSA +

+ +Neo-Async is thought to be used as a drop-in replacement for [Async](https://github.com/caolan/async), it almost fully covers its functionality and runs [faster](#benchmark). + +Benchmark is [here](#benchmark)! + +Bluebird's benchmark is [here](https://github.com/suguru03/bluebird/tree/aigle/benchmark)! + +## Code Coverage +![coverage](https://raw.githubusercontent.com/wiki/suguru03/neo-async/images/coverage.png) + +## Installation + +### In a browser +```html + +``` + +### In an AMD loader +```js +require(['async'], function(async) {}); +``` + +### Promise and async/await + +I recommend to use [`Aigle`](https://github.com/suguru03/aigle). + +It is optimized for Promise handling and has almost the same functionality as `neo-async`. + +### Node.js + +#### standard + +```bash +$ npm install neo-async +``` +```js +var async = require('neo-async'); +``` + +#### replacement +```bash +$ npm install neo-async +$ ln -s ./node_modules/neo-async ./node_modules/async +``` +```js +var async = require('async'); +``` + +### Bower + +```bash +bower install neo-async +``` + +## Feature + +[JSDoc](http://suguru03.github.io/neo-async/doc/async.html) + +\* not in Async + +### Collections + +- [`each`](http://suguru03.github.io/neo-async/doc/async.each.html) +- [`eachSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) +- [`eachLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) +- [`forEach`](http://suguru03.github.io/neo-async/doc/async.each.html) -> [`each`](http://suguru03.github.io/neo-async/doc/async.each.html) +- [`forEachSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) -> [`eachSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) +- [`forEachLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) -> [`eachLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) +- [`eachOf`](http://suguru03.github.io/neo-async/doc/async.each.html) -> [`each`](http://suguru03.github.io/neo-async/doc/async.each.html) +- [`eachOfSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) -> [`eachSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) +- [`eachOfLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) -> [`eachLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) +- [`forEachOf`](http://suguru03.github.io/neo-async/doc/async.each.html) -> [`each`](http://suguru03.github.io/neo-async/doc/async.each.html) +- [`forEachOfSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) -> [`eachSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) +- [`eachOfLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) -> [`forEachLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) +- [`map`](http://suguru03.github.io/neo-async/doc/async.map.html) +- [`mapSeries`](http://suguru03.github.io/neo-async/doc/async.mapSeries.html) +- [`mapLimit`](http://suguru03.github.io/neo-async/doc/async.mapLimit.html) +- [`mapValues`](http://suguru03.github.io/neo-async/doc/async.mapValues.html) +- [`mapValuesSeries`](http://suguru03.github.io/neo-async/doc/async.mapValuesSeries.html) +- [`mapValuesLimit`](http://suguru03.github.io/neo-async/doc/async.mapValuesLimit.html) +- [`filter`](http://suguru03.github.io/neo-async/doc/async.filter.html) +- [`filterSeries`](http://suguru03.github.io/neo-async/doc/async.filterSeries.html) +- [`filterLimit`](http://suguru03.github.io/neo-async/doc/async.filterLimit.html) +- [`select`](http://suguru03.github.io/neo-async/doc/async.filter.html) -> [`filter`](http://suguru03.github.io/neo-async/doc/async.filter.html) +- [`selectSeries`](http://suguru03.github.io/neo-async/doc/async.filterSeries.html) -> [`filterSeries`](http://suguru03.github.io/neo-async/doc/async.filterSeries.html) +- [`selectLimit`](http://suguru03.github.io/neo-async/doc/async.filterLimit.html) -> [`filterLimit`](http://suguru03.github.io/neo-async/doc/async.filterLimit.html) +- [`reject`](http://suguru03.github.io/neo-async/doc/async.reject.html) +- [`rejectSeries`](http://suguru03.github.io/neo-async/doc/async.rejectSeries.html) +- [`rejectLimit`](http://suguru03.github.io/neo-async/doc/async.rejectLimit.html) +- [`detect`](http://suguru03.github.io/neo-async/doc/async.detect.html) +- [`detectSeries`](http://suguru03.github.io/neo-async/doc/async.detectSeries.html) +- [`detectLimit`](http://suguru03.github.io/neo-async/doc/async.detectLimit.html) +- [`find`](http://suguru03.github.io/neo-async/doc/async.detect.html) -> [`detect`](http://suguru03.github.io/neo-async/doc/async.detect.html) +- [`findSeries`](http://suguru03.github.io/neo-async/doc/async.detectSeries.html) -> [`detectSeries`](http://suguru03.github.io/neo-async/doc/async.detectSeries.html) +- [`findLimit`](http://suguru03.github.io/neo-async/doc/async.detectLimit.html) -> [`detectLimit`](http://suguru03.github.io/neo-async/doc/async.detectLimit.html) +- [`pick`](http://suguru03.github.io/neo-async/doc/async.pick.html) * +- [`pickSeries`](http://suguru03.github.io/neo-async/doc/async.pickSeries.html) * +- [`pickLimit`](http://suguru03.github.io/neo-async/doc/async.pickLimit.html) * +- [`omit`](http://suguru03.github.io/neo-async/doc/async.omit.html) * +- [`omitSeries`](http://suguru03.github.io/neo-async/doc/async.omitSeries.html) * +- [`omitLimit`](http://suguru03.github.io/neo-async/doc/async.omitLimit.html) * +- [`reduce`](http://suguru03.github.io/neo-async/doc/async.reduce.html) +- [`inject`](http://suguru03.github.io/neo-async/doc/async.reduce.html) -> [`reduce`](http://suguru03.github.io/neo-async/doc/async.reduce.html) +- [`foldl`](http://suguru03.github.io/neo-async/doc/async.reduce.html) -> [`reduce`](http://suguru03.github.io/neo-async/doc/async.reduce.html) +- [`reduceRight`](http://suguru03.github.io/neo-async/doc/async.reduceRight.html) +- [`foldr`](http://suguru03.github.io/neo-async/doc/async.reduceRight.html) -> [`reduceRight`](http://suguru03.github.io/neo-async/doc/async.reduceRight.html) +- [`transform`](http://suguru03.github.io/neo-async/doc/async.transform.html) +- [`transformSeries`](http://suguru03.github.io/neo-async/doc/async.transformSeries.html) * +- [`transformLimit`](http://suguru03.github.io/neo-async/doc/async.transformLimit.html) * +- [`sortBy`](http://suguru03.github.io/neo-async/doc/async.sortBy.html) +- [`sortBySeries`](http://suguru03.github.io/neo-async/doc/async.sortBySeries.html) * +- [`sortByLimit`](http://suguru03.github.io/neo-async/doc/async.sortByLimit.html) * +- [`some`](http://suguru03.github.io/neo-async/doc/async.some.html) +- [`someSeries`](http://suguru03.github.io/neo-async/doc/async.someSeries.html) +- [`someLimit`](http://suguru03.github.io/neo-async/doc/async.someLimit.html) +- [`any`](http://suguru03.github.io/neo-async/doc/async.some.html) -> [`some`](http://suguru03.github.io/neo-async/doc/async.some.html) +- [`anySeries`](http://suguru03.github.io/neo-async/doc/async.someSeries.html) -> [`someSeries`](http://suguru03.github.io/neo-async/doc/async.someSeries.html) +- [`anyLimit`](http://suguru03.github.io/neo-async/doc/async.someLimit.html) -> [`someLimit`](http://suguru03.github.io/neo-async/doc/async.someLimit.html) +- [`every`](http://suguru03.github.io/neo-async/doc/async.every.html) +- [`everySeries`](http://suguru03.github.io/neo-async/doc/async.everySeries.html) +- [`everyLimit`](http://suguru03.github.io/neo-async/doc/async.everyLimit.html) +- [`all`](http://suguru03.github.io/neo-async/doc/async.every.html) -> [`every`](http://suguru03.github.io/neo-async/doc/async.every.html) +- [`allSeries`](http://suguru03.github.io/neo-async/doc/async.everySeries.html) -> [`every`](http://suguru03.github.io/neo-async/doc/async.everySeries.html) +- [`allLimit`](http://suguru03.github.io/neo-async/doc/async.everyLimit.html) -> [`every`](http://suguru03.github.io/neo-async/doc/async.everyLimit.html) +- [`concat`](http://suguru03.github.io/neo-async/doc/async.concat.html) +- [`concatSeries`](http://suguru03.github.io/neo-async/doc/async.concatSeries.html) +- [`concatLimit`](http://suguru03.github.io/neo-async/doc/async.concatLimit.html) * + +### Control Flow + +- [`parallel`](http://suguru03.github.io/neo-async/doc/async.parallel.html) +- [`series`](http://suguru03.github.io/neo-async/doc/async.series.html) +- [`parallelLimit`](http://suguru03.github.io/neo-async/doc/async.series.html) +- [`tryEach`](http://suguru03.github.io/neo-async/doc/async.tryEach.html) +- [`waterfall`](http://suguru03.github.io/neo-async/doc/async.waterfall.html) +- [`angelFall`](http://suguru03.github.io/neo-async/doc/async.angelFall.html) * +- [`angelfall`](http://suguru03.github.io/neo-async/doc/async.angelFall.html) -> [`angelFall`](http://suguru03.github.io/neo-async/doc/async.angelFall.html) * +- [`whilst`](#whilst) +- [`doWhilst`](#doWhilst) +- [`until`](#until) +- [`doUntil`](#doUntil) +- [`during`](#during) +- [`doDuring`](#doDuring) +- [`forever`](#forever) +- [`compose`](#compose) +- [`seq`](#seq) +- [`applyEach`](#applyEach) +- [`applyEachSeries`](#applyEachSeries) +- [`queue`](#queue) +- [`priorityQueue`](#priorityQueue) +- [`cargo`](#cargo) +- [`auto`](#auto) +- [`autoInject`](#autoInject) +- [`retry`](#retry) +- [`retryable`](#retryable) +- [`iterator`](#iterator) +- [`times`](http://suguru03.github.io/neo-async/doc/async.times.html) +- [`timesSeries`](http://suguru03.github.io/neo-async/doc/async.timesSeries.html) +- [`timesLimit`](http://suguru03.github.io/neo-async/doc/async.timesLimit.html) +- [`race`](#race) + +### Utils +- [`apply`](#apply) +- [`setImmediate`](#setImmediate) +- [`nextTick`](#nextTick) +- [`memoize`](#memoize) +- [`unmemoize`](#unmemoize) +- [`ensureAsync`](#ensureAsync) +- [`constant`](#constant) +- [`asyncify`](#asyncify) +- [`wrapSync`](#asyncify) -> [`asyncify`](#asyncify) +- [`log`](#log) +- [`dir`](#dir) +- [`timeout`](http://suguru03.github.io/neo-async/doc/async.timeout.html) +- [`reflect`](#reflect) +- [`reflectAll`](#reflectAll) +- [`createLogger`](#createLogger) + +## Mode +- [`safe`](#safe) * +- [`fast`](#fast) * + +## Benchmark + +[Benchmark: Async vs Neo-Async](http://suguru03.hatenablog.com/entry/2016/06/10/135559) + +### How to check + +```bash +$ node perf +``` + +### Environment + +* Darwin 17.3.0 x64 +* Node.js v8.9.4 +* async v2.6.0 +* neo-async v2.5.0 +* benchmark v2.1.4 + +### Result + +The value is the ratio (Neo-Async/Async) of the average speed. + +#### Collections +|function|benchmark| +|---|--:| +|each/forEach|2.43| +|eachSeries/forEachSeries|1.75| +|eachLimit/forEachLimit|1.68| +|eachOf|3.29| +|eachOfSeries|1.50| +|eachOfLimit|1.59| +|map|3.95| +|mapSeries|1.81| +|mapLimit|1.27| +|mapValues|2.73| +|mapValuesSeries|1.59| +|mapValuesLimit|1.23| +|filter|3.00| +|filterSeries|1.74| +|filterLimit|1.17| +|reject|4.59| +|rejectSeries|2.31| +|rejectLimit|1.58| +|detect|4.30| +|detectSeries|1.86| +|detectLimit|1.32| +|reduce|1.82| +|transform|2.46| +|sortBy|4.08| +|some|2.19| +|someSeries|1.83| +|someLimit|1.32| +|every|2.09| +|everySeries|1.84| +|everyLimit|1.35| +|concat|3.79| +|concatSeries|4.45| + +#### Control Flow +|funciton|benchmark| +|---|--:| +|parallel|2.93| +|series|1.96| +|waterfall|1.29| +|whilst|1.00| +|doWhilst|1.12| +|until|1.12| +|doUntil|1.12| +|during|1.18| +|doDuring|2.42| +|times|4.25| +|auto|1.97| + + +## License +[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fsuguru03%2Fneo-async.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fsuguru03%2Fneo-async?ref=badge_large) diff --git a/node_modules/neo-async/all.js b/node_modules/neo-async/all.js new file mode 100644 index 0000000..dad54e7 --- /dev/null +++ b/node_modules/neo-async/all.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./async').all; diff --git a/node_modules/neo-async/allLimit.js b/node_modules/neo-async/allLimit.js new file mode 100644 index 0000000..d9d7aaa --- /dev/null +++ b/node_modules/neo-async/allLimit.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./async').allLimit; diff --git a/node_modules/neo-async/allSeries.js b/node_modules/neo-async/allSeries.js new file mode 100644 index 0000000..2a7a8ba --- /dev/null +++ b/node_modules/neo-async/allSeries.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./async').allSeries; diff --git a/node_modules/neo-async/angelFall.js b/node_modules/neo-async/angelFall.js new file mode 100644 index 0000000..476c23e --- /dev/null +++ b/node_modules/neo-async/angelFall.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./async').angelfall; diff --git a/node_modules/neo-async/any.js b/node_modules/neo-async/any.js new file mode 100644 index 0000000..d6b07bb --- /dev/null +++ b/node_modules/neo-async/any.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./async').any; diff --git a/node_modules/neo-async/anyLimit.js b/node_modules/neo-async/anyLimit.js new file mode 100644 index 0000000..34114f8 --- /dev/null +++ b/node_modules/neo-async/anyLimit.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./async').anyLimit; diff --git a/node_modules/neo-async/anySeries.js b/node_modules/neo-async/anySeries.js new file mode 100644 index 0000000..bb3781f --- /dev/null +++ b/node_modules/neo-async/anySeries.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./async').anySeries; diff --git a/node_modules/neo-async/apply.js b/node_modules/neo-async/apply.js new file mode 100644 index 0000000..41135e2 --- /dev/null +++ b/node_modules/neo-async/apply.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./async').apply; diff --git a/node_modules/neo-async/applyEach.js b/node_modules/neo-async/applyEach.js new file mode 100644 index 0000000..292bd1c --- /dev/null +++ b/node_modules/neo-async/applyEach.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./async').applyEach; diff --git a/node_modules/neo-async/applyEachSeries.js b/node_modules/neo-async/applyEachSeries.js new file mode 100644 index 0000000..0aece7c --- /dev/null +++ b/node_modules/neo-async/applyEachSeries.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./async').applyEachSeries; diff --git a/node_modules/neo-async/async.js b/node_modules/neo-async/async.js new file mode 100644 index 0000000..e78eb16 --- /dev/null +++ b/node_modules/neo-async/async.js @@ -0,0 +1,9184 @@ +(function(global, factory) { + /*jshint -W030 */ + 'use strict'; + typeof exports === 'object' && typeof module !== 'undefined' + ? factory(exports) + : typeof define === 'function' && define.amd + ? define(['exports'], factory) + : global.async + ? factory((global.neo_async = global.neo_async || {})) + : factory((global.async = global.async || {})); +})(this, function(exports) { + 'use strict'; + + var noop = function noop() {}; + var throwError = function throwError() { + throw new Error('Callback was already called.'); + }; + + var DEFAULT_TIMES = 5; + var DEFAULT_INTERVAL = 0; + + var obj = 'object'; + var func = 'function'; + var isArray = Array.isArray; + var nativeKeys = Object.keys; + var nativePush = Array.prototype.push; + var iteratorSymbol = typeof Symbol === func && Symbol.iterator; + + var nextTick, asyncNextTick, asyncSetImmediate; + createImmediate(); + + /** + * @memberof async + * @namespace each + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(); + * }, num * 10); + * }; + * async.each(array, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(); + * }, num * 10); + * }; + * async.each(array, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [[1, 0], [2, 2], [3, 1]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(); + * }, num * 10); + * }; + * async.each(object, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(); + * }, num * 10); + * }; + * async.each(object, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b']] + * }); + * + * @example + * + * // break + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num !== 2); + * }, num * 10); + * }; + * async.each(array, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [1, 2] + * }); + * + */ + var each = createEach(arrayEach, baseEach, symbolEach); + + /** + * @memberof async + * @namespace map + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.map(array, iterator, function(err, res) { + * console.log(res); // [1, 3, 2]; + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num); + * }, num * 10); + * }; + * async.map(array, iterator, function(err, res) { + * console.log(res); // [1, 3, 2] + * console.log(order); // [[1, 0], [2, 2], [3, 1]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.map(object, iterator, function(err, res) { + * console.log(res); // [1, 3, 2] + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num); + * }, num * 10); + * }; + * async.map(object, iterator, function(err, res) { + * console.log(res); // [1, 3, 2] + * console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b']] + * }); + * + */ + var map = createMap(arrayEachIndex, baseEachIndex, symbolEachIndex, true); + + /** + * @memberof async + * @namespace mapValues + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.mapValues(array, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 3, '2': 2 } + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num); + * }, num * 10); + * }; + * async.mapValues(array, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 3, '2': 2 } + * console.log(order); // [[1, 0], [2, 2], [3, 1]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.mapValues(object, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 3, c: 2 } + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num); + * }, num * 10); + * }; + * async.mapValues(object, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 3, c: 2 } + * console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b']] + * }); + * + */ + var mapValues = createMap(arrayEachIndex, baseEachKey, symbolEachKey, false); + + /** + * @memberof async + * @namespace filter + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filter(array, iterator, function(err, res) { + * console.log(res); // [1, 3]; + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filter(array, iterator, function(err, res) { + * console.log(res); // [1, 3]; + * console.log(order); // [[1, 0], [2, 2], [3, 1]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filter(object, iterator, function(err, res) { + * console.log(res); // [1, 3]; + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filter(object, iterator, function(err, res) { + * console.log(res); // [1, 3]; + * console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b']] + * }); + * + */ + var filter = createFilter(arrayEachIndexValue, baseEachIndexValue, symbolEachIndexValue, true); + + /** + * @memberof async + * @namespace filterSeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filterSeries(array, iterator, function(err, res) { + * console.log(res); // [1, 3]; + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filterSeries(array, iterator, function(err, res) { + * console.log(res); // [1, 3] + * console.log(order); // [[1, 0], [3, 1], [2, 2]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filterSeries(object, iterator, function(err, res) { + * console.log(res); // [1, 3] + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filterSeries(object, iterator, function(err, res) { + * console.log(res); // [1, 3] + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'c']] + * }); + * + */ + var filterSeries = createFilterSeries(true); + + /** + * @memberof async + * @namespace filterLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filterLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [1, 5, 3] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filterLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [1, 5, 3] + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filterLimit(object, 2, iterator, function(err, res) { + * console.log(res); // [1, 5, 3] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.filterLimit(object, 2, iterator, function(err, res) { + * console.log(res); // [1, 5, 3] + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e'], [4, 'd']] + * }); + * + */ + var filterLimit = createFilterLimit(true); + + /** + * @memberof async + * @namespace reject + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.reject(array, iterator, function(err, res) { + * console.log(res); // [2]; + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.reject(array, iterator, function(err, res) { + * console.log(res); // [2]; + * console.log(order); // [[1, 0], [2, 2], [3, 1]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.reject(object, iterator, function(err, res) { + * console.log(res); // [2]; + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.reject(object, iterator, function(err, res) { + * console.log(res); // [2]; + * console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b']] + * }); + * + */ + var reject = createFilter(arrayEachIndexValue, baseEachIndexValue, symbolEachIndexValue, false); + + /** + * @memberof async + * @namespace rejectSeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.rejectSeries(array, iterator, function(err, res) { + * console.log(res); // [2]; + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.rejectSeries(object, iterator, function(err, res) { + * console.log(res); // [2]; + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.rejectSeries(object, iterator, function(err, res) { + * console.log(res); // [2]; + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'c']] + * }); + * + */ + var rejectSeries = createFilterSeries(false); + + /** + * @memberof async + * @namespace rejectLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.rejectLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [4, 2] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.rejectLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [4, 2] + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.rejectLimit(object, 2, iterator, function(err, res) { + * console.log(res); // [4, 2] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.rejectLimit(object, 2, iterator, function(err, res) { + * console.log(res); // [4, 2] + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e'], [4, 'd']] + * }); + * + */ + var rejectLimit = createFilterLimit(false); + + /** + * @memberof async + * @namespace detect + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detect(array, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [1] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detect(array, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [[1, 0]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detect(object, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [1] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detect(object, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [[1, 'a']] + * }); + * + */ + var detect = createDetect(arrayEachValue, baseEachValue, symbolEachValue, true); + + /** + * @memberof async + * @namespace detectSeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detectSeries(array, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [1] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detectSeries(array, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [[1, 0]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detectSeries(object, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [1] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detectSeries(object, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [[1, 'a']] + * }); + * + */ + var detectSeries = createDetectSeries(true); + + /** + * @memberof async + * @namespace detectLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detectLimit(array, 2, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [1] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detectLimit(array, 2, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [[1, 0]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detectLimit(object, 2, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [1] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.detectLimit(object, 2, iterator, function(err, res) { + * console.log(res); // 1 + * console.log(order); // [[1, 'a']] + * }); + * + */ + var detectLimit = createDetectLimit(true); + + /** + * @memberof async + * @namespace every + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.every(array, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [1, 2] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.every(array, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [[1, 0], [2, 2]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.every(object, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [1, 2] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.every(object, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [[1, 'a'], [2, 'c']] + * }); + * + */ + var every = createEvery(arrayEachValue, baseEachValue, symbolEachValue); + + /** + * @memberof async + * @namespace everySeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.everySeries(array, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.everySeries(array, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [[1, 0], [3, 1], [2, 2]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.everySeries(object, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.everySeries(object, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [[1, 'a'], [3, 'b'] [2, 'c']] + * }); + * + */ + var everySeries = createEverySeries(); + + /** + * @memberof async + * @namespace everyLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.everyLimit(array, 2, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [1, 3, 5, 2] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.everyLimit(array, 2, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.everyLimit(object, 2, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [1, 3, 5, 2] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.everyLimit(object, 2, iterator, function(err, res) { + * console.log(res); // false + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e']] + * }); + * + */ + var everyLimit = createEveryLimit(); + + /** + * @memberof async + * @namespace pick + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2, 4]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pick(array, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 3 } + * console.log(order); // [1, 2, 3, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2, 4]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pick(array, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 3 } + * console.log(order); // [[0, 1], [2, 2], [3, 1], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pick(object, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 3 } + * console.log(order); // [1, 2, 3, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pick(object, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 3 } + * console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b'], [4, 'd']] + * }); + * + */ + var pick = createPick(arrayEachIndexValue, baseEachKeyValue, symbolEachKeyValue, true); + + /** + * @memberof async + * @namespace pickSeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2, 4]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pickSeries(array, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 3 } + * console.log(order); // [1, 3, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2, 4]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pickSeries(array, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 3 } + * console.log(order); // [[0, 1], [3, 1], [2, 2], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pickSeries(object, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 3 } + * console.log(order); // [1, 3, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pickSeries(object, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 3 } + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'c'], [4, 'd']] + * }); + * + */ + var pickSeries = createPickSeries(true); + + /** + * @memberof async + * @namespace pickLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pickLimit(array, 2, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 5, '2': 3 } + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pickLimit(array, 2, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 5, '2': 3 } + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pickLimit(object, 2, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 5, c: 3 } + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.pickLimit(object, 2, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 5, c: 3 } + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e'], [4, 'd']] + * }); + * + */ + var pickLimit = createPickLimit(true); + + /** + * @memberof async + * @namespace omit + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2, 4]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omit(array, iterator, function(err, res) { + * console.log(res); // { '2': 2, '3': 4 } + * console.log(order); // [1, 2, 3, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2, 4]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omit(array, iterator, function(err, res) { + * console.log(res); // { '2': 2, '3': 4 } + * console.log(order); // [[0, 1], [2, 2], [3, 1], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omit(object, iterator, function(err, res) { + * console.log(res); // { c: 2, d: 4 } + * console.log(order); // [1, 2, 3, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omit(object, iterator, function(err, res) { + * console.log(res); // { c: 2, d: 4 } + * console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b'], [4, 'd']] + * }); + * + */ + var omit = createPick(arrayEachIndexValue, baseEachKeyValue, symbolEachKeyValue, false); + + /** + * @memberof async + * @namespace omitSeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2, 4]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omitSeries(array, iterator, function(err, res) { + * console.log(res); // { '2': 2, '3': 4 } + * console.log(order); // [1, 3, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2, 4]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omitSeries(array, iterator, function(err, res) { + * console.log(res); // { '2': 2, '3': 4 } + * console.log(order); // [[0, 1], [3, 1], [2, 2], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omitSeries(object, iterator, function(err, res) { + * console.log(res); // { c: 2, d: 4 } + * console.log(order); // [1, 3, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omitSeries(object, iterator, function(err, res) { + * console.log(res); // { c: 2, d: 4 } + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'c'], [4, 'd']] + * }); + * + */ + var omitSeries = createPickSeries(false); + + /** + * @memberof async + * @namespace omitLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omitLimit(array, 2, iterator, function(err, res) { + * console.log(res); // { '3': 4, '4': 2 } + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omitLimit(array, 2, iterator, function(err, res) { + * console.log(res); // { '3': 4, '4': 2 } + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omitLimit(object, 2, iterator, function(err, res) { + * console.log(res); // { d: 4, e: 2 } + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.omitLimit(object, 2, iterator, function(err, res) { + * console.log(res); // { d: 4, e: 2 } + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e'], [4, 'd']] + * }); + * + */ + var omitLimit = createPickLimit(false); + + /** + * @memberof async + * @namespace transform + * @param {Array|Object} collection + * @param {Array|Object|Function} [accumulator] + * @param {Function} [iterator] + * @param {Function} [callback] + * @example + * + * // array + * var order = []; + * var collection = [1, 3, 2, 4]; + * var iterator = function(result, num, done) { + * setTimeout(function() { + * order.push(num); + * result.push(num) + * done(); + * }, num * 10); + * }; + * async.transform(collection, iterator, function(err, res) { + * console.log(res); // [1, 2, 3, 4] + * console.log(order); // [1, 2, 3, 4] + * }); + * + * @example + * + * // array with index and accumulator + * var order = []; + * var collection = [1, 3, 2, 4]; + * var iterator = function(result, num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * result[index] = num; + * done(); + * }, num * 10); + * }; + * async.transform(collection, {}, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 3, '2': 2, '3': 4 } + * console.log(order); // [[1, 0], [2, 2], [3, 1], [4, 3]] + * }); + * + * @example + * + * // object with accumulator + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(result, num, done) { + * setTimeout(function() { + * order.push(num); + * result.push(num); + * done(); + * }, num * 10); + * }; + * async.transform(collection, [], iterator, function(err, res) { + * console.log(res); // [1, 2, 3, 4] + * console.log(order); // [1, 2, 3, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(result, num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * result[key] = num; + * done(); + * }, num * 10); + * }; + * async.transform(collection, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 3, c: 2, d: 4 } + * console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b'], [4, 'd']] + * }); + * + */ + var transform = createTransform(arrayEachResult, baseEachResult, symbolEachResult); + + /** + * @memberof async + * @namespace sortBy + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.sortBy(array, iterator, function(err, res) { + * console.log(res); // [1, 2, 3]; + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num); + * }, num * 10); + * }; + * async.sortBy(array, iterator, function(err, res) { + * console.log(res); // [1, 2, 3] + * console.log(order); // [[1, 0], [2, 2], [3, 1]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.sortBy(object, iterator, function(err, res) { + * console.log(res); // [1, 2, 3] + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num); + * }, num * 10); + * }; + * async.sortBy(object, iterator, function(err, res) { + * console.log(res); // [1, 2, 3] + * console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b']] + * }); + * + */ + var sortBy = createSortBy(arrayEachIndexValue, baseEachIndexValue, symbolEachIndexValue); + + /** + * @memberof async + * @namespace concat + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, [num]); + * }, num * 10); + * }; + * async.concat(array, iterator, function(err, res) { + * console.log(res); // [1, 2, 3]; + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, [num]); + * }, num * 10); + * }; + * async.concat(array, iterator, function(err, res) { + * console.log(res); // [1, 2, 3] + * console.log(order); // [[1, 0], [2, 2], [3, 1]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, [num]); + * }, num * 10); + * }; + * async.concat(object, iterator, function(err, res) { + * console.log(res); // [1, 2, 3] + * console.log(order); // [1, 2, 3] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, [num]); + * }, num * 10); + * }; + * async.concat(object, iterator, function(err, res) { + * console.log(res); // [1, 2, 3] + * console.log(order); // [[1, 'a'], [2, 'c'], [3, 'b']] + * }); + * + */ + var concat = createConcat(arrayEachIndex, baseEachIndex, symbolEachIndex); + + /** + * @memberof async + * @namespace groupBy + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [4.2, 6.4, 6.1]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupBy(array, iterator, function(err, res) { + * console.log(res); // { '4': [4.2], '6': [6.1, 6.4] } + * console.log(order); // [4.2, 6.1, 6.4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [4.2, 6.4, 6.1]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupBy(array, iterator, function(err, res) { + * console.log(res); // { '4': [4.2], '6': [6.1, 6.4] } + * console.log(order); // [[4.2, 0], [6.1, 2], [6.4, 1]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 4.2, b: 6.4, c: 6.1 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupBy(object, iterator, function(err, res) { + * console.log(res); // { '4': [4.2], '6': [6.1, 6.4] } + * console.log(order); // [4.2, 6.1, 6.4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 4.2, b: 6.4, c: 6.1 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupBy(object, iterator, function(err, res) { + * console.log(res); // { '4': [4.2], '6': [6.1, 6.4] } + * console.log(order); // [[4.2, 'a'], [6.1, 'c'], [6.4, 'b']] + * }); + * + */ + var groupBy = createGroupBy(arrayEachValue, baseEachValue, symbolEachValue); + + /** + * @memberof async + * @namespace parallel + * @param {Array|Object} tasks - functions + * @param {Function} callback + * @example + * + * var order = []; + * var tasks = [ + * function(done) { + * setTimeout(function() { + * order.push(1); + * done(null, 1); + * }, 10); + * }, + * function(done) { + * setTimeout(function() { + * order.push(2); + * done(null, 2); + * }, 30); + * }, + * function(done) { + * setTimeout(function() { + * order.push(3); + * done(null, 3); + * }, 40); + * }, + * function(done) { + * setTimeout(function() { + * order.push(4); + * done(null, 4); + * }, 20); + * } + * ]; + * async.parallel(tasks, function(err, res) { + * console.log(res); // [1, 2, 3, 4]; + * console.log(order); // [1, 4, 2, 3] + * }); + * + * @example + * + * var order = []; + * var tasks = { + * 'a': function(done) { + * setTimeout(function() { + * order.push(1); + * done(null, 1); + * }, 10); + * }, + * 'b': function(done) { + * setTimeout(function() { + * order.push(2); + * done(null, 2); + * }, 30); + * }, + * 'c': function(done) { + * setTimeout(function() { + * order.push(3); + * done(null, 3); + * }, 40); + * }, + * 'd': function(done) { + * setTimeout(function() { + * order.push(4); + * done(null, 4); + * }, 20); + * } + * }; + * async.parallel(tasks, function(err, res) { + * console.log(res); // { a: 1, b: 2, c: 3, d:4 } + * console.log(order); // [1, 4, 2, 3] + * }); + * + */ + var parallel = createParallel(arrayEachFunc, baseEachFunc); + + /** + * @memberof async + * @namespace applyEach + */ + var applyEach = createApplyEach(map); + + /** + * @memberof async + * @namespace applyEachSeries + */ + var applyEachSeries = createApplyEach(mapSeries); + + /** + * @memberof async + * @namespace log + */ + var log = createLogger('log'); + + /** + * @memberof async + * @namespace dir + */ + var dir = createLogger('dir'); + + /** + * @version 2.6.2 + * @namespace async + */ + var index = { + VERSION: '2.6.2', + + // Collections + each: each, + eachSeries: eachSeries, + eachLimit: eachLimit, + forEach: each, + forEachSeries: eachSeries, + forEachLimit: eachLimit, + eachOf: each, + eachOfSeries: eachSeries, + eachOfLimit: eachLimit, + forEachOf: each, + forEachOfSeries: eachSeries, + forEachOfLimit: eachLimit, + map: map, + mapSeries: mapSeries, + mapLimit: mapLimit, + mapValues: mapValues, + mapValuesSeries: mapValuesSeries, + mapValuesLimit: mapValuesLimit, + filter: filter, + filterSeries: filterSeries, + filterLimit: filterLimit, + select: filter, + selectSeries: filterSeries, + selectLimit: filterLimit, + reject: reject, + rejectSeries: rejectSeries, + rejectLimit: rejectLimit, + detect: detect, + detectSeries: detectSeries, + detectLimit: detectLimit, + find: detect, + findSeries: detectSeries, + findLimit: detectLimit, + pick: pick, + pickSeries: pickSeries, + pickLimit: pickLimit, + omit: omit, + omitSeries: omitSeries, + omitLimit: omitLimit, + reduce: reduce, + inject: reduce, + foldl: reduce, + reduceRight: reduceRight, + foldr: reduceRight, + transform: transform, + transformSeries: transformSeries, + transformLimit: transformLimit, + sortBy: sortBy, + sortBySeries: sortBySeries, + sortByLimit: sortByLimit, + some: some, + someSeries: someSeries, + someLimit: someLimit, + any: some, + anySeries: someSeries, + anyLimit: someLimit, + every: every, + everySeries: everySeries, + everyLimit: everyLimit, + all: every, + allSeries: everySeries, + allLimit: everyLimit, + concat: concat, + concatSeries: concatSeries, + concatLimit: concatLimit, + groupBy: groupBy, + groupBySeries: groupBySeries, + groupByLimit: groupByLimit, + + // Control Flow + parallel: parallel, + series: series, + parallelLimit: parallelLimit, + tryEach: tryEach, + waterfall: waterfall, + angelFall: angelFall, + angelfall: angelFall, + whilst: whilst, + doWhilst: doWhilst, + until: until, + doUntil: doUntil, + during: during, + doDuring: doDuring, + forever: forever, + compose: compose, + seq: seq, + applyEach: applyEach, + applyEachSeries: applyEachSeries, + queue: queue, + priorityQueue: priorityQueue, + cargo: cargo, + auto: auto, + autoInject: autoInject, + retry: retry, + retryable: retryable, + iterator: iterator, + times: times, + timesSeries: timesSeries, + timesLimit: timesLimit, + race: race, + + // Utils + apply: apply, + nextTick: asyncNextTick, + setImmediate: asyncSetImmediate, + memoize: memoize, + unmemoize: unmemoize, + ensureAsync: ensureAsync, + constant: constant, + asyncify: asyncify, + wrapSync: asyncify, + log: log, + dir: dir, + reflect: reflect, + reflectAll: reflectAll, + timeout: timeout, + createLogger: createLogger, + + // Mode + safe: safe, + fast: fast + }; + + exports['default'] = index; + baseEachSync( + index, + function(func, key) { + exports[key] = func; + }, + nativeKeys(index) + ); + + /** + * @private + */ + function createImmediate(safeMode) { + var delay = function delay(fn) { + var args = slice(arguments, 1); + setTimeout(function() { + fn.apply(null, args); + }); + }; + asyncSetImmediate = typeof setImmediate === func ? setImmediate : delay; + if (typeof process === obj && typeof process.nextTick === func) { + nextTick = /^v0.10/.test(process.version) ? asyncSetImmediate : process.nextTick; + asyncNextTick = /^v0/.test(process.version) ? asyncSetImmediate : process.nextTick; + } else { + asyncNextTick = nextTick = asyncSetImmediate; + } + if (safeMode === false) { + nextTick = function(cb) { + cb(); + }; + } + } + + /* sync functions based on lodash */ + + /** + * Converts `arguments` to an array. + * + * @private + * @param {Array} array = The array to slice. + */ + function createArray(array) { + var index = -1; + var size = array.length; + var result = Array(size); + + while (++index < size) { + result[index] = array[index]; + } + return result; + } + + /** + * Create an array from `start` + * + * @private + * @param {Array} array - The array to slice. + * @param {number} start - The start position. + */ + function slice(array, start) { + var end = array.length; + var index = -1; + var size = end - start; + if (size <= 0) { + return []; + } + var result = Array(size); + + while (++index < size) { + result[index] = array[index + start]; + } + return result; + } + + /** + * @private + * @param {Object} object + */ + function objectClone(object) { + var keys = nativeKeys(object); + var size = keys.length; + var index = -1; + var result = {}; + + while (++index < size) { + var key = keys[index]; + result[key] = object[key]; + } + return result; + } + + /** + * Create an array with all falsey values removed. + * + * @private + * @param {Array} array - The array to compact. + */ + function compact(array) { + var index = -1; + var size = array.length; + var result = []; + + while (++index < size) { + var value = array[index]; + if (value) { + result[result.length] = value; + } + } + return result; + } + + /** + * Create an array of reverse sequence. + * + * @private + * @param {Array} array - The array to reverse. + */ + function reverse(array) { + var index = -1; + var size = array.length; + var result = Array(size); + var resIndex = size; + + while (++index < size) { + result[--resIndex] = array[index]; + } + return result; + } + + /** + * Checks if key exists in object property. + * + * @private + * @param {Object} object - The object to inspect. + * @param {string} key - The key to check. + */ + function has(object, key) { + return object.hasOwnProperty(key); + } + + /** + * Check if target exists in array. + * @private + * @param {Array} array + * @param {*} target + */ + function notInclude(array, target) { + var index = -1; + var size = array.length; + + while (++index < size) { + if (array[index] === target) { + return false; + } + } + return true; + } + + /** + * @private + * @param {Array} array - The array to iterate over. + * @param {Function} iterator - The function invoked per iteration. + */ + function arrayEachSync(array, iterator) { + var index = -1; + var size = array.length; + + while (++index < size) { + iterator(array[index], index); + } + return array; + } + + /** + * @private + * @param {Object} object - The object to iterate over. + * @param {Function} iterator - The function invoked per iteration. + * @param {Array} keys + */ + function baseEachSync(object, iterator, keys) { + var index = -1; + var size = keys.length; + + while (++index < size) { + var key = keys[index]; + iterator(object[key], key); + } + return object; + } + + /** + * @private + * @param {number} n + * @param {Function} iterator + */ + function timesSync(n, iterator) { + var index = -1; + while (++index < n) { + iterator(index); + } + } + + /** + * @private + * @param {Array} array + * @param {number[]} criteria + */ + function sortByCriteria(array, criteria) { + var l = array.length; + var indices = Array(l); + var i; + for (i = 0; i < l; i++) { + indices[i] = i; + } + quickSort(criteria, 0, l - 1, indices); + var result = Array(l); + for (var n = 0; n < l; n++) { + i = indices[n]; + result[n] = i === undefined ? array[n] : array[i]; + } + return result; + } + + function partition(array, i, j, mid, indices) { + var l = i; + var r = j; + while (l <= r) { + i = l; + while (l < r && array[l] < mid) { + l++; + } + while (r >= i && array[r] >= mid) { + r--; + } + if (l > r) { + break; + } + swap(array, indices, l++, r--); + } + return l; + } + + function swap(array, indices, l, r) { + var n = array[l]; + array[l] = array[r]; + array[r] = n; + var i = indices[l]; + indices[l] = indices[r]; + indices[r] = i; + } + + function quickSort(array, i, j, indices) { + if (i === j) { + return; + } + var k = i; + while (++k <= j && array[i] === array[k]) { + var l = k - 1; + if (indices[l] > indices[k]) { + var index = indices[l]; + indices[l] = indices[k]; + indices[k] = index; + } + } + if (k > j) { + return; + } + var p = array[i] > array[k] ? i : k; + k = partition(array, i, j, array[p], indices); + quickSort(array, i, k - 1, indices); + quickSort(array, k, j, indices); + } + + /** + * @Private + */ + function makeConcatResult(array) { + var result = []; + arrayEachSync(array, function(value) { + if (value === noop) { + return; + } + if (isArray(value)) { + nativePush.apply(result, value); + } else { + result.push(value); + } + }); + return result; + } + + /* async functions */ + + /** + * @private + */ + function arrayEach(array, iterator, callback) { + var index = -1; + var size = array.length; + + if (iterator.length === 3) { + while (++index < size) { + iterator(array[index], index, onlyOnce(callback)); + } + } else { + while (++index < size) { + iterator(array[index], onlyOnce(callback)); + } + } + } + + /** + * @private + */ + function baseEach(object, iterator, callback, keys) { + var key; + var index = -1; + var size = keys.length; + + if (iterator.length === 3) { + while (++index < size) { + key = keys[index]; + iterator(object[key], key, onlyOnce(callback)); + } + } else { + while (++index < size) { + iterator(object[keys[index]], onlyOnce(callback)); + } + } + } + + /** + * @private + */ + function symbolEach(collection, iterator, callback) { + var iter = collection[iteratorSymbol](); + var index = 0; + var item; + if (iterator.length === 3) { + while ((item = iter.next()).done === false) { + iterator(item.value, index++, onlyOnce(callback)); + } + } else { + while ((item = iter.next()).done === false) { + index++; + iterator(item.value, onlyOnce(callback)); + } + } + return index; + } + + /** + * @private + */ + function arrayEachResult(array, result, iterator, callback) { + var index = -1; + var size = array.length; + + if (iterator.length === 4) { + while (++index < size) { + iterator(result, array[index], index, onlyOnce(callback)); + } + } else { + while (++index < size) { + iterator(result, array[index], onlyOnce(callback)); + } + } + } + + /** + * @private + */ + function baseEachResult(object, result, iterator, callback, keys) { + var key; + var index = -1; + var size = keys.length; + + if (iterator.length === 4) { + while (++index < size) { + key = keys[index]; + iterator(result, object[key], key, onlyOnce(callback)); + } + } else { + while (++index < size) { + iterator(result, object[keys[index]], onlyOnce(callback)); + } + } + } + + /** + * @private + */ + function symbolEachResult(collection, result, iterator, callback) { + var item; + var index = 0; + var iter = collection[iteratorSymbol](); + + if (iterator.length === 4) { + while ((item = iter.next()).done === false) { + iterator(result, item.value, index++, onlyOnce(callback)); + } + } else { + while ((item = iter.next()).done === false) { + index++; + iterator(result, item.value, onlyOnce(callback)); + } + } + return index; + } + + /** + * @private + */ + function arrayEachFunc(array, createCallback) { + var index = -1; + var size = array.length; + + while (++index < size) { + array[index](createCallback(index)); + } + } + + /** + * @private + */ + function baseEachFunc(object, createCallback, keys) { + var key; + var index = -1; + var size = keys.length; + + while (++index < size) { + key = keys[index]; + object[key](createCallback(key)); + } + } + + /** + * @private + */ + function arrayEachIndex(array, iterator, createCallback) { + var index = -1; + var size = array.length; + + if (iterator.length === 3) { + while (++index < size) { + iterator(array[index], index, createCallback(index)); + } + } else { + while (++index < size) { + iterator(array[index], createCallback(index)); + } + } + } + + /** + * @private + */ + function baseEachIndex(object, iterator, createCallback, keys) { + var key; + var index = -1; + var size = keys.length; + + if (iterator.length === 3) { + while (++index < size) { + key = keys[index]; + iterator(object[key], key, createCallback(index)); + } + } else { + while (++index < size) { + iterator(object[keys[index]], createCallback(index)); + } + } + } + + /** + * @private + */ + function symbolEachIndex(collection, iterator, createCallback) { + var item; + var index = 0; + var iter = collection[iteratorSymbol](); + + if (iterator.length === 3) { + while ((item = iter.next()).done === false) { + iterator(item.value, index, createCallback(index++)); + } + } else { + while ((item = iter.next()).done === false) { + iterator(item.value, createCallback(index++)); + } + } + return index; + } + + /** + * @private + */ + function baseEachKey(object, iterator, createCallback, keys) { + var key; + var index = -1; + var size = keys.length; + + if (iterator.length === 3) { + while (++index < size) { + key = keys[index]; + iterator(object[key], key, createCallback(key)); + } + } else { + while (++index < size) { + key = keys[index]; + iterator(object[key], createCallback(key)); + } + } + } + + /** + * @private + */ + function symbolEachKey(collection, iterator, createCallback) { + var item; + var index = 0; + var iter = collection[iteratorSymbol](); + + if (iterator.length === 3) { + while ((item = iter.next()).done === false) { + iterator(item.value, index, createCallback(index++)); + } + } else { + while ((item = iter.next()).done === false) { + iterator(item.value, createCallback(index++)); + } + } + return index; + } + + /** + * @private + */ + function arrayEachValue(array, iterator, createCallback) { + var value; + var index = -1; + var size = array.length; + + if (iterator.length === 3) { + while (++index < size) { + value = array[index]; + iterator(value, index, createCallback(value)); + } + } else { + while (++index < size) { + value = array[index]; + iterator(value, createCallback(value)); + } + } + } + + /** + * @private + */ + function baseEachValue(object, iterator, createCallback, keys) { + var key, value; + var index = -1; + var size = keys.length; + + if (iterator.length === 3) { + while (++index < size) { + key = keys[index]; + value = object[key]; + iterator(value, key, createCallback(value)); + } + } else { + while (++index < size) { + value = object[keys[index]]; + iterator(value, createCallback(value)); + } + } + } + + /** + * @private + */ + function symbolEachValue(collection, iterator, createCallback) { + var value, item; + var index = 0; + var iter = collection[iteratorSymbol](); + + if (iterator.length === 3) { + while ((item = iter.next()).done === false) { + value = item.value; + iterator(value, index++, createCallback(value)); + } + } else { + while ((item = iter.next()).done === false) { + index++; + value = item.value; + iterator(value, createCallback(value)); + } + } + return index; + } + + /** + * @private + */ + function arrayEachIndexValue(array, iterator, createCallback) { + var value; + var index = -1; + var size = array.length; + + if (iterator.length === 3) { + while (++index < size) { + value = array[index]; + iterator(value, index, createCallback(index, value)); + } + } else { + while (++index < size) { + value = array[index]; + iterator(value, createCallback(index, value)); + } + } + } + + /** + * @private + */ + function baseEachIndexValue(object, iterator, createCallback, keys) { + var key, value; + var index = -1; + var size = keys.length; + + if (iterator.length === 3) { + while (++index < size) { + key = keys[index]; + value = object[key]; + iterator(value, key, createCallback(index, value)); + } + } else { + while (++index < size) { + value = object[keys[index]]; + iterator(value, createCallback(index, value)); + } + } + } + + /** + * @private + */ + function symbolEachIndexValue(collection, iterator, createCallback) { + var value, item; + var index = 0; + var iter = collection[iteratorSymbol](); + + if (iterator.length === 3) { + while ((item = iter.next()).done === false) { + value = item.value; + iterator(value, index, createCallback(index++, value)); + } + } else { + while ((item = iter.next()).done === false) { + value = item.value; + iterator(value, createCallback(index++, value)); + } + } + return index; + } + + /** + * @private + */ + function baseEachKeyValue(object, iterator, createCallback, keys) { + var key, value; + var index = -1; + var size = keys.length; + + if (iterator.length === 3) { + while (++index < size) { + key = keys[index]; + value = object[key]; + iterator(value, key, createCallback(key, value)); + } + } else { + while (++index < size) { + key = keys[index]; + value = object[key]; + iterator(value, createCallback(key, value)); + } + } + } + + /** + * @private + */ + function symbolEachKeyValue(collection, iterator, createCallback) { + var value, item; + var index = 0; + var iter = collection[iteratorSymbol](); + + if (iterator.length === 3) { + while ((item = iter.next()).done === false) { + value = item.value; + iterator(value, index, createCallback(index++, value)); + } + } else { + while ((item = iter.next()).done === false) { + value = item.value; + iterator(value, createCallback(index++, value)); + } + } + return index; + } + + /** + * @private + * @param {Function} func + */ + function onlyOnce(func) { + return function(err, res) { + var fn = func; + func = throwError; + fn(err, res); + }; + } + + /** + * @private + * @param {Function} func + */ + function once(func) { + return function(err, res) { + var fn = func; + func = noop; + fn(err, res); + }; + } + + /** + * @private + * @param {Function} arrayEach + * @param {Function} baseEach + */ + function createEach(arrayEach, baseEach, symbolEach) { + return function each(collection, iterator, callback) { + callback = once(callback || noop); + var size, keys; + var completed = 0; + if (isArray(collection)) { + size = collection.length; + arrayEach(collection, iterator, done); + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = symbolEach(collection, iterator, done); + size && size === completed && callback(null); + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + baseEach(collection, iterator, done, keys); + } + if (!size) { + callback(null); + } + + function done(err, bool) { + if (err) { + callback = once(callback); + callback(err); + } else if (++completed === size) { + callback(null); + } else if (bool === false) { + callback = once(callback); + callback(null); + } + } + }; + } + + /** + * @private + * @param {Function} arrayEach + * @param {Function} baseEach + * @param {Function} symbolEach + */ + function createMap(arrayEach, baseEach, symbolEach, useArray) { + var init, clone; + if (useArray) { + init = Array; + clone = createArray; + } else { + init = function() { + return {}; + }; + clone = objectClone; + } + + return function(collection, iterator, callback) { + callback = callback || noop; + var size, keys, result; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + result = init(size); + arrayEach(collection, iterator, createCallback); + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + // TODO: size could be changed + result = init(0); + size = symbolEach(collection, iterator, createCallback); + size && size === completed && callback(null, result); + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + result = init(size); + baseEach(collection, iterator, createCallback, keys); + } + if (!size) { + callback(null, init()); + } + + function createCallback(key) { + return function done(err, res) { + if (key === null) { + throwError(); + } + if (err) { + key = null; + callback = once(callback); + callback(err, clone(result)); + return; + } + result[key] = res; + key = null; + if (++completed === size) { + callback(null, result); + } + }; + } + }; + } + + /** + * @private + * @param {Function} arrayEach + * @param {Function} baseEach + * @param {Function} symbolEach + * @param {boolean} bool + */ + function createFilter(arrayEach, baseEach, symbolEach, bool) { + return function(collection, iterator, callback) { + callback = callback || noop; + var size, keys, result; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + result = Array(size); + arrayEach(collection, iterator, createCallback); + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + result = []; + size = symbolEach(collection, iterator, createCallback); + size && size === completed && callback(null, compact(result)); + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + result = Array(size); + baseEach(collection, iterator, createCallback, keys); + } + if (!size) { + return callback(null, []); + } + + function createCallback(index, value) { + return function done(err, res) { + if (index === null) { + throwError(); + } + if (err) { + index = null; + callback = once(callback); + callback(err); + return; + } + if (!!res === bool) { + result[index] = value; + } + index = null; + if (++completed === size) { + callback(null, compact(result)); + } + }; + } + }; + } + + /** + * @private + * @param {boolean} bool + */ + function createFilterSeries(bool) { + return function(collection, iterator, callback) { + callback = onlyOnce(callback || noop); + var size, key, value, keys, iter, item, iterate; + var sync = false; + var completed = 0; + var result = []; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null, []); + } + iterate(); + + function arrayIterator() { + value = collection[completed]; + iterator(value, done); + } + + function arrayIteratorWithIndex() { + value = collection[completed]; + iterator(value, completed, done); + } + + function symbolIterator() { + item = iter.next(); + value = item.value; + item.done ? callback(null, result) : iterator(value, done); + } + + function symbolIteratorWithKey() { + item = iter.next(); + value = item.value; + item.done ? callback(null, result) : iterator(value, completed, done); + } + + function objectIterator() { + key = keys[completed]; + value = collection[key]; + iterator(value, done); + } + + function objectIteratorWithKey() { + key = keys[completed]; + value = collection[key]; + iterator(value, key, done); + } + + function done(err, res) { + if (err) { + callback(err); + return; + } + if (!!res === bool) { + result[result.length] = value; + } + if (++completed === size) { + iterate = throwError; + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + }; + } + + /** + * @private + * @param {boolean} bool + */ + function createFilterLimit(bool) { + return function(collection, limit, iterator, callback) { + callback = callback || noop; + var size, index, key, value, keys, iter, item, iterate, result; + var sync = false; + var started = 0; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + result = []; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null, []); + } + result = result || Array(size); + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + index = started++; + if (index < size) { + value = collection[index]; + iterator(value, createCallback(value, index)); + } + } + + function arrayIteratorWithIndex() { + index = started++; + if (index < size) { + value = collection[index]; + iterator(value, index, createCallback(value, index)); + } + } + + function symbolIterator() { + item = iter.next(); + if (item.done === false) { + value = item.value; + iterator(value, createCallback(value, started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, compact(result)); + } + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done === false) { + value = item.value; + iterator(value, started, createCallback(value, started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, compact(result)); + } + } + + function objectIterator() { + index = started++; + if (index < size) { + value = collection[keys[index]]; + iterator(value, createCallback(value, index)); + } + } + + function objectIteratorWithKey() { + index = started++; + if (index < size) { + key = keys[index]; + value = collection[key]; + iterator(value, key, createCallback(value, index)); + } + } + + function createCallback(value, index) { + return function(err, res) { + if (index === null) { + throwError(); + } + if (err) { + index = null; + iterate = noop; + callback = once(callback); + callback(err); + return; + } + if (!!res === bool) { + result[index] = value; + } + index = null; + if (++completed === size) { + callback = onlyOnce(callback); + callback(null, compact(result)); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + }; + } + }; + } + + /** + * @memberof async + * @namespace eachSeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(); + * }, num * 10); + * }; + * async.eachSeries(array, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(); + * }, num * 10); + * }; + * async.eachSeries(array, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [[1, 0], [3, 1], [2, 2]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(); + * }, num * 10); + * }; + * async.eachSeries(object, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(); + * }, num * 10); + * }; + * async.eachSeries(object, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'b']] + * }); + * + * @example + * + * // break + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num !== 3); + * }, num * 10); + * }; + * async.eachSeries(array, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [1, 3] + * }); + */ + function eachSeries(collection, iterator, callback) { + callback = onlyOnce(callback || noop); + var size, key, keys, iter, item, iterate; + var sync = false; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null); + } + iterate(); + + function arrayIterator() { + iterator(collection[completed], done); + } + + function arrayIteratorWithIndex() { + iterator(collection[completed], completed, done); + } + + function symbolIterator() { + item = iter.next(); + item.done ? callback(null) : iterator(item.value, done); + } + + function symbolIteratorWithKey() { + item = iter.next(); + item.done ? callback(null) : iterator(item.value, completed, done); + } + + function objectIterator() { + iterator(collection[keys[completed]], done); + } + + function objectIteratorWithKey() { + key = keys[completed]; + iterator(collection[key], key, done); + } + + function done(err, bool) { + if (err) { + callback(err); + } else if (++completed === size || bool === false) { + iterate = throwError; + callback(null); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace eachLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(); + * }, num * 10); + * }; + * async.eachLimit(array, 2, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(); + * }, num * 10); + * }; + * async.eachLimit(array, 2, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(); + * }, num * 10); + * }; + * async.eachLimit(object, 2, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(); + * }, num * 10); + * }; + * async.eachLimit(object, 2, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e'], [4, 'd']] + * }); + * + * @example + * + * // break + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num !== 5); + * }, num * 10); + * }; + * async.eachLimit(array, 2, iterator, function(err, res) { + * console.log(res); // undefined + * console.log(order); // [1, 3, 5] + * }); + * + */ + function eachLimit(collection, limit, iterator, callback) { + callback = callback || noop; + var size, index, key, keys, iter, item, iterate; + var sync = false; + var started = 0; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } else { + return callback(null); + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null); + } + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + if (started < size) { + iterator(collection[started++], done); + } + } + + function arrayIteratorWithIndex() { + index = started++; + if (index < size) { + iterator(collection[index], index, done); + } + } + + function symbolIterator() { + item = iter.next(); + if (item.done === false) { + started++; + iterator(item.value, done); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null); + } + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done === false) { + iterator(item.value, started++, done); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null); + } + } + + function objectIterator() { + if (started < size) { + iterator(collection[keys[started++]], done); + } + } + + function objectIteratorWithKey() { + index = started++; + if (index < size) { + key = keys[index]; + iterator(collection[key], key, done); + } + } + + function done(err, bool) { + if (err || bool === false) { + iterate = noop; + callback = once(callback); + callback(err); + } else if (++completed === size) { + iterator = noop; + iterate = throwError; + callback = onlyOnce(callback); + callback(null); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace mapSeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.mapSeries(array, iterator, function(err, res) { + * console.log(res); // [1, 3, 2]; + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num); + * }, num * 10); + * }; + * async.mapSeries(array, iterator, function(err, res) { + * console.log(res); // [1, 3, 2] + * console.log(order); // [[1, 0], [3, 1], [2, 2]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.mapSeries(object, iterator, function(err, res) { + * console.log(res); // [1, 3, 2] + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num); + * }, num * 10); + * }; + * async.mapSeries(object, iterator, function(err, res) { + * console.log(res); // [1, 3, 2] + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'c']] + * }); + * + */ + function mapSeries(collection, iterator, callback) { + callback = callback || noop; + var size, key, keys, iter, item, result, iterate; + var sync = false; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + result = []; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null, []); + } + result = result || Array(size); + iterate(); + + function arrayIterator() { + iterator(collection[completed], done); + } + + function arrayIteratorWithIndex() { + iterator(collection[completed], completed, done); + } + + function symbolIterator() { + item = iter.next(); + item.done ? callback(null, result) : iterator(item.value, done); + } + + function symbolIteratorWithKey() { + item = iter.next(); + item.done ? callback(null, result) : iterator(item.value, completed, done); + } + + function objectIterator() { + iterator(collection[keys[completed]], done); + } + + function objectIteratorWithKey() { + key = keys[completed]; + iterator(collection[key], key, done); + } + + function done(err, res) { + if (err) { + iterate = throwError; + callback = onlyOnce(callback); + callback(err, createArray(result)); + return; + } + result[completed] = res; + if (++completed === size) { + iterate = throwError; + callback(null, result); + callback = throwError; + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace mapLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.mapLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [1, 5, 3, 4, 2] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num); + * }, num * 10); + * }; + * async.mapLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [1, 5, 3, 4, 2] + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.mapLimit(object, 2, iterator, function(err, res) { + * console.log(res); // [1, 5, 3, 4, 2] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num); + * }, num * 10); + * }; + * async.mapLimit(object, 2, iterator, function(err, res) { + * console.log(res); // [1, 5, 3, 4, 2] + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e'], [4, 'd']] + * }); + * + */ + function mapLimit(collection, limit, iterator, callback) { + callback = callback || noop; + var size, index, key, keys, iter, item, result, iterate; + var sync = false; + var started = 0; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + result = []; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null, []); + } + result = result || Array(size); + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + index = started++; + if (index < size) { + iterator(collection[index], createCallback(index)); + } + } + + function arrayIteratorWithIndex() { + index = started++; + if (index < size) { + iterator(collection[index], index, createCallback(index)); + } + } + + function symbolIterator() { + item = iter.next(); + if (item.done === false) { + iterator(item.value, createCallback(started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, result); + } + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done === false) { + iterator(item.value, started, createCallback(started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, result); + } + } + + function objectIterator() { + index = started++; + if (index < size) { + iterator(collection[keys[index]], createCallback(index)); + } + } + + function objectIteratorWithKey() { + index = started++; + if (index < size) { + key = keys[index]; + iterator(collection[key], key, createCallback(index)); + } + } + + function createCallback(index) { + return function(err, res) { + if (index === null) { + throwError(); + } + if (err) { + index = null; + iterate = noop; + callback = once(callback); + callback(err, createArray(result)); + return; + } + result[index] = res; + index = null; + if (++completed === size) { + iterate = throwError; + callback(null, result); + callback = throwError; + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + }; + } + } + + /** + * @memberof async + * @namespace mapValuesSeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.mapValuesSeries(array, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 3, '2': 2 } + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num); + * }, num * 10); + * }; + * async.mapValuesSeries(array, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 3, '2': 2 } + * console.log(order); // [[1, 0], [3, 1], [2, 2]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.mapValuesSeries(object, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 3, c: 2 } + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num); + * }, num * 10); + * }; + * async.mapValuesSeries(object, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 3, c: 2 } + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'c']] + * }); + * + */ + function mapValuesSeries(collection, iterator, callback) { + callback = callback || noop; + var size, key, keys, iter, item, iterate; + var sync = false; + var result = {}; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null, result); + } + iterate(); + + function arrayIterator() { + key = completed; + iterator(collection[completed], done); + } + + function arrayIteratorWithIndex() { + key = completed; + iterator(collection[completed], completed, done); + } + + function symbolIterator() { + key = completed; + item = iter.next(); + item.done ? callback(null, result) : iterator(item.value, done); + } + + function symbolIteratorWithKey() { + key = completed; + item = iter.next(); + item.done ? callback(null, result) : iterator(item.value, completed, done); + } + + function objectIterator() { + key = keys[completed]; + iterator(collection[key], done); + } + + function objectIteratorWithKey() { + key = keys[completed]; + iterator(collection[key], key, done); + } + + function done(err, res) { + if (err) { + iterate = throwError; + callback = onlyOnce(callback); + callback(err, objectClone(result)); + return; + } + result[key] = res; + if (++completed === size) { + iterate = throwError; + callback(null, result); + callback = throwError; + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace mapValuesLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.mapValuesLimit(array, 2, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 5, '2': 3, '3': 4, '4': 2 } + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num); + * }, num * 10); + * }; + * async.mapValuesLimit(array, 2, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 5, '2': 3, '3': 4, '4': 2 } + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.mapValuesLimit(object, 2, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 5, c: 3, d: 4, e: 2 } + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num); + * }, num * 10); + * }; + * async.mapValuesLimit(object, 2, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 5, c: 3, d: 4, e: 2 } + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e'], [4, 'd']] + * }); + * + */ + function mapValuesLimit(collection, limit, iterator, callback) { + callback = callback || noop; + var size, index, key, keys, iter, item, iterate; + var sync = false; + var result = {}; + var started = 0; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null, result); + } + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + index = started++; + if (index < size) { + iterator(collection[index], createCallback(index)); + } + } + + function arrayIteratorWithIndex() { + index = started++; + if (index < size) { + iterator(collection[index], index, createCallback(index)); + } + } + + function symbolIterator() { + item = iter.next(); + if (item.done === false) { + iterator(item.value, createCallback(started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, result); + } + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done === false) { + iterator(item.value, started, createCallback(started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, result); + } + } + + function objectIterator() { + index = started++; + if (index < size) { + key = keys[index]; + iterator(collection[key], createCallback(key)); + } + } + + function objectIteratorWithKey() { + index = started++; + if (index < size) { + key = keys[index]; + iterator(collection[key], key, createCallback(key)); + } + } + + function createCallback(key) { + return function(err, res) { + if (key === null) { + throwError(); + } + if (err) { + key = null; + iterate = noop; + callback = once(callback); + callback(err, objectClone(result)); + return; + } + result[key] = res; + key = null; + if (++completed === size) { + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + }; + } + } + + /** + * @private + * @param {Function} arrayEach + * @param {Function} baseEach + * @param {Function} symbolEach + * @param {boolean} bool + */ + function createDetect(arrayEach, baseEach, symbolEach, bool) { + return function(collection, iterator, callback) { + callback = callback || noop; + var size, keys; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + arrayEach(collection, iterator, createCallback); + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = symbolEach(collection, iterator, createCallback); + size && size === completed && callback(null); + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + baseEach(collection, iterator, createCallback, keys); + } + if (!size) { + callback(null); + } + + function createCallback(value) { + var called = false; + return function done(err, res) { + if (called) { + throwError(); + } + called = true; + if (err) { + callback = once(callback); + callback(err); + } else if (!!res === bool) { + callback = once(callback); + callback(null, value); + } else if (++completed === size) { + callback(null); + } + }; + } + }; + } + + /** + * @private + * @param {boolean} bool + */ + function createDetectSeries(bool) { + return function(collection, iterator, callback) { + callback = onlyOnce(callback || noop); + var size, key, value, keys, iter, item, iterate; + var sync = false; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null); + } + iterate(); + + function arrayIterator() { + value = collection[completed]; + iterator(value, done); + } + + function arrayIteratorWithIndex() { + value = collection[completed]; + iterator(value, completed, done); + } + + function symbolIterator() { + item = iter.next(); + value = item.value; + item.done ? callback(null) : iterator(value, done); + } + + function symbolIteratorWithKey() { + item = iter.next(); + value = item.value; + item.done ? callback(null) : iterator(value, completed, done); + } + + function objectIterator() { + value = collection[keys[completed]]; + iterator(value, done); + } + + function objectIteratorWithKey() { + key = keys[completed]; + value = collection[key]; + iterator(value, key, done); + } + + function done(err, res) { + if (err) { + callback(err); + } else if (!!res === bool) { + iterate = throwError; + callback(null, value); + } else if (++completed === size) { + iterate = throwError; + callback(null); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + }; + } + + /** + * @private + * @param {boolean} bool + */ + function createDetectLimit(bool) { + return function(collection, limit, iterator, callback) { + callback = callback || noop; + var size, index, key, value, keys, iter, item, iterate; + var sync = false; + var started = 0; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null); + } + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + index = started++; + if (index < size) { + value = collection[index]; + iterator(value, createCallback(value)); + } + } + + function arrayIteratorWithIndex() { + index = started++; + if (index < size) { + value = collection[index]; + iterator(value, index, createCallback(value)); + } + } + + function symbolIterator() { + item = iter.next(); + if (item.done === false) { + started++; + value = item.value; + iterator(value, createCallback(value)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null); + } + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done === false) { + value = item.value; + iterator(value, started++, createCallback(value)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null); + } + } + + function objectIterator() { + index = started++; + if (index < size) { + value = collection[keys[index]]; + iterator(value, createCallback(value)); + } + } + + function objectIteratorWithKey() { + if (started < size) { + key = keys[started++]; + value = collection[key]; + iterator(value, key, createCallback(value)); + } + } + + function createCallback(value) { + var called = false; + return function(err, res) { + if (called) { + throwError(); + } + called = true; + if (err) { + iterate = noop; + callback = once(callback); + callback(err); + } else if (!!res === bool) { + iterate = noop; + callback = once(callback); + callback(null, value); + } else if (++completed === size) { + callback(null); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + }; + } + }; + } + + /** + * @private + * @param {Function} arrayEach + * @param {Function} baseEach + * @param {Function} symbolEach + * @param {boolean} bool + */ + function createPick(arrayEach, baseEach, symbolEach, bool) { + return function(collection, iterator, callback) { + callback = callback || noop; + var size, keys; + var completed = 0; + var result = {}; + + if (isArray(collection)) { + size = collection.length; + arrayEach(collection, iterator, createCallback); + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = symbolEach(collection, iterator, createCallback); + size && size === completed && callback(null, result); + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + baseEach(collection, iterator, createCallback, keys); + } + if (!size) { + return callback(null, {}); + } + + function createCallback(key, value) { + return function done(err, res) { + if (key === null) { + throwError(); + } + if (err) { + key = null; + callback = once(callback); + callback(err, objectClone(result)); + return; + } + if (!!res === bool) { + result[key] = value; + } + key = null; + if (++completed === size) { + callback(null, result); + } + }; + } + }; + } + + /** + * @private + * @param {boolean} bool + */ + function createPickSeries(bool) { + return function(collection, iterator, callback) { + callback = onlyOnce(callback || noop); + var size, key, value, keys, iter, item, iterate; + var sync = false; + var result = {}; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null, {}); + } + iterate(); + + function arrayIterator() { + key = completed; + value = collection[completed]; + iterator(value, done); + } + + function arrayIteratorWithIndex() { + key = completed; + value = collection[completed]; + iterator(value, completed, done); + } + + function symbolIterator() { + key = completed; + item = iter.next(); + value = item.value; + item.done ? callback(null, result) : iterator(value, done); + } + + function symbolIteratorWithKey() { + key = completed; + item = iter.next(); + value = item.value; + item.done ? callback(null, result) : iterator(value, key, done); + } + + function objectIterator() { + key = keys[completed]; + value = collection[key]; + iterator(value, done); + } + + function objectIteratorWithKey() { + key = keys[completed]; + value = collection[key]; + iterator(value, key, done); + } + + function done(err, res) { + if (err) { + callback(err, result); + return; + } + if (!!res === bool) { + result[key] = value; + } + if (++completed === size) { + iterate = throwError; + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + }; + } + + /** + * @private + * @param {boolean} bool + */ + function createPickLimit(bool) { + return function(collection, limit, iterator, callback) { + callback = callback || noop; + var size, index, key, value, keys, iter, item, iterate; + var sync = false; + var result = {}; + var started = 0; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null, {}); + } + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + index = started++; + if (index < size) { + value = collection[index]; + iterator(value, createCallback(value, index)); + } + } + + function arrayIteratorWithIndex() { + index = started++; + if (index < size) { + value = collection[index]; + iterator(value, index, createCallback(value, index)); + } + } + + function symbolIterator() { + item = iter.next(); + if (item.done === false) { + value = item.value; + iterator(value, createCallback(value, started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, result); + } + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done === false) { + value = item.value; + iterator(value, started, createCallback(value, started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, result); + } + } + + function objectIterator() { + if (started < size) { + key = keys[started++]; + value = collection[key]; + iterator(value, createCallback(value, key)); + } + } + + function objectIteratorWithKey() { + if (started < size) { + key = keys[started++]; + value = collection[key]; + iterator(value, key, createCallback(value, key)); + } + } + + function createCallback(value, key) { + return function(err, res) { + if (key === null) { + throwError(); + } + if (err) { + key = null; + iterate = noop; + callback = once(callback); + callback(err, objectClone(result)); + return; + } + if (!!res === bool) { + result[key] = value; + } + key = null; + if (++completed === size) { + iterate = throwError; + callback = onlyOnce(callback); + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + }; + } + }; + } + + /** + * @memberof async + * @namespace reduce + * @param {Array|Object} collection + * @param {*} result + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var collection = [1, 3, 2, 4]; + * var iterator = function(result, num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, result + num); + * }, num * 10); + * }; + * async.reduce(collection, 0, iterator, function(err, res) { + * console.log(res); // 10 + * console.log(order); // [1, 3, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var collection = [1, 3, 2, 4]; + * var iterator = function(result, num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, result + num); + * }, num * 10); + * }; + * async.reduce(collection, '', iterator, function(err, res) { + * console.log(res); // '1324' + * console.log(order); // [[1, 0], [3, 1], [2, 2], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(result, num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, result + num); + * }, num * 10); + * }; + * async.reduce(collection, '', iterator, function(err, res) { + * console.log(res); // '1324' + * console.log(order); // [1, 3, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(result, num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, result + num); + * }, num * 10); + * }; + * async.reduce(collection, 0, iterator, function(err, res) { + * console.log(res); // 10 + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'b'], [4, 'd']] + * }); + * + */ + function reduce(collection, result, iterator, callback) { + callback = onlyOnce(callback || noop); + var size, key, keys, iter, item, iterate; + var sync = false; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 4 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 4 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 4 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null, result); + } + iterate(result); + + function arrayIterator(result) { + iterator(result, collection[completed], done); + } + + function arrayIteratorWithIndex(result) { + iterator(result, collection[completed], completed, done); + } + + function symbolIterator(result) { + item = iter.next(); + item.done ? callback(null, result) : iterator(result, item.value, done); + } + + function symbolIteratorWithKey(result) { + item = iter.next(); + item.done ? callback(null, result) : iterator(result, item.value, completed, done); + } + + function objectIterator(result) { + iterator(result, collection[keys[completed]], done); + } + + function objectIteratorWithKey(result) { + key = keys[completed]; + iterator(result, collection[key], key, done); + } + + function done(err, result) { + if (err) { + callback(err, result); + } else if (++completed === size) { + iterator = throwError; + callback(null, result); + } else if (sync) { + nextTick(function() { + iterate(result); + }); + } else { + sync = true; + iterate(result); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace reduceRight + * @param {Array|Object} collection + * @param {*} result + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var collection = [1, 3, 2, 4]; + * var iterator = function(result, num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, result + num); + * }, num * 10); + * }; + * async.reduceRight(collection, 0, iterator, function(err, res) { + * console.log(res); // 10 + * console.log(order); // [4, 2, 3, 1] + * }); + * + * @example + * + * // array with index + * var order = []; + * var collection = [1, 3, 2, 4]; + * var iterator = function(result, num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, result + num); + * }, num * 10); + * }; + * async.reduceRight(collection, '', iterator, function(err, res) { + * console.log(res); // '4231' + * console.log(order); // [[4, 3], [2, 2], [3, 1], [1, 0]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(result, num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, result + num); + * }, num * 10); + * }; + * async.reduceRight(collection, '', iterator, function(err, res) { + * console.log(res); // '4231' + * console.log(order); // [4, 2, 3, 1] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(result, num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, result + num); + * }, num * 10); + * }; + * async.reduceRight(collection, 0, iterator, function(err, res) { + * console.log(res); // 10 + * console.log(order); // [[4, 3], [2, 2], [3, 1], [1, 0]] + * }); + * + */ + function reduceRight(collection, result, iterator, callback) { + callback = onlyOnce(callback || noop); + var resIndex, index, key, keys, iter, item, col, iterate; + var sync = false; + + if (isArray(collection)) { + resIndex = collection.length; + iterate = iterator.length === 4 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + col = []; + iter = collection[iteratorSymbol](); + index = -1; + while ((item = iter.next()).done === false) { + col[++index] = item.value; + } + collection = col; + resIndex = col.length; + iterate = iterator.length === 4 ? arrayIteratorWithIndex : arrayIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + resIndex = keys.length; + iterate = iterator.length === 4 ? objectIteratorWithKey : objectIterator; + } + if (!resIndex) { + return callback(null, result); + } + iterate(result); + + function arrayIterator(result) { + iterator(result, collection[--resIndex], done); + } + + function arrayIteratorWithIndex(result) { + iterator(result, collection[--resIndex], resIndex, done); + } + + function objectIterator(result) { + iterator(result, collection[keys[--resIndex]], done); + } + + function objectIteratorWithKey(result) { + key = keys[--resIndex]; + iterator(result, collection[key], key, done); + } + + function done(err, result) { + if (err) { + callback(err, result); + } else if (resIndex === 0) { + iterate = throwError; + callback(null, result); + } else if (sync) { + nextTick(function() { + iterate(result); + }); + } else { + sync = true; + iterate(result); + } + sync = false; + } + } + + /** + * @private + * @param {Function} arrayEach + * @param {Function} baseEach + * @param {Function} symbolEach + */ + function createTransform(arrayEach, baseEach, symbolEach) { + return function transform(collection, accumulator, iterator, callback) { + if (arguments.length === 3) { + callback = iterator; + iterator = accumulator; + accumulator = undefined; + } + callback = callback || noop; + var size, keys, result; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + result = accumulator !== undefined ? accumulator : []; + arrayEach(collection, result, iterator, done); + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + result = accumulator !== undefined ? accumulator : {}; + size = symbolEach(collection, result, iterator, done); + size && size === completed && callback(null, result); + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + result = accumulator !== undefined ? accumulator : {}; + baseEach(collection, result, iterator, done, keys); + } + if (!size) { + callback(null, accumulator !== undefined ? accumulator : result || {}); + } + + function done(err, bool) { + if (err) { + callback = once(callback); + callback(err, isArray(result) ? createArray(result) : objectClone(result)); + } else if (++completed === size) { + callback(null, result); + } else if (bool === false) { + callback = once(callback); + callback(null, isArray(result) ? createArray(result) : objectClone(result)); + } + } + }; + } + + /** + * @memberof async + * @namespace transformSeries + * @param {Array|Object} collection + * @param {Array|Object|Function} [accumulator] + * @param {Function} [iterator] + * @param {Function} [callback] + * @example + * + * // array + * var order = []; + * var collection = [1, 3, 2, 4]; + * var iterator = function(result, num, done) { + * setTimeout(function() { + * order.push(num); + * result.push(num) + * done(); + * }, num * 10); + * }; + * async.transformSeries(collection, iterator, function(err, res) { + * console.log(res); // [1, 3, 2, 4] + * console.log(order); // [1, 3, 2, 4] + * }); + * + * @example + * + * // array with index and accumulator + * var order = []; + * var collection = [1, 3, 2, 4]; + * var iterator = function(result, num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * result[index] = num; + * done(); + * }, num * 10); + * }; + * async.transformSeries(collection, {}, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 3, '2': 2, '3': 4 } + * console.log(order); // [[1, 0], [3, 1], [2, 2], [4, 3]] + * }); + * + * @example + * + * // object with accumulator + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(result, num, done) { + * setTimeout(function() { + * order.push(num); + * result.push(num); + * done(); + * }, num * 10); + * }; + * async.transformSeries(collection, [], iterator, function(err, res) { + * console.log(res); // [1, 3, 2, 4] + * console.log(order); // [1, 3, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2, d: 4 }; + * var iterator = function(result, num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * result[key] = num; + * done(); + * }, num * 10); + * }; + * async.transformSeries(collection, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 3, c: 2, d: 4 } + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'b'], [4, 'd']] + * }); + * + */ + function transformSeries(collection, accumulator, iterator, callback) { + if (arguments.length === 3) { + callback = iterator; + iterator = accumulator; + accumulator = undefined; + } + callback = onlyOnce(callback || noop); + var size, key, keys, iter, item, iterate, result; + var sync = false; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + result = accumulator !== undefined ? accumulator : []; + iterate = iterator.length === 4 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + result = accumulator !== undefined ? accumulator : {}; + iterate = iterator.length === 4 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + result = accumulator !== undefined ? accumulator : {}; + iterate = iterator.length === 4 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null, accumulator !== undefined ? accumulator : result || {}); + } + iterate(); + + function arrayIterator() { + iterator(result, collection[completed], done); + } + + function arrayIteratorWithIndex() { + iterator(result, collection[completed], completed, done); + } + + function symbolIterator() { + item = iter.next(); + item.done ? callback(null, result) : iterator(result, item.value, done); + } + + function symbolIteratorWithKey() { + item = iter.next(); + item.done ? callback(null, result) : iterator(result, item.value, completed, done); + } + + function objectIterator() { + iterator(result, collection[keys[completed]], done); + } + + function objectIteratorWithKey() { + key = keys[completed]; + iterator(result, collection[key], key, done); + } + + function done(err, bool) { + if (err) { + callback(err, result); + } else if (++completed === size || bool === false) { + iterate = throwError; + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace transformLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Array|Object|Function} [accumulator] + * @param {Function} [iterator] + * @param {Function} [callback] + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(result, num, done) { + * setTimeout(function() { + * order.push(num); + * result.push(num); + * done(); + * }, num * 10); + * }; + * async.transformLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [1, 3, 5, 2, 4] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // array with index and accumulator + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(result, num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * result[index] = key; + * done(); + * }, num * 10); + * }; + * async.transformLimit(array, 2, {}, iterator, function(err, res) { + * console.log(res); // { '0': 1, '1': 5, '2': 3, '3': 4, '4': 2 } + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4], [4, 3]] + * }); + * + * @example + * + * // object with accumulator + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(result, num, done) { + * setTimeout(function() { + * order.push(num); + * result.push(num); + * done(); + * }, num * 10); + * }; + * async.transformLimit(object, 2, [], iterator, function(err, res) { + * console.log(res); // [1, 3, 5, 2, 4] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(result, num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * result[key] = num; + * done(); + * }, num * 10); + * }; + * async.transformLimit(object, 2, iterator, function(err, res) { + * console.log(res); // { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e'], [4, 'd']] + * }); + * + */ + function transformLimit(collection, limit, accumulator, iterator, callback) { + if (arguments.length === 4) { + callback = iterator; + iterator = accumulator; + accumulator = undefined; + } + callback = callback || noop; + var size, index, key, keys, iter, item, iterate, result; + var sync = false; + var started = 0; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + result = accumulator !== undefined ? accumulator : []; + iterate = iterator.length === 4 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + result = accumulator !== undefined ? accumulator : {}; + iterate = iterator.length === 4 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + result = accumulator !== undefined ? accumulator : {}; + iterate = iterator.length === 4 ? objectIteratorWithKey : objectIterator; + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null, accumulator !== undefined ? accumulator : result || {}); + } + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + index = started++; + if (index < size) { + iterator(result, collection[index], onlyOnce(done)); + } + } + + function arrayIteratorWithIndex() { + index = started++; + if (index < size) { + iterator(result, collection[index], index, onlyOnce(done)); + } + } + + function symbolIterator() { + item = iter.next(); + if (item.done === false) { + started++; + iterator(result, item.value, onlyOnce(done)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, result); + } + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done === false) { + iterator(result, item.value, started++, onlyOnce(done)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, result); + } + } + + function objectIterator() { + index = started++; + if (index < size) { + iterator(result, collection[keys[index]], onlyOnce(done)); + } + } + + function objectIteratorWithKey() { + index = started++; + if (index < size) { + key = keys[index]; + iterator(result, collection[key], key, onlyOnce(done)); + } + } + + function done(err, bool) { + if (err || bool === false) { + iterate = noop; + callback(err || null, isArray(result) ? createArray(result) : objectClone(result)); + callback = noop; + } else if (++completed === size) { + iterator = noop; + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @private + * @param {function} arrayEach + * @param {function} baseEach + * @param {function} symbolEach + */ + function createSortBy(arrayEach, baseEach, symbolEach) { + return function sortBy(collection, iterator, callback) { + callback = callback || noop; + var size, array, criteria; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + array = Array(size); + criteria = Array(size); + arrayEach(collection, iterator, createCallback); + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + array = []; + criteria = []; + size = symbolEach(collection, iterator, createCallback); + size && size === completed && callback(null, sortByCriteria(array, criteria)); + } else if (typeof collection === obj) { + var keys = nativeKeys(collection); + size = keys.length; + array = Array(size); + criteria = Array(size); + baseEach(collection, iterator, createCallback, keys); + } + if (!size) { + callback(null, []); + } + + function createCallback(index, value) { + var called = false; + array[index] = value; + return function done(err, criterion) { + if (called) { + throwError(); + } + called = true; + criteria[index] = criterion; + if (err) { + callback = once(callback); + callback(err); + } else if (++completed === size) { + callback(null, sortByCriteria(array, criteria)); + } + }; + } + }; + } + + /** + * @memberof async + * @namespace sortBySeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.sortBySeries(array, iterator, function(err, res) { + * console.log(res); // [1, 2, 3]; + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num); + * }, num * 10); + * }; + * async.sortBySeries(array, iterator, function(err, res) { + * console.log(res); // [1, 2, 3] + * console.log(order); // [[1, 0], [3, 1], [2, 2]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.sortBySeries(object, iterator, function(err, res) { + * console.log(res); // [1, 2, 3] + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num); + * }, num * 10); + * }; + * async.sortBySeries(object, iterator, function(err, res) { + * console.log(res); // [1, 2, 3] + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'c']] + * }); + * + */ + function sortBySeries(collection, iterator, callback) { + callback = onlyOnce(callback || noop); + var size, key, value, keys, iter, item, array, criteria, iterate; + var sync = false; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + array = collection; + criteria = Array(size); + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + array = []; + criteria = []; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + array = Array(size); + criteria = Array(size); + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null, []); + } + iterate(); + + function arrayIterator() { + value = collection[completed]; + iterator(value, done); + } + + function arrayIteratorWithIndex() { + value = collection[completed]; + iterator(value, completed, done); + } + + function symbolIterator() { + item = iter.next(); + if (item.done) { + return callback(null, sortByCriteria(array, criteria)); + } + value = item.value; + array[completed] = value; + iterator(value, done); + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done) { + return callback(null, sortByCriteria(array, criteria)); + } + value = item.value; + array[completed] = value; + iterator(value, completed, done); + } + + function objectIterator() { + value = collection[keys[completed]]; + array[completed] = value; + iterator(value, done); + } + + function objectIteratorWithKey() { + key = keys[completed]; + value = collection[key]; + array[completed] = value; + iterator(value, key, done); + } + + function done(err, criterion) { + criteria[completed] = criterion; + if (err) { + callback(err); + } else if (++completed === size) { + iterate = throwError; + callback(null, sortByCriteria(array, criteria)); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace sortByLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.sortByLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [1, 2, 3, 4, 5] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num); + * }, num * 10); + * }; + * async.sortByLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [1, 2, 3, 4, 5] + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num); + * }, num * 10); + * }; + * async.sortByLimit(object, 2, iterator, function(err, res) { + * console.log(res); // [1, 2, 3, 4, 5] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num); + * }, num * 10); + * }; + * async.sortByLimit(object, 2, iterator, function(err, res) { + * console.log(res); // [1, 2, 3, 4, 5] + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e'], [4, 'd']] + * }); + * + */ + function sortByLimit(collection, limit, iterator, callback) { + callback = callback || noop; + var size, index, key, value, array, keys, iter, item, criteria, iterate; + var sync = false; + var started = 0; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + array = collection; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + array = []; + criteria = []; + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + array = Array(size); + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null, []); + } + criteria = criteria || Array(size); + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + if (started < size) { + value = collection[started]; + iterator(value, createCallback(value, started++)); + } + } + + function arrayIteratorWithIndex() { + index = started++; + if (index < size) { + value = collection[index]; + iterator(value, index, createCallback(value, index)); + } + } + + function symbolIterator() { + item = iter.next(); + if (item.done === false) { + value = item.value; + array[started] = value; + iterator(value, createCallback(value, started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, sortByCriteria(array, criteria)); + } + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done === false) { + value = item.value; + array[started] = value; + iterator(value, started, createCallback(value, started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, sortByCriteria(array, criteria)); + } + } + + function objectIterator() { + if (started < size) { + value = collection[keys[started]]; + array[started] = value; + iterator(value, createCallback(value, started++)); + } + } + + function objectIteratorWithKey() { + if (started < size) { + key = keys[started]; + value = collection[key]; + array[started] = value; + iterator(value, key, createCallback(value, started++)); + } + } + + function createCallback(value, index) { + var called = false; + return function(err, criterion) { + if (called) { + throwError(); + } + called = true; + criteria[index] = criterion; + if (err) { + iterate = noop; + callback(err); + callback = noop; + } else if (++completed === size) { + callback(null, sortByCriteria(array, criteria)); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + }; + } + } + + /** + * @memberof async + * @namespace some + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.some(array, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [1] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.some(array, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [[1, 0]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.some(object, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [1] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.some(object, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [[1, 'a']] + * }); + * + */ + function some(collection, iterator, callback) { + callback = callback || noop; + detect(collection, iterator, done); + + function done(err, res) { + if (err) { + return callback(err); + } + callback(null, !!res); + } + } + + /** + * @memberof async + * @namespace someSeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.someSeries(array, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [1] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.someSeries(array, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [[1, 0]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.someSeries(object, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [1] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.someSeries(object, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [[1, 'a']] + * }); + * + */ + function someSeries(collection, iterator, callback) { + callback = callback || noop; + detectSeries(collection, iterator, done); + + function done(err, res) { + if (err) { + return callback(err); + } + callback(null, !!res); + } + } + + /** + * @memberof async + * @namespace someLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.someLimit(array, 2, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [1] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.someLimit(array, 2, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [[1, 0]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, num % 2); + * }, num * 10); + * }; + * async.someLimit(object, 2, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [1] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num % 2); + * }, num * 10); + * }; + * async.someLimit(object, 2, iterator, function(err, res) { + * console.log(res); // true + * console.log(order); // [[1, 'a']] + * }); + * + */ + function someLimit(collection, limit, iterator, callback) { + callback = callback || noop; + detectLimit(collection, limit, iterator, done); + + function done(err, res) { + if (err) { + return callback(err); + } + callback(null, !!res); + } + } + + /** + * @private + * @param {Function} arrayEach + * @param {Function} baseEach + * @param {Function} symbolEach + */ + function createEvery(arrayEach, baseEach, symbolEach) { + var deny = createDetect(arrayEach, baseEach, symbolEach, false); + + return function every(collection, iterator, callback) { + callback = callback || noop; + deny(collection, iterator, done); + + function done(err, res) { + if (err) { + return callback(err); + } + callback(null, !res); + } + }; + } + + /** + * @private + */ + function createEverySeries() { + var denySeries = createDetectSeries(false); + + return function everySeries(collection, iterator, callback) { + callback = callback || noop; + denySeries(collection, iterator, done); + + function done(err, res) { + if (err) { + return callback(err); + } + callback(null, !res); + } + }; + } + + /** + * @private + */ + function createEveryLimit() { + var denyLimit = createDetectLimit(false); + + return function everyLimit(collection, limit, iterator, callback) { + callback = callback || noop; + denyLimit(collection, limit, iterator, done); + + function done(err, res) { + if (err) { + return callback(err); + } + callback(null, !res); + } + }; + } + + /** + * @private + * @param {Function} arrayEach + * @param {Function} baseEach + * @param {Function} symbolEach + */ + function createConcat(arrayEach, baseEach, symbolEach) { + return function concat(collection, iterator, callback) { + callback = callback || noop; + var size, result; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + result = Array(size); + arrayEach(collection, iterator, createCallback); + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + result = []; + size = symbolEach(collection, iterator, createCallback); + size && size === completed && callback(null, result); + } else if (typeof collection === obj) { + var keys = nativeKeys(collection); + size = keys.length; + result = Array(size); + baseEach(collection, iterator, createCallback, keys); + } + if (!size) { + callback(null, []); + } + + function createCallback(index) { + return function done(err, res) { + if (index === null) { + throwError(); + } + if (err) { + index = null; + callback = once(callback); + arrayEachSync(result, function(array, index) { + if (array === undefined) { + result[index] = noop; + } + }); + callback(err, makeConcatResult(result)); + return; + } + switch (arguments.length) { + case 0: + case 1: + result[index] = noop; + break; + case 2: + result[index] = res; + break; + default: + result[index] = slice(arguments, 1); + break; + } + index = null; + if (++completed === size) { + callback(null, makeConcatResult(result)); + } + }; + } + }; + } + + /** + * @memberof async + * @namespace concatSeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, [num]); + * }, num * 10); + * }; + * async.concatSeries(array, iterator, function(err, res) { + * console.log(res); // [1, 3, 2]; + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 3, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, [num]); + * }, num * 10); + * }; + * async.concatSeries(array, iterator, function(err, res) { + * console.log(res); // [1, 3, 2] + * console.log(order); // [[1, 0], [3, 1], [2, 2]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, [num]); + * }, num * 10); + * }; + * async.concatSeries(object, iterator, function(err, res) { + * console.log(res); // [1, 3, 2] + * console.log(order); // [1, 3, 2] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 3, c: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, [num]); + * }, num * 10); + * }; + * async.concatSeries(object, iterator, function(err, res) { + * console.log(res); // [1, 3, 2] + * console.log(order); // [[1, 'a'], [3, 'b'], [2, 'c']] + * }); + * + */ + function concatSeries(collection, iterator, callback) { + callback = onlyOnce(callback || noop); + var size, key, keys, iter, item, iterate; + var sync = false; + var result = []; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null, result); + } + iterate(); + + function arrayIterator() { + iterator(collection[completed], done); + } + + function arrayIteratorWithIndex() { + iterator(collection[completed], completed, done); + } + + function symbolIterator() { + item = iter.next(); + item.done ? callback(null, result) : iterator(item.value, done); + } + + function symbolIteratorWithKey() { + item = iter.next(); + item.done ? callback(null, result) : iterator(item.value, completed, done); + } + + function objectIterator() { + iterator(collection[keys[completed]], done); + } + + function objectIteratorWithKey() { + key = keys[completed]; + iterator(collection[key], key, done); + } + + function done(err, array) { + if (isArray(array)) { + nativePush.apply(result, array); + } else if (arguments.length >= 2) { + nativePush.apply(result, slice(arguments, 1)); + } + if (err) { + callback(err, result); + } else if (++completed === size) { + iterate = throwError; + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace concatLimit + * @param {Array|Object} collection + * @param {number} limit - limit >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, [num]); + * }, num * 10); + * }; + * async.concatLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [1, 3, 5, 2, 4] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1, 5, 3, 4, 2]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, [num]); + * }, num * 10); + * }; + * async.cocnatLimit(array, 2, iterator, function(err, res) { + * console.log(res); // [1, 3, 5, 2, 4] + * console.log(order); // [[1, 0], [3, 2], [5, 1], [2, 4], [4, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, [num]); + * }, num * 10); + * }; + * async.concatLimit(object, 2, iterator, function(err, res) { + * console.log(res); // [1, 3, 5, 2, 4] + * console.log(order); // [1, 3, 5, 2, 4] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1, b: 5, c: 3, d: 4, e: 2 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, num); + * }, num * 10); + * }; + * async.cocnatLimit(object, 2, iterator, function(err, res) { + * console.log(res); // [1, 3, 5, 2, 4] + * console.log(order); // [[1, 'a'], [3, 'c'], [5, 'b'], [2, 'e'], [4, 'd']] + * }); + * + */ + function concatLimit(collection, limit, iterator, callback) { + callback = callback || noop; + var size, key, iter, item, iterate, result; + var sync = false; + var started = 0; + var completed = 0; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + result = []; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + var keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null, []); + } + result = result || Array(size); + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + if (started < size) { + iterator(collection[started], createCallback(started++)); + } + } + + function arrayIteratorWithIndex() { + if (started < size) { + iterator(collection[started], started, createCallback(started++)); + } + } + + function symbolIterator() { + item = iter.next(); + if (item.done === false) { + iterator(item.value, createCallback(started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, makeConcatResult(result)); + } + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done === false) { + iterator(item.value, started, createCallback(started++)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, makeConcatResult(result)); + } + } + + function objectIterator() { + if (started < size) { + iterator(collection[keys[started]], createCallback(started++)); + } + } + + function objectIteratorWithKey() { + if (started < size) { + key = keys[started]; + iterator(collection[key], key, createCallback(started++)); + } + } + + function createCallback(index) { + return function(err, res) { + if (index === null) { + throwError(); + } + if (err) { + index = null; + iterate = noop; + callback = once(callback); + arrayEachSync(result, function(array, index) { + if (array === undefined) { + result[index] = noop; + } + }); + callback(err, makeConcatResult(result)); + return; + } + switch (arguments.length) { + case 0: + case 1: + result[index] = noop; + break; + case 2: + result[index] = res; + break; + default: + result[index] = slice(arguments, 1); + break; + } + index = null; + if (++completed === size) { + iterate = throwError; + callback(null, makeConcatResult(result)); + callback = throwError; + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + }; + } + } + + /** + * @private + * @param {Function} arrayEach + * @param {Function} baseEach + * @param {Function} symbolEach + */ + function createGroupBy(arrayEach, baseEach, symbolEach) { + return function groupBy(collection, iterator, callback) { + callback = callback || noop; + var size; + var completed = 0; + var result = {}; + + if (isArray(collection)) { + size = collection.length; + arrayEach(collection, iterator, createCallback); + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = symbolEach(collection, iterator, createCallback); + size && size === completed && callback(null, result); + } else if (typeof collection === obj) { + var keys = nativeKeys(collection); + size = keys.length; + baseEach(collection, iterator, createCallback, keys); + } + if (!size) { + callback(null, {}); + } + + function createCallback(value) { + var called = false; + return function done(err, key) { + if (called) { + throwError(); + } + called = true; + if (err) { + callback = once(callback); + callback(err, objectClone(result)); + return; + } + var array = result[key]; + if (!array) { + result[key] = [value]; + } else { + array.push(value); + } + if (++completed === size) { + callback(null, result); + } + }; + } + }; + } + + /** + * @memberof async + * @namespace groupBySeries + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [4.2, 6.4, 6.1]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupBySeries(array, iterator, function(err, res) { + * console.log(res); // { '4': [4.2], '6': [6.4, 6.1] } + * console.log(order); // [4.2, 6.4, 6.1] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [4.2, 6.4, 6.1]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupBySeries(array, iterator, function(err, res) { + * console.log(res); // { '4': [4.2], '6': [6.4, 6.1] } + * console.log(order); // [[4.2, 0], [6.4, 1], [6.1, 2]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 4.2, b: 6.4, c: 6.1 }; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupBySeries(object, iterator, function(err, res) { + * console.log(res); // { '4': [4.2], '6': [6.4, 6.1] } + * console.log(order); // [4.2, 6.4, 6.1] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 4.2, b: 6.4, c: 6.1 }; + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupBySeries(object, iterator, function(err, res) { + * console.log(res); // { '4': [4.2], '6': [6.4, 6.1] } + * console.log(order); // [[4.2, 'a'], [6.4, 'b'], [6.1, 'c']] + * }); + * + */ + function groupBySeries(collection, iterator, callback) { + callback = onlyOnce(callback || noop); + var size, key, value, keys, iter, item, iterate; + var sync = false; + var completed = 0; + var result = {}; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size) { + return callback(null, result); + } + iterate(); + + function arrayIterator() { + value = collection[completed]; + iterator(value, done); + } + + function arrayIteratorWithIndex() { + value = collection[completed]; + iterator(value, completed, done); + } + + function symbolIterator() { + item = iter.next(); + value = item.value; + item.done ? callback(null, result) : iterator(value, done); + } + + function symbolIteratorWithKey() { + item = iter.next(); + value = item.value; + item.done ? callback(null, result) : iterator(value, completed, done); + } + + function objectIterator() { + value = collection[keys[completed]]; + iterator(value, done); + } + + function objectIteratorWithKey() { + key = keys[completed]; + value = collection[key]; + iterator(value, key, done); + } + + function done(err, key) { + if (err) { + iterate = throwError; + callback = onlyOnce(callback); + callback(err, objectClone(result)); + return; + } + var array = result[key]; + if (!array) { + result[key] = [value]; + } else { + array.push(value); + } + if (++completed === size) { + iterate = throwError; + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace groupByLimit + * @param {Array|Object} collection + * @param {Function} iterator + * @param {Function} callback + * @example + * + * // array + * var order = []; + * var array = [1.1, 5.9, 3.2, 3.9, 2.1]; + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupByLimit(array, 2, iterator, function(err, res) { + * console.log(res); // { '1': [1.1], '3': [3.2, 3.9], '5': [5.9], '2': [2.1] } + * console.log(order); // [1.1, 3.2, 5.9, 2.1, 3.9] + * }); + * + * @example + * + * // array with index + * var order = []; + * var array = [1.1, 5.9, 3.2, 3.9, 2.1]; + * var iterator = function(num, index, done) { + * setTimeout(function() { + * order.push([num, index]); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupByLimit(array, 2, iterator, function(err, res) { + * console.log(res); // { '1': [1.1], '3': [3.2, 3.9], '5': [5.9], '2': [2.1] } + * console.log(order); // [[1.1, 0], [3.2, 2], [5.9, 1], [2.1, 4], [3.9, 3]] + * }); + * + * @example + * + * // object + * var order = []; + * var object = { a: 1.1, b: 5.9, c: 3.2, d: 3.9, e: 2.1 } + * var iterator = function(num, done) { + * setTimeout(function() { + * order.push(num); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupByLimit(object, 2, iterator, function(err, res) { + * console.log(res); // { '1': [1.1], '3': [3.2, 3.9], '5': [5.9], '2': [2.1] } + * console.log(order); // [1.1, 3.2, 5.9, 2.1, 3.9] + * }); + * + * @example + * + * // object with key + * var order = []; + * var object = { a: 1.1, b: 5.9, c: 3.2, d: 3.9, e: 2.1 } + * var iterator = function(num, key, done) { + * setTimeout(function() { + * order.push([num, key]); + * done(null, Math.floor(num)); + * }, num * 10); + * }; + * async.groupByLimit(object, 2, iterator, function(err, res) { + * console.log(res); // { '1': [1.1], '3': [3.2, 3.9], '5': [5.9], '2': [2.1] } + * console.log(order); // [[1.1, 'a'], [3.2, 'c'], [5.9, 'b'], [2.1, 'e'], [3.9, 'd']] + * }); + * + */ + function groupByLimit(collection, limit, iterator, callback) { + callback = callback || noop; + var size, index, key, value, keys, iter, item, iterate; + var sync = false; + var started = 0; + var completed = 0; + var result = {}; + + if (isArray(collection)) { + size = collection.length; + iterate = iterator.length === 3 ? arrayIteratorWithIndex : arrayIterator; + } else if (!collection) { + } else if (iteratorSymbol && collection[iteratorSymbol]) { + size = Infinity; + iter = collection[iteratorSymbol](); + iterate = iterator.length === 3 ? symbolIteratorWithKey : symbolIterator; + } else if (typeof collection === obj) { + keys = nativeKeys(collection); + size = keys.length; + iterate = iterator.length === 3 ? objectIteratorWithKey : objectIterator; + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null, result); + } + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + if (started < size) { + value = collection[started++]; + iterator(value, createCallback(value)); + } + } + + function arrayIteratorWithIndex() { + index = started++; + if (index < size) { + value = collection[index]; + iterator(value, index, createCallback(value)); + } + } + + function symbolIterator() { + item = iter.next(); + if (item.done === false) { + started++; + value = item.value; + iterator(value, createCallback(value)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, result); + } + } + + function symbolIteratorWithKey() { + item = iter.next(); + if (item.done === false) { + value = item.value; + iterator(value, started++, createCallback(value)); + } else if (completed === started && iterator !== noop) { + iterator = noop; + callback(null, result); + } + } + + function objectIterator() { + if (started < size) { + value = collection[keys[started++]]; + iterator(value, createCallback(value)); + } + } + + function objectIteratorWithKey() { + if (started < size) { + key = keys[started++]; + value = collection[key]; + iterator(value, key, createCallback(value)); + } + } + + function createCallback(value) { + var called = false; + return function(err, key) { + if (called) { + throwError(); + } + called = true; + if (err) { + iterate = noop; + callback = once(callback); + callback(err, objectClone(result)); + return; + } + var array = result[key]; + if (!array) { + result[key] = [value]; + } else { + array.push(value); + } + if (++completed === size) { + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + }; + } + } + + /** + * @private + * @param {Function} arrayEach + * @param {Function} baseEach + */ + function createParallel(arrayEach, baseEach) { + return function parallel(tasks, callback) { + callback = callback || noop; + var size, keys, result; + var completed = 0; + + if (isArray(tasks)) { + size = tasks.length; + result = Array(size); + arrayEach(tasks, createCallback); + } else if (tasks && typeof tasks === obj) { + keys = nativeKeys(tasks); + size = keys.length; + result = {}; + baseEach(tasks, createCallback, keys); + } + if (!size) { + callback(null, result); + } + + function createCallback(key) { + return function(err, res) { + if (key === null) { + throwError(); + } + if (err) { + key = null; + callback = once(callback); + callback(err, result); + return; + } + result[key] = arguments.length <= 2 ? res : slice(arguments, 1); + key = null; + if (++completed === size) { + callback(null, result); + } + }; + } + }; + } + + /** + * @memberof async + * @namespace series + * @param {Array|Object} tasks - functions + * @param {Function} callback + * @example + * + * var order = []; + * var tasks = [ + * function(done) { + * setTimeout(function() { + * order.push(1); + * done(null, 1); + * }, 10); + * }, + * function(done) { + * setTimeout(function() { + * order.push(2); + * done(null, 2); + * }, 30); + * }, + * function(done) { + * setTimeout(function() { + * order.push(3); + * done(null, 3); + * }, 40); + * }, + * function(done) { + * setTimeout(function() { + * order.push(4); + * done(null, 4); + * }, 20); + * } + * ]; + * async.series(tasks, function(err, res) { + * console.log(res); // [1, 2, 3, 4]; + * console.log(order); // [1, 2, 3, 4] + * }); + * + * @example + * + * var order = []; + * var tasks = { + * 'a': function(done) { + * setTimeout(function() { + * order.push(1); + * done(null, 1); + * }, 10); + * }, + * 'b': function(done) { + * setTimeout(function() { + * order.push(2); + * done(null, 2); + * }, 30); + * }, + * 'c': function(done) { + * setTimeout(function() { + * order.push(3); + * done(null, 3); + * }, 40); + * }, + * 'd': function(done) { + * setTimeout(function() { + * order.push(4); + * done(null, 4); + * }, 20); + * } + * }; + * async.series(tasks, function(err, res) { + * console.log(res); // { a: 1, b: 2, c: 3, d:4 } + * console.log(order); // [1, 4, 2, 3] + * }); + * + */ + function series(tasks, callback) { + callback = callback || noop; + var size, key, keys, result, iterate; + var sync = false; + var completed = 0; + + if (isArray(tasks)) { + size = tasks.length; + result = Array(size); + iterate = arrayIterator; + } else if (tasks && typeof tasks === obj) { + keys = nativeKeys(tasks); + size = keys.length; + result = {}; + iterate = objectIterator; + } else { + return callback(null); + } + if (!size) { + return callback(null, result); + } + iterate(); + + function arrayIterator() { + key = completed; + tasks[completed](done); + } + + function objectIterator() { + key = keys[completed]; + tasks[key](done); + } + + function done(err, res) { + if (err) { + iterate = throwError; + callback = onlyOnce(callback); + callback(err, result); + return; + } + result[key] = arguments.length <= 2 ? res : slice(arguments, 1); + if (++completed === size) { + iterate = throwError; + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace parallelLimit + * @param {Array|Object} tasks - functions + * @param {number} limit - limit >= 1 + * @param {Function} callback + * @example + * + * var order = []; + * var tasks = [ + * function(done) { + * setTimeout(function() { + * order.push(1); + * done(null, 1); + * }, 10); + * }, + * function(done) { + * setTimeout(function() { + * order.push(2); + * done(null, 2); + * }, 50); + * }, + * function(done) { + * setTimeout(function() { + * order.push(3); + * done(null, 3); + * }, 30); + * }, + * function(done) { + * setTimeout(function() { + * order.push(4); + * done(null, 4); + * }, 40); + * } + * ]; + * async.parallelLimit(tasks, 2, function(err, res) { + * console.log(res); // [1, 2, 3, 4]; + * console.log(order); // [1, 3, 2, 4] + * }); + * + * @example + * + * var order = []; + * var tasks = { + * 'a': function(done) { + * setTimeout(function() { + * order.push(1); + * done(null, 1); + * }, 10); + * }, + * 'b': function(done) { + * setTimeout(function() { + * order.push(2); + * done(null, 2); + * }, 50); + * }, + * 'c': function(done) { + * setTimeout(function() { + * order.push(3); + * done(null, 3); + * }, 20); + * }, + * 'd': function(done) { + * setTimeout(function() { + * order.push(4); + * done(null, 4); + * }, 40); + * } + * }; + * async.parallelLimit(tasks, 2, function(err, res) { + * console.log(res); // { a: 1, b: 2, c: 3, d:4 } + * console.log(order); // [1, 3, 2, 4] + * }); + * + */ + function parallelLimit(tasks, limit, callback) { + callback = callback || noop; + var size, index, key, keys, result, iterate; + var sync = false; + var started = 0; + var completed = 0; + + if (isArray(tasks)) { + size = tasks.length; + result = Array(size); + iterate = arrayIterator; + } else if (tasks && typeof tasks === obj) { + keys = nativeKeys(tasks); + size = keys.length; + result = {}; + iterate = objectIterator; + } + if (!size || isNaN(limit) || limit < 1) { + return callback(null, result); + } + timesSync(limit > size ? size : limit, iterate); + + function arrayIterator() { + index = started++; + if (index < size) { + tasks[index](createCallback(index)); + } + } + + function objectIterator() { + if (started < size) { + key = keys[started++]; + tasks[key](createCallback(key)); + } + } + + function createCallback(key) { + return function(err, res) { + if (key === null) { + throwError(); + } + if (err) { + key = null; + iterate = noop; + callback = once(callback); + callback(err, result); + return; + } + result[key] = arguments.length <= 2 ? res : slice(arguments, 1); + key = null; + if (++completed === size) { + callback(null, result); + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + }; + } + } + + /** + * @memberof async + * @namespace tryEach + * @param {Array|Object} tasks - functions + * @param {Function} callback + * @example + * + * var tasks = [ + * function(done) { + * setTimeout(function() { + * done(new Error('error')); + * }, 10); + * }, + * function(done) { + * setTimeout(function() { + * done(null, 2); + * }, 10); + * } + * ]; + * async.tryEach(tasks, function(err, res) { + * console.log(res); // 2 + * }); + * + * @example + * + * var tasks = [ + * function(done) { + * setTimeout(function() { + * done(new Error('error1')); + * }, 10); + * }, + * function(done) { + * setTimeout(function() { + * done(new Error('error2'); + * }, 10); + * } + * ]; + * async.tryEach(tasks, function(err, res) { + * console.log(err); // error2 + * console.log(res); // undefined + * }); + * + */ + function tryEach(tasks, callback) { + callback = callback || noop; + var size, keys, iterate; + var sync = false; + var completed = 0; + + if (isArray(tasks)) { + size = tasks.length; + iterate = arrayIterator; + } else if (tasks && typeof tasks === obj) { + keys = nativeKeys(tasks); + size = keys.length; + iterate = objectIterator; + } + if (!size) { + return callback(null); + } + iterate(); + + function arrayIterator() { + tasks[completed](done); + } + + function objectIterator() { + tasks[keys[completed]](done); + } + + function done(err, res) { + if (!err) { + if (arguments.length <= 2) { + callback(null, res); + } else { + callback(null, slice(arguments, 1)); + } + } else if (++completed === size) { + callback(err); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * check for waterfall tasks + * @private + * @param {Array} tasks + * @param {Function} callback + * @return {boolean} + */ + function checkWaterfallTasks(tasks, callback) { + if (!isArray(tasks)) { + callback(new Error('First argument to waterfall must be an array of functions')); + return false; + } + if (tasks.length === 0) { + callback(null); + return false; + } + return true; + } + + /** + * check for waterfall tasks + * @private + * @param {function} func + * @param {Array|Object} args - arguments + * @return {function} next + */ + function waterfallIterator(func, args, next) { + switch (args.length) { + case 0: + case 1: + return func(next); + case 2: + return func(args[1], next); + case 3: + return func(args[1], args[2], next); + case 4: + return func(args[1], args[2], args[3], next); + case 5: + return func(args[1], args[2], args[3], args[4], next); + case 6: + return func(args[1], args[2], args[3], args[4], args[5], next); + default: + args = slice(args, 1); + args.push(next); + return func.apply(null, args); + } + } + + /** + * @memberof async + * @namespace waterfall + * @param {Array} tasks - functions + * @param {Function} callback + * @example + * + * var order = []; + * var tasks = [ + * function(next) { + * setTimeout(function() { + * order.push(1); + * next(null, 1); + * }, 10); + * }, + * function(arg1, next) { + * setTimeout(function() { + * order.push(2); + * next(null, 1, 2); + * }, 30); + * }, + * function(arg1, arg2, next) { + * setTimeout(function() { + * order.push(3); + * next(null, 3); + * }, 20); + * }, + * function(arg1, next) { + * setTimeout(function() { + * order.push(4); + * next(null, 1, 2, 3, 4); + * }, 40); + * } + * ]; + * async.waterfall(tasks, function(err, arg1, arg2, arg3, arg4) { + * console.log(arg1, arg2, arg3, arg4); // 1 2 3 4 + * }); + * + */ + function waterfall(tasks, callback) { + callback = callback || noop; + if (!checkWaterfallTasks(tasks, callback)) { + return; + } + var func, args, done, sync; + var completed = 0; + var size = tasks.length; + waterfallIterator(tasks[0], [], createCallback(0)); + + function iterate() { + waterfallIterator(func, args, createCallback(func)); + } + + function createCallback(index) { + return function next(err, res) { + if (index === undefined) { + callback = noop; + throwError(); + } + index = undefined; + if (err) { + done = callback; + callback = throwError; + done(err); + return; + } + if (++completed === size) { + done = callback; + callback = throwError; + if (arguments.length <= 2) { + done(err, res); + } else { + done.apply(null, createArray(arguments)); + } + return; + } + if (sync) { + args = arguments; + func = tasks[completed] || throwError; + nextTick(iterate); + } else { + sync = true; + waterfallIterator(tasks[completed] || throwError, arguments, createCallback(completed)); + } + sync = false; + }; + } + } + + /** + * `angelFall` is like `waterfall` and inject callback to last argument of next task. + * + * @memberof async + * @namespace angelFall + * @param {Array} tasks - functions + * @param {Function} callback + * @example + * + * var order = []; + * var tasks = [ + * function(next) { + * setTimeout(function() { + * order.push(1); + * next(null, 1); + * }, 10); + * }, + * function(arg1, empty, next) { + * setTimeout(function() { + * order.push(2); + * next(null, 1, 2); + * }, 30); + * }, + * function(next) { + * setTimeout(function() { + * order.push(3); + * next(null, 3); + * }, 20); + * }, + * function(arg1, empty1, empty2, empty3, next) { + * setTimeout(function() { + * order.push(4); + * next(null, 1, 2, 3, 4); + * }, 40); + * } + * ]; + * async.angelFall(tasks, function(err, arg1, arg2, arg3, arg4) { + * console.log(arg1, arg2, arg3, arg4); // 1 2 3 4 + * }); + * + */ + function angelFall(tasks, callback) { + callback = callback || noop; + if (!checkWaterfallTasks(tasks, callback)) { + return; + } + var completed = 0; + var sync = false; + var size = tasks.length; + var func = tasks[completed]; + var args = []; + var iterate = function() { + switch (func.length) { + case 0: + try { + next(null, func()); + } catch (e) { + next(e); + } + return; + case 1: + return func(next); + case 2: + return func(args[1], next); + case 3: + return func(args[1], args[2], next); + case 4: + return func(args[1], args[2], args[3], next); + case 5: + return func(args[1], args[2], args[3], args[4], next); + default: + args = slice(args, 1); + args[func.length - 1] = next; + return func.apply(null, args); + } + }; + iterate(); + + function next(err, res) { + if (err) { + iterate = throwError; + callback = onlyOnce(callback); + callback(err); + return; + } + if (++completed === size) { + iterate = throwError; + var done = callback; + callback = throwError; + if (arguments.length === 2) { + done(err, res); + } else { + done.apply(null, createArray(arguments)); + } + return; + } + func = tasks[completed]; + args = arguments; + if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace whilst + * @param {Function} test + * @param {Function} iterator + * @param {Function} callback + */ + function whilst(test, iterator, callback) { + callback = callback || noop; + var sync = false; + if (test()) { + iterate(); + } else { + callback(null); + } + + function iterate() { + if (sync) { + nextTick(next); + } else { + sync = true; + iterator(done); + } + sync = false; + } + + function next() { + iterator(done); + } + + function done(err, arg) { + if (err) { + return callback(err); + } + if (arguments.length <= 2) { + if (test(arg)) { + iterate(); + } else { + callback(null, arg); + } + return; + } + arg = slice(arguments, 1); + if (test.apply(null, arg)) { + iterate(); + } else { + callback.apply(null, [null].concat(arg)); + } + } + } + + /** + * @memberof async + * @namespace doWhilst + * @param {Function} iterator + * @param {Function} test + * @param {Function} callback + */ + function doWhilst(iterator, test, callback) { + callback = callback || noop; + var sync = false; + next(); + + function iterate() { + if (sync) { + nextTick(next); + } else { + sync = true; + iterator(done); + } + sync = false; + } + + function next() { + iterator(done); + } + + function done(err, arg) { + if (err) { + return callback(err); + } + if (arguments.length <= 2) { + if (test(arg)) { + iterate(); + } else { + callback(null, arg); + } + return; + } + arg = slice(arguments, 1); + if (test.apply(null, arg)) { + iterate(); + } else { + callback.apply(null, [null].concat(arg)); + } + } + } + + /** + * @memberof async + * @namespace until + * @param {Function} test + * @param {Function} iterator + * @param {Function} callback + */ + function until(test, iterator, callback) { + callback = callback || noop; + var sync = false; + if (!test()) { + iterate(); + } else { + callback(null); + } + + function iterate() { + if (sync) { + nextTick(next); + } else { + sync = true; + iterator(done); + } + sync = false; + } + + function next() { + iterator(done); + } + + function done(err, arg) { + if (err) { + return callback(err); + } + if (arguments.length <= 2) { + if (!test(arg)) { + iterate(); + } else { + callback(null, arg); + } + return; + } + arg = slice(arguments, 1); + if (!test.apply(null, arg)) { + iterate(); + } else { + callback.apply(null, [null].concat(arg)); + } + } + } + + /** + * @memberof async + * @namespace doUntil + * @param {Function} iterator + * @param {Function} test + * @param {Function} callback + */ + function doUntil(iterator, test, callback) { + callback = callback || noop; + var sync = false; + next(); + + function iterate() { + if (sync) { + nextTick(next); + } else { + sync = true; + iterator(done); + } + sync = false; + } + + function next() { + iterator(done); + } + + function done(err, arg) { + if (err) { + return callback(err); + } + if (arguments.length <= 2) { + if (!test(arg)) { + iterate(); + } else { + callback(null, arg); + } + return; + } + arg = slice(arguments, 1); + if (!test.apply(null, arg)) { + iterate(); + } else { + callback.apply(null, [null].concat(arg)); + } + } + } + + /** + * @memberof async + * @namespace during + * @param {Function} test + * @param {Function} iterator + * @param {Function} callback + */ + function during(test, iterator, callback) { + callback = callback || noop; + _test(); + + function _test() { + test(iterate); + } + + function iterate(err, truth) { + if (err) { + return callback(err); + } + if (truth) { + iterator(done); + } else { + callback(null); + } + } + + function done(err) { + if (err) { + return callback(err); + } + _test(); + } + } + + /** + * @memberof async + * @namespace doDuring + * @param {Function} test + * @param {Function} iterator + * @param {Function} callback + */ + function doDuring(iterator, test, callback) { + callback = callback || noop; + iterate(null, true); + + function iterate(err, truth) { + if (err) { + return callback(err); + } + if (truth) { + iterator(done); + } else { + callback(null); + } + } + + function done(err, res) { + if (err) { + return callback(err); + } + switch (arguments.length) { + case 0: + case 1: + test(iterate); + break; + case 2: + test(res, iterate); + break; + default: + var args = slice(arguments, 1); + args.push(iterate); + test.apply(null, args); + break; + } + } + } + + /** + * @memberof async + * @namespace forever + */ + function forever(iterator, callback) { + var sync = false; + iterate(); + + function iterate() { + iterator(next); + } + + function next(err) { + if (err) { + if (callback) { + return callback(err); + } + throw err; + } + if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace compose + */ + function compose() { + return seq.apply(null, reverse(arguments)); + } + + /** + * @memberof async + * @namespace seq + */ + function seq(/* functions... */) { + var fns = createArray(arguments); + + return function() { + var self = this; + var args = createArray(arguments); + var callback = args[args.length - 1]; + if (typeof callback === func) { + args.pop(); + } else { + callback = noop; + } + reduce(fns, args, iterator, done); + + function iterator(newargs, fn, callback) { + var func = function(err) { + var nextargs = slice(arguments, 1); + callback(err, nextargs); + }; + newargs.push(func); + fn.apply(self, newargs); + } + + function done(err, res) { + res = isArray(res) ? res : [res]; + res.unshift(err); + callback.apply(self, res); + } + }; + } + + function createApplyEach(func) { + return function applyEach(fns /* arguments */) { + var go = function() { + var self = this; + var args = createArray(arguments); + var callback = args.pop() || noop; + return func(fns, iterator, callback); + + function iterator(fn, done) { + fn.apply(self, args.concat([done])); + } + }; + if (arguments.length > 1) { + var args = slice(arguments, 1); + return go.apply(this, args); + } else { + return go; + } + }; + } + + /** + * @see https://github.com/caolan/async/blob/master/lib/internal/DoublyLinkedList.js + */ + function DLL() { + this.head = null; + this.tail = null; + this.length = 0; + } + + DLL.prototype._removeLink = function(node) { + var prev = node.prev; + var next = node.next; + if (prev) { + prev.next = next; + } else { + this.head = next; + } + if (next) { + next.prev = prev; + } else { + this.tail = prev; + } + node.prev = null; + node.next = null; + this.length--; + return node; + }; + + DLL.prototype.empty = DLL; + + DLL.prototype._setInitial = function(node) { + this.length = 1; + this.head = this.tail = node; + }; + + DLL.prototype.insertBefore = function(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) { + node.prev.next = newNode; + } else { + this.head = newNode; + } + node.prev = newNode; + this.length++; + }; + + DLL.prototype.unshift = function(node) { + if (this.head) { + this.insertBefore(this.head, node); + } else { + this._setInitial(node); + } + }; + + DLL.prototype.push = function(node) { + var tail = this.tail; + if (tail) { + node.prev = tail; + node.next = tail.next; + this.tail = node; + tail.next = node; + this.length++; + } else { + this._setInitial(node); + } + }; + + DLL.prototype.shift = function() { + return this.head && this._removeLink(this.head); + }; + + DLL.prototype.splice = function(end) { + var task; + var tasks = []; + while (end-- && (task = this.shift())) { + tasks.push(task); + } + return tasks; + }; + + DLL.prototype.remove = function(test) { + var node = this.head; + while (node) { + if (test(node)) { + this._removeLink(node); + } + node = node.next; + } + return this; + }; + + /** + * @private + */ + function baseQueue(isQueue, worker, concurrency, payload) { + if (concurrency === undefined) { + concurrency = 1; + } else if (isNaN(concurrency) || concurrency < 1) { + throw new Error('Concurrency must not be zero'); + } + + var workers = 0; + var workersList = []; + var _callback, _unshift; + + var q = { + _tasks: new DLL(), + concurrency: concurrency, + payload: payload, + saturated: noop, + unsaturated: noop, + buffer: concurrency / 4, + empty: noop, + drain: noop, + error: noop, + started: false, + paused: false, + push: push, + kill: kill, + unshift: unshift, + remove: remove, + process: isQueue ? runQueue : runCargo, + length: getLength, + running: running, + workersList: getWorkersList, + idle: idle, + pause: pause, + resume: resume, + _worker: worker + }; + return q; + + function push(tasks, callback) { + _insert(tasks, callback); + } + + function unshift(tasks, callback) { + _insert(tasks, callback, true); + } + + function _exec(task) { + var item = { + data: task, + callback: _callback + }; + if (_unshift) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + nextTick(q.process); + } + + function _insert(tasks, callback, unshift) { + if (callback == null) { + callback = noop; + } else if (typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + var _tasks = isArray(tasks) ? tasks : [tasks]; + + if (tasks === undefined || !_tasks.length) { + if (q.idle()) { + nextTick(q.drain); + } + return; + } + + _unshift = unshift; + _callback = callback; + arrayEachSync(_tasks, _exec); + // Avoid leaking the callback + _callback = undefined; + } + + function kill() { + q.drain = noop; + q._tasks.empty(); + } + + function _next(q, tasks) { + var called = false; + return function done(err, res) { + if (called) { + throwError(); + } + called = true; + + workers--; + var task; + var index = -1; + var size = workersList.length; + var taskIndex = -1; + var taskSize = tasks.length; + var useApply = arguments.length > 2; + var args = useApply && createArray(arguments); + while (++taskIndex < taskSize) { + task = tasks[taskIndex]; + while (++index < size) { + if (workersList[index] === task) { + if (index === 0) { + workersList.shift(); + } else { + workersList.splice(index, 1); + } + index = size; + size--; + } + } + index = -1; + if (useApply) { + task.callback.apply(task, args); + } else { + task.callback(err, res); + } + if (err) { + q.error(err, task.data); + } + } + + if (workers <= q.concurrency - q.buffer) { + q.unsaturated(); + } + + if (q._tasks.length + workers === 0) { + q.drain(); + } + q.process(); + }; + } + + function runQueue() { + while (!q.paused && workers < q.concurrency && q._tasks.length) { + var task = q._tasks.shift(); + workers++; + workersList.push(task); + if (q._tasks.length === 0) { + q.empty(); + } + if (workers === q.concurrency) { + q.saturated(); + } + var done = _next(q, [task]); + worker(task.data, done); + } + } + + function runCargo() { + while (!q.paused && workers < q.concurrency && q._tasks.length) { + var tasks = q._tasks.splice(q.payload || q._tasks.length); + var index = -1; + var size = tasks.length; + var data = Array(size); + while (++index < size) { + data[index] = tasks[index].data; + } + workers++; + nativePush.apply(workersList, tasks); + if (q._tasks.length === 0) { + q.empty(); + } + if (workers === q.concurrency) { + q.saturated(); + } + var done = _next(q, tasks); + worker(data, done); + } + } + + function getLength() { + return q._tasks.length; + } + + function running() { + return workers; + } + + function getWorkersList() { + return workersList; + } + + function idle() { + return q.length() + workers === 0; + } + + function pause() { + q.paused = true; + } + + function _resume() { + nextTick(q.process); + } + + function resume() { + if (q.paused === false) { + return; + } + q.paused = false; + var count = q.concurrency < q._tasks.length ? q.concurrency : q._tasks.length; + timesSync(count, _resume); + } + + /** + * @param {Function} test + */ + function remove(test) { + q._tasks.remove(test); + } + } + + /** + * @memberof async + * @namespace queue + */ + function queue(worker, concurrency) { + return baseQueue(true, worker, concurrency); + } + + /** + * @memberof async + * @namespace priorityQueue + */ + function priorityQueue(worker, concurrency) { + var q = baseQueue(true, worker, concurrency); + q.push = push; + delete q.unshift; + return q; + + function push(tasks, priority, callback) { + q.started = true; + priority = priority || 0; + var _tasks = isArray(tasks) ? tasks : [tasks]; + var taskSize = _tasks.length; + + if (tasks === undefined || taskSize === 0) { + if (q.idle()) { + nextTick(q.drain); + } + return; + } + + callback = typeof callback === func ? callback : noop; + var nextNode = q._tasks.head; + while (nextNode && priority >= nextNode.priority) { + nextNode = nextNode.next; + } + while (taskSize--) { + var item = { + data: _tasks[taskSize], + priority: priority, + callback: callback + }; + if (nextNode) { + q._tasks.insertBefore(nextNode, item); + } else { + q._tasks.push(item); + } + nextTick(q.process); + } + } + } + + /** + * @memberof async + * @namespace cargo + */ + function cargo(worker, payload) { + return baseQueue(false, worker, 1, payload); + } + + /** + * @memberof async + * @namespace auto + * @param {Object} tasks + * @param {number} [concurrency] + * @param {Function} [callback] + */ + function auto(tasks, concurrency, callback) { + if (typeof concurrency === func) { + callback = concurrency; + concurrency = null; + } + var keys = nativeKeys(tasks); + var rest = keys.length; + var results = {}; + if (rest === 0) { + return callback(null, results); + } + var runningTasks = 0; + var readyTasks = new DLL(); + var listeners = Object.create(null); + callback = onlyOnce(callback || noop); + concurrency = concurrency || rest; + + baseEachSync(tasks, iterator, keys); + proceedQueue(); + + function iterator(task, key) { + // no dependencies + var _task, _taskSize; + if (!isArray(task)) { + _task = task; + _taskSize = 0; + readyTasks.push([_task, _taskSize, done]); + return; + } + var dependencySize = task.length - 1; + _task = task[dependencySize]; + _taskSize = dependencySize; + if (dependencySize === 0) { + readyTasks.push([_task, _taskSize, done]); + return; + } + // dependencies + var index = -1; + while (++index < dependencySize) { + var dependencyName = task[index]; + if (notInclude(keys, dependencyName)) { + var msg = + 'async.auto task `' + + key + + '` has non-existent dependency `' + + dependencyName + + '` in ' + + task.join(', '); + throw new Error(msg); + } + var taskListeners = listeners[dependencyName]; + if (!taskListeners) { + taskListeners = listeners[dependencyName] = []; + } + taskListeners.push(taskListener); + } + + function done(err, arg) { + if (key === null) { + throwError(); + } + arg = arguments.length <= 2 ? arg : slice(arguments, 1); + if (err) { + rest = 0; + runningTasks = 0; + readyTasks.length = 0; + var safeResults = objectClone(results); + safeResults[key] = arg; + key = null; + var _callback = callback; + callback = noop; + _callback(err, safeResults); + return; + } + runningTasks--; + rest--; + results[key] = arg; + taskComplete(key); + key = null; + } + + function taskListener() { + if (--dependencySize === 0) { + readyTasks.push([_task, _taskSize, done]); + } + } + } + + function proceedQueue() { + if (readyTasks.length === 0 && runningTasks === 0) { + if (rest !== 0) { + throw new Error('async.auto task has cyclic dependencies'); + } + return callback(null, results); + } + while (readyTasks.length && runningTasks < concurrency && callback !== noop) { + runningTasks++; + var array = readyTasks.shift(); + if (array[1] === 0) { + array[0](array[2]); + } else { + array[0](results, array[2]); + } + } + } + + function taskComplete(key) { + var taskListeners = listeners[key] || []; + arrayEachSync(taskListeners, function(task) { + task(); + }); + proceedQueue(); + } + } + + var FN_ARGS = /^(function)?\s*[^\(]*\(\s*([^\)]*)\)/m; + var FN_ARG_SPLIT = /,/; + var FN_ARG = /(=.+)?(\s*)$/; + var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm; + + /** + * parse function arguments for `autoInject` + * + * @private + */ + function parseParams(func) { + func = func.toString().replace(STRIP_COMMENTS, ''); + func = func.match(FN_ARGS)[2].replace(' ', ''); + func = func ? func.split(FN_ARG_SPLIT) : []; + func = func.map(function(arg) { + return arg.replace(FN_ARG, '').trim(); + }); + return func; + } + + /** + * @memberof async + * @namespace autoInject + * @param {Object} tasks + * @param {number} [concurrency] + * @param {Function} [callback] + */ + function autoInject(tasks, concurrency, callback) { + var newTasks = {}; + baseEachSync(tasks, iterator, nativeKeys(tasks)); + auto(newTasks, concurrency, callback); + + function iterator(task, key) { + var params; + var taskLength = task.length; + + if (isArray(task)) { + if (taskLength === 0) { + throw new Error('autoInject task functions require explicit parameters.'); + } + params = createArray(task); + taskLength = params.length - 1; + task = params[taskLength]; + if (taskLength === 0) { + newTasks[key] = task; + return; + } + } else if (taskLength === 1) { + newTasks[key] = task; + return; + } else { + params = parseParams(task); + if (taskLength === 0 && params.length === 0) { + throw new Error('autoInject task functions require explicit parameters.'); + } + taskLength = params.length - 1; + } + params[taskLength] = newTask; + newTasks[key] = params; + + function newTask(results, done) { + switch (taskLength) { + case 1: + task(results[params[0]], done); + break; + case 2: + task(results[params[0]], results[params[1]], done); + break; + case 3: + task(results[params[0]], results[params[1]], results[params[2]], done); + break; + default: + var i = -1; + while (++i < taskLength) { + params[i] = results[params[i]]; + } + params[i] = done; + task.apply(null, params); + break; + } + } + } + } + + /** + * @memberof async + * @namespace retry + * @param {integer|Object|Function} opts + * @param {Function} [task] + * @param {Function} [callback] + */ + function retry(opts, task, callback) { + var times, intervalFunc, errorFilter; + var count = 0; + if (arguments.length < 3 && typeof opts === func) { + callback = task || noop; + task = opts; + opts = null; + times = DEFAULT_TIMES; + } else { + callback = callback || noop; + switch (typeof opts) { + case 'object': + if (typeof opts.errorFilter === func) { + errorFilter = opts.errorFilter; + } + var interval = opts.interval; + switch (typeof interval) { + case func: + intervalFunc = interval; + break; + case 'string': + case 'number': + interval = +interval; + intervalFunc = interval + ? function() { + return interval; + } + : function() { + return DEFAULT_INTERVAL; + }; + break; + } + times = +opts.times || DEFAULT_TIMES; + break; + case 'number': + times = opts || DEFAULT_TIMES; + break; + case 'string': + times = +opts || DEFAULT_TIMES; + break; + default: + throw new Error('Invalid arguments for async.retry'); + } + } + if (typeof task !== 'function') { + throw new Error('Invalid arguments for async.retry'); + } + + if (intervalFunc) { + task(intervalCallback); + } else { + task(simpleCallback); + } + + function simpleIterator() { + task(simpleCallback); + } + + function simpleCallback(err, res) { + if (++count === times || !err || (errorFilter && !errorFilter(err))) { + if (arguments.length <= 2) { + return callback(err, res); + } + var args = createArray(arguments); + return callback.apply(null, args); + } + simpleIterator(); + } + + function intervalIterator() { + task(intervalCallback); + } + + function intervalCallback(err, res) { + if (++count === times || !err || (errorFilter && !errorFilter(err))) { + if (arguments.length <= 2) { + return callback(err, res); + } + var args = createArray(arguments); + return callback.apply(null, args); + } + setTimeout(intervalIterator, intervalFunc(count)); + } + } + + function retryable(opts, task) { + if (!task) { + task = opts; + opts = null; + } + return done; + + function done() { + var taskFn; + var args = createArray(arguments); + var lastIndex = args.length - 1; + var callback = args[lastIndex]; + switch (task.length) { + case 1: + taskFn = task1; + break; + case 2: + taskFn = task2; + break; + case 3: + taskFn = task3; + break; + default: + taskFn = task4; + } + if (opts) { + retry(opts, taskFn, callback); + } else { + retry(taskFn, callback); + } + + function task1(done) { + task(done); + } + + function task2(done) { + task(args[0], done); + } + + function task3(done) { + task(args[0], args[1], done); + } + + function task4(callback) { + args[lastIndex] = callback; + task.apply(null, args); + } + } + } + + /** + * @memberof async + * @namespace iterator + */ + function iterator(tasks) { + var size = 0; + var keys = []; + if (isArray(tasks)) { + size = tasks.length; + } else { + keys = nativeKeys(tasks); + size = keys.length; + } + return makeCallback(0); + + function makeCallback(index) { + var fn = function() { + if (size) { + var key = keys[index] || index; + tasks[key].apply(null, createArray(arguments)); + } + return fn.next(); + }; + fn.next = function() { + return index < size - 1 ? makeCallback(index + 1) : null; + }; + return fn; + } + } + + /** + * @memberof async + * @namespace apply + */ + function apply(func) { + switch (arguments.length) { + case 0: + case 1: + return func; + case 2: + return func.bind(null, arguments[1]); + case 3: + return func.bind(null, arguments[1], arguments[2]); + case 4: + return func.bind(null, arguments[1], arguments[2], arguments[3]); + case 5: + return func.bind(null, arguments[1], arguments[2], arguments[3], arguments[4]); + default: + var size = arguments.length; + var index = 0; + var args = Array(size); + args[index] = null; + while (++index < size) { + args[index] = arguments[index]; + } + return func.bind.apply(func, args); + } + } + + /** + * @memberof async + * @namespace timeout + * @param {Function} func + * @param {number} millisec + * @param {*} info + */ + function timeout(func, millisec, info) { + var callback, timer; + return wrappedFunc; + + function wrappedFunc() { + timer = setTimeout(timeoutCallback, millisec); + var args = createArray(arguments); + var lastIndex = args.length - 1; + callback = args[lastIndex]; + args[lastIndex] = injectedCallback; + simpleApply(func, args); + } + + function timeoutCallback() { + var name = func.name || 'anonymous'; + var err = new Error('Callback function "' + name + '" timed out.'); + err.code = 'ETIMEDOUT'; + if (info) { + err.info = info; + } + timer = null; + callback(err); + } + + function injectedCallback() { + if (timer !== null) { + simpleApply(callback, createArray(arguments)); + clearTimeout(timer); + } + } + + function simpleApply(func, args) { + switch (args.length) { + case 0: + func(); + break; + case 1: + func(args[0]); + break; + case 2: + func(args[0], args[1]); + break; + default: + func.apply(null, args); + break; + } + } + } + + /** + * @memberof async + * @namespace times + * @param {number} n - n >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * var iterator = function(n, done) { + * done(null, n); + * }; + * async.times(4, iterator, function(err, res) { + * console.log(res); // [0, 1, 2, 3]; + * }); + * + */ + function times(n, iterator, callback) { + callback = callback || noop; + n = +n; + if (isNaN(n) || n < 1) { + return callback(null, []); + } + var result = Array(n); + timesSync(n, iterate); + + function iterate(num) { + iterator(num, createCallback(num)); + } + + function createCallback(index) { + return function(err, res) { + if (index === null) { + throwError(); + } + result[index] = res; + index = null; + if (err) { + callback(err); + callback = noop; + } else if (--n === 0) { + callback(null, result); + } + }; + } + } + + /** + * @memberof async + * @namespace timesSeries + * @param {number} n - n >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * var iterator = function(n, done) { + * done(null, n); + * }; + * async.timesSeries(4, iterator, function(err, res) { + * console.log(res); // [0, 1, 2, 3]; + * }); + * + */ + function timesSeries(n, iterator, callback) { + callback = callback || noop; + n = +n; + if (isNaN(n) || n < 1) { + return callback(null, []); + } + var result = Array(n); + var sync = false; + var completed = 0; + iterate(); + + function iterate() { + iterator(completed, done); + } + + function done(err, res) { + result[completed] = res; + if (err) { + callback(err); + callback = throwError; + } else if (++completed >= n) { + callback(null, result); + callback = throwError; + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + } + } + + /** + * @memberof async + * @namespace timesLimit + * @param {number} n - n >= 1 + * @param {number} limit - n >= 1 + * @param {Function} iterator + * @param {Function} callback + * @example + * + * var iterator = function(n, done) { + * done(null, n); + * }; + * async.timesLimit(4, 2, iterator, function(err, res) { + * console.log(res); // [0, 1, 2, 3]; + * }); + * + */ + function timesLimit(n, limit, iterator, callback) { + callback = callback || noop; + n = +n; + if (isNaN(n) || n < 1 || isNaN(limit) || limit < 1) { + return callback(null, []); + } + var result = Array(n); + var sync = false; + var started = 0; + var completed = 0; + timesSync(limit > n ? n : limit, iterate); + + function iterate() { + var index = started++; + if (index < n) { + iterator(index, createCallback(index)); + } + } + + function createCallback(index) { + return function(err, res) { + if (index === null) { + throwError(); + } + result[index] = res; + index = null; + if (err) { + callback(err); + callback = noop; + } else if (++completed >= n) { + callback(null, result); + callback = throwError; + } else if (sync) { + nextTick(iterate); + } else { + sync = true; + iterate(); + } + sync = false; + }; + } + } + + /** + * @memberof async + * @namespace race + * @param {Array|Object} tasks - functions + * @param {Function} callback + * @example + * + * // array + * var called = 0; + * var tasks = [ + * function(done) { + * setTimeout(function() { + * called++; + * done(null, '1'); + * }, 30); + * }, + * function(done) { + * setTimeout(function() { + * called++; + * done(null, '2'); + * }, 20); + * }, + * function(done) { + * setTimeout(function() { + * called++; + * done(null, '3'); + * }, 10); + * } + * ]; + * async.race(tasks, function(err, res) { + * console.log(res); // '3' + * console.log(called); // 1 + * setTimeout(function() { + * console.log(called); // 3 + * }, 50); + * }); + * + * @example + * + * // object + * var called = 0; + * var tasks = { + * 'test1': function(done) { + * setTimeout(function() { + * called++; + * done(null, '1'); + * }, 30); + * }, + * 'test2': function(done) { + * setTimeout(function() { + * called++; + * done(null, '2'); + * }, 20); + * }, + * 'test3': function(done) { + * setTimeout(function() { + * called++; + * done(null, '3'); + * }, 10); + * } + * }; + * async.race(tasks, function(err, res) { + * console.log(res); // '3' + * console.log(called); // 1 + * setTimeout(function() { + * console.log(called); // 3 + * done(); + * }, 50); + * }); + * + */ + function race(tasks, callback) { + callback = once(callback || noop); + var size, keys; + var index = -1; + if (isArray(tasks)) { + size = tasks.length; + while (++index < size) { + tasks[index](callback); + } + } else if (tasks && typeof tasks === obj) { + keys = nativeKeys(tasks); + size = keys.length; + while (++index < size) { + tasks[keys[index]](callback); + } + } else { + return callback(new TypeError('First argument to race must be a collection of functions')); + } + if (!size) { + callback(null); + } + } + + /** + * @memberof async + * @namespace memoize + */ + function memoize(fn, hasher) { + hasher = + hasher || + function(hash) { + return hash; + }; + + var memo = {}; + var queues = {}; + var memoized = function() { + var args = createArray(arguments); + var callback = args.pop(); + var key = hasher.apply(null, args); + if (has(memo, key)) { + nextTick(function() { + callback.apply(null, memo[key]); + }); + return; + } + if (has(queues, key)) { + return queues[key].push(callback); + } + + queues[key] = [callback]; + args.push(done); + fn.apply(null, args); + + function done(err) { + var args = createArray(arguments); + if (!err) { + memo[key] = args; + } + var q = queues[key]; + delete queues[key]; + + var i = -1; + var size = q.length; + while (++i < size) { + q[i].apply(null, args); + } + } + }; + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; + } + + /** + * @memberof async + * @namespace unmemoize + */ + function unmemoize(fn) { + return function() { + return (fn.unmemoized || fn).apply(null, arguments); + }; + } + + /** + * @memberof async + * @namespace ensureAsync + */ + function ensureAsync(fn) { + return function(/* ...args, callback */) { + var args = createArray(arguments); + var lastIndex = args.length - 1; + var callback = args[lastIndex]; + var sync = true; + args[lastIndex] = done; + fn.apply(this, args); + sync = false; + + function done() { + var innerArgs = createArray(arguments); + if (sync) { + nextTick(function() { + callback.apply(null, innerArgs); + }); + } else { + callback.apply(null, innerArgs); + } + } + }; + } + + /** + * @memberof async + * @namespace constant + */ + function constant(/* values... */) { + var args = [null].concat(createArray(arguments)); + return function(callback) { + callback = arguments[arguments.length - 1]; + callback.apply(this, args); + }; + } + + function asyncify(fn) { + return function(/* args..., callback */) { + var args = createArray(arguments); + var callback = args.pop(); + var result; + try { + result = fn.apply(this, args); + } catch (e) { + return callback(e); + } + if (result && typeof result.then === func) { + result.then( + function(value) { + invokeCallback(callback, null, value); + }, + function(err) { + invokeCallback(callback, err && err.message ? err : new Error(err)); + } + ); + } else { + callback(null, result); + } + }; + } + + function invokeCallback(callback, err, value) { + try { + callback(err, value); + } catch (e) { + nextTick(rethrow, e); + } + } + + function rethrow(error) { + throw error; + } + + /** + * @memberof async + * @namespace reflect + * @param {Function} func + * @return {Function} + */ + function reflect(func) { + return function(/* args..., callback */) { + var callback; + switch (arguments.length) { + case 1: + callback = arguments[0]; + return func(done); + case 2: + callback = arguments[1]; + return func(arguments[0], done); + default: + var args = createArray(arguments); + var lastIndex = args.length - 1; + callback = args[lastIndex]; + args[lastIndex] = done; + func.apply(this, args); + } + + function done(err, res) { + if (err) { + return callback(null, { + error: err + }); + } + if (arguments.length > 2) { + res = slice(arguments, 1); + } + callback(null, { + value: res + }); + } + }; + } + + /** + * @memberof async + * @namespace reflectAll + * @param {Array[]|Object} tasks + * @return {Function} + */ + function reflectAll(tasks) { + var newTasks, keys; + if (isArray(tasks)) { + newTasks = Array(tasks.length); + arrayEachSync(tasks, iterate); + } else if (tasks && typeof tasks === obj) { + keys = nativeKeys(tasks); + newTasks = {}; + baseEachSync(tasks, iterate, keys); + } + return newTasks; + + function iterate(func, key) { + newTasks[key] = reflect(func); + } + } + + /** + * @memberof async + * @namespace createLogger + */ + function createLogger(name) { + return function(fn) { + var args = slice(arguments, 1); + args.push(done); + fn.apply(null, args); + }; + + function done(err) { + if (typeof console === obj) { + if (err) { + if (console.error) { + console.error(err); + } + return; + } + if (console[name]) { + var args = slice(arguments, 1); + arrayEachSync(args, function(arg) { + console[name](arg); + }); + } + } + } + } + + /** + * @memberof async + * @namespace safe + */ + function safe() { + createImmediate(); + return exports; + } + + /** + * @memberof async + * @namespace fast + */ + function fast() { + createImmediate(false); + return exports; + } +}); diff --git a/node_modules/neo-async/async.min.js b/node_modules/neo-async/async.min.js new file mode 100644 index 0000000..4161a3f --- /dev/null +++ b/node_modules/neo-async/async.min.js @@ -0,0 +1,80 @@ +(function(N,O){"object"===typeof exports&&"undefined"!==typeof module?O(exports):"function"===typeof define&&define.amd?define(["exports"],O):N.async?O(N.neo_async=N.neo_async||{}):O(N.async=N.async||{})})(this,function(N){function O(a){var c=function(a){var d=J(arguments,1);setTimeout(function(){a.apply(null,d)})};T="function"===typeof setImmediate?setImmediate:c;"object"===typeof process&&"function"===typeof process.nextTick?(D=/^v0.10/.test(process.version)?T:process.nextTick,ba=/^v0/.test(process.version)? +T:process.nextTick):ba=D=T;!1===a&&(D=function(a){a()})}function H(a){for(var c=-1,b=a.length,d=Array(b);++c=d)return[];for(var e=Array(d);++bd[e]){var g=d[f]; +d[f]=d[e];d[e]=g}}if(!(e>b)){for(var l,e=a[a[c]>a[e]?c:e],f=c,g=b;f<=g;){for(l=f;f=l&&a[g]>=e;)g--;if(f>g)break;var q=a;l=d;var s=f++,h=g--,k=q[s];q[s]=q[h];q[h]=k;q=l[s];l[s]=l[h];l[h]=q}e=f;ca(a,c,e-1,d);ca(a,e,b,d)}}}function S(a){var c=[];Q(a,function(a){a!==w&&(C(a)?X.apply(c,a):c.push(a))});return c}function da(a,c,b){var d=-1,e=a.length;if(3===c.length)for(;++db)return e(null,[]);y=y||Array(m);K(b>m?m:b,x)}}function Y(a,c,b){function d(){c(a[v],s)}function e(){c(a[v],v,s)}function f(){n=r.next();n.done?b(null):c(n.value,s)}function g(){n=r.next();n.done?b(null):c(n.value,v,s)}function l(){c(a[m[v]],s)}function q(){k=m[v];c(a[k],k,s)}function s(a,d){a?b(a):++v===h||!1===d?(p=A,b(null)):u?D(p): +(u=!0,p());u=!1}b=E(b||w);var h,k,m,r,n,p,u=!1,v=0;C(a)?(h=a.length,p=3===c.length?e:d):a&&(z&&a[z]?(h=Infinity,r=a[z](),p=3===c.length?g:f):"object"===typeof a&&(m=F(a),h=m.length,p=3===c.length?q:l));if(!h)return b(null);p()}function Z(a,c,b,d){function e(){xc)return d(null);K(c>k?k:c,v)}function za(a,c,b){function d(){c(a[t],s)}function e(){c(a[t],t,s)}function f(){n=r.next(); +n.done?b(null,p):c(n.value,s)}function g(){n=r.next();n.done?b(null,p):c(n.value,t,s)}function l(){c(a[m[t]],s)}function q(){k=m[t];c(a[k],k,s)}function s(a,d){a?(u=A,b=E(b),b(a,H(p))):(p[t]=d,++t===h?(u=A,b(null,p),b=A):v?D(u):(v=!0,u()),v=!1)}b=b||w;var h,k,m,r,n,p,u,v=!1,t=0;C(a)?(h=a.length,u=3===c.length?e:d):a&&(z&&a[z]?(h=Infinity,p=[],r=a[z](),u=3===c.length?g:f):"object"===typeof a&&(m=F(a),h=m.length,u=3===c.length?q:l));if(!h)return b(null,[]);p=p||Array(h);u()}function Aa(a,c,b,d){return function(e, +f,g){function l(a){var b=!1;return function(c,e){b&&A();b=!0;c?(g=I(g),g(c)):!!e===d?(g=I(g),g(null,a)):++h===q&&g(null)}}g=g||w;var q,s,h=0;C(e)?(q=e.length,a(e,f,l)):e&&(z&&e[z]?(q=b(e,f,l))&&q===h&&g(null):"object"===typeof e&&(s=F(e),q=s.length,c(e,f,l,s)));q||g(null)}}function Ba(a){return function(c,b,d){function e(){r=c[x];b(r,h)}function f(){r=c[x];b(r,x,h)}function g(){u=p.next();r=u.value;u.done?d(null):b(r,h)}function l(){u=p.next();r=u.value;u.done?d(null):b(r,x,h)}function q(){r=c[n[x]]; +b(r,h)}function s(){m=n[x];r=c[m];b(r,m,h)}function h(b,c){b?d(b):!!c===a?(v=A,d(null,r)):++x===k?(v=A,d(null)):t?D(v):(t=!0,v());t=!1}d=E(d||w);var k,m,r,n,p,u,v,t=!1,x=0;C(c)?(k=c.length,v=3===b.length?f:e):c&&(z&&c[z]?(k=Infinity,p=c[z](),v=3===b.length?l:g):"object"===typeof c&&(n=F(c),k=n.length,v=3===b.length?s:q));if(!k)return d(null);v()}}function Ca(a){return function(c,b,d,e){function f(){r=G++;rb)return e(null);K(b>m?m:b,x)}}function Da(a,c,b,d){return function(e,f,g){function l(a,b){return function(c,e){null===a&&A();c?(a=null,g=I(g),g(c,L(k))):(!!e===d&&(k[a]=b),a=null,++h===q&&g(null,k))}}g=g||w;var q,s,h=0,k={};C(e)?(q=e.length,a(e,f,l)):e&&(z&&e[z]?(q=b(e,f,l))&&q===h&&g(null,k):"object"===typeof e&&(s=F(e),q=s.length,c(e,f,l,s)));if(!q)return g(null,{})}}function Ea(a){return function(c, +b,d){function e(){m=y;r=c[y];b(r,h)}function f(){m=y;r=c[y];b(r,y,h)}function g(){m=y;u=p.next();r=u.value;u.done?d(null,x):b(r,h)}function l(){m=y;u=p.next();r=u.value;u.done?d(null,x):b(r,m,h)}function q(){m=n[y];r=c[m];b(r,h)}function s(){m=n[y];r=c[m];b(r,m,h)}function h(b,c){b?d(b,x):(!!c===a&&(x[m]=r),++y===k?(v=A,d(null,x)):t?D(v):(t=!0,v()),t=!1)}d=E(d||w);var k,m,r,n,p,u,v,t=!1,x={},y=0;C(c)?(k=c.length,v=3===b.length?f:e):c&&(z&&c[z]?(k=Infinity,p=c[z](),v=3===b.length?l:g):"object"===typeof c&& +(n=F(c),k=n.length,v=3===b.length?s:q));if(!k)return d(null,{});v()}}function Fa(a){return function(c,b,d,e){function f(){r=B++;rb)return e(null,{});K(b>m?m:b,x)}}function $(a,c,b,d){function e(d){b(d,a[t],h)}function f(d){b(d,a[t],t,h)}function g(a){p=n.next();p.done?d(null,a):b(a,p.value, +h)}function l(a){p=n.next();p.done?d(null,a):b(a,p.value,t,h)}function q(d){b(d,a[r[t]],h)}function s(d){m=r[t];b(d,a[m],m,h)}function h(a,c){a?d(a,c):++t===k?(b=A,d(null,c)):v?D(function(){u(c)}):(v=!0,u(c));v=!1}d=E(d||w);var k,m,r,n,p,u,v=!1,t=0;C(a)?(k=a.length,u=4===b.length?f:e):a&&(z&&a[z]?(k=Infinity,n=a[z](),u=4===b.length?l:g):"object"===typeof a&&(r=F(a),k=r.length,u=4===b.length?s:q));if(!k)return d(null,c);u(c)}function Ga(a,c,b,d){function e(d){b(d,a[--s],q)}function f(d){b(d,a[--s], +s,q)}function g(d){b(d,a[m[--s]],q)}function l(d){k=m[--s];b(d,a[k],k,q)}function q(a,b){a?d(a,b):0===s?(u=A,d(null,b)):v?D(function(){u(b)}):(v=!0,u(b));v=!1}d=E(d||w);var s,h,k,m,r,n,p,u,v=!1;if(C(a))s=a.length,u=4===b.length?f:e;else if(a)if(z&&a[z]){p=[];r=a[z]();for(h=-1;!1===(n=r.next()).done;)p[++h]=n.value;a=p;s=p.length;u=4===b.length?f:e}else"object"===typeof a&&(m=F(a),s=m.length,u=4===b.length?l:g);if(!s)return d(null,c);u(c)}function Ha(a,c,b){b=b||w;ja(a,c,function(a,c){if(a)return b(a); +b(null,!!c)})}function Ia(a,c,b){b=b||w;ka(a,c,function(a,c){if(a)return b(a);b(null,!!c)})}function Ja(a,c,b,d){d=d||w;la(a,c,b,function(a,b){if(a)return d(a);d(null,!!b)})}function Ka(a,c){return C(a)?0===a.length?(c(null),!1):!0:(c(Error("First argument to waterfall must be an array of functions")),!1)}function ma(a,c,b){switch(c.length){case 0:case 1:return a(b);case 2:return a(c[1],b);case 3:return a(c[1],c[2],b);case 4:return a(c[1],c[2],c[3],b);case 5:return a(c[1],c[2],c[3],c[4],b);case 6:return a(c[1], +c[2],c[3],c[4],c[5],b);default:return c=J(c,1),c.push(b),a.apply(null,c)}}function La(a,c){function b(b,h){if(b)q=A,c=E(c),c(b);else if(++d===f){q=A;var k=c;c=A;2===arguments.length?k(b,h):k.apply(null,H(arguments))}else g=a[d],l=arguments,e?D(q):(e=!0,q()),e=!1}c=c||w;if(Ka(a,c)){var d=0,e=!1,f=a.length,g=a[d],l=[],q=function(){switch(g.length){case 0:try{b(null,g())}catch(a){b(a)}break;case 1:return g(b);case 2:return g(l[1],b);case 3:return g(l[1],l[2],b);case 4:return g(l[1],l[2],l[3],b);case 5:return g(l[1], +l[2],l[3],l[4],b);default:return l=J(l,1),l[g.length-1]=b,g.apply(null,l)}};q()}}function Ma(){var a=H(arguments);return function(){var c=this,b=H(arguments),d=b[b.length-1];"function"===typeof d?b.pop():d=w;$(a,b,function(a,b,d){a.push(function(a){var b=J(arguments,1);d(a,b)});b.apply(c,a)},function(a,b){b=C(b)?b:[b];b.unshift(a);d.apply(c,b)})}}function Na(a){return function(c){var b=function(){var b=this,d=H(arguments),g=d.pop()||w;return a(c,function(a,c){a.apply(b,d.concat([c]))},g)};if(1b)throw Error("Concurrency must not be zero");var h=0,k=[],m,r,n={_tasks:new M,concurrency:b,payload:d,saturated:w,unsaturated:w,buffer:b/4,empty:w,drain:w,error:w,started:!1,paused:!1,push:function(a, +b){f(a,b)},kill:function(){n.drain=w;n._tasks.empty()},unshift:function(a,b){f(a,b,!0)},remove:function(a){n._tasks.remove(a)},process:a?l:q,length:function(){return n._tasks.length},running:function(){return h},workersList:function(){return k},idle:function(){return 0===n.length()+h},pause:function(){n.paused=!0},resume:function(){!1!==n.paused&&(n.paused=!1,K(n.concurrency=arguments.length?f:J(arguments,1);if(a){q=g=0;s.length=0;var k=L(l);k[d]=f;d=null;var h= +b;b=w;h(a,k)}else q--,g--,l[d]=f,e(d),d=null}function n(){0===--v&&s.push([p,u,c])}var p,u;if(C(a)){var v=a.length-1;p=a[v];u=v;if(0===v)s.push([p,u,c]);else for(var t=-1;++t=arguments.length)return b(a,e);var f=H(arguments);return b.apply(null,f)}c(d)}function e(){c(f)}function f(a,d){if(++s===g||!a||q&&!q(a)){if(2>=arguments.length)return b(a,d);var c=H(arguments);return b.apply(null,c)}setTimeout(e,l(s))}var g,l,q,s=0;if(3>arguments.length&&"function"===typeof a)b=c||w,c=a,a=null,g=5;else switch(b=b||w,typeof a){case "object":"function"===typeof a.errorFilter&&(q=a.errorFilter);var h=a.interval; +switch(typeof h){case "function":l=h;break;case "string":case "number":l=(h=+h)?function(){return h}:function(){return 0}}g=+a.times||5;break;case "number":g=a||5;break;case "string":g=+a||5;break;default:throw Error("Invalid arguments for async.retry");}if("function"!==typeof c)throw Error("Invalid arguments for async.retry");l?c(f):c(d)}function Pa(a){return function(){var c=H(arguments),b=c.pop(),d;try{d=a.apply(this,c)}catch(e){return b(e)}d&&"function"===typeof d.then?d.then(function(a){try{b(null, +a)}catch(d){D(Qa,d)}},function(a){a=a&&a.message?a:Error(a);try{b(a,void 0)}catch(d){D(Qa,d)}}):b(null,d)}}function Qa(a){throw a;}function Ra(a){return function(){function c(a,d){if(a)return b(null,{error:a});2=arguments.length?c:J(arguments,1),a=null,++q===f&&d(null,l))}}d=d||w;var f,g,l,q=0;C(b)?(f=b.length,l=Array(f),a(b,e)):b&&"object"===typeof b&&(g=F(b),f=g.length,l={},c(b,e,g));f||d(null,l)}}(function(a,c){for(var b=-1,d=a.length;++bc)return d(null,[]);v=v||Array(k);K(c>k?k:c,t)},mapValues:fb,mapValuesSeries:function(a,c,b){function d(){k=t;c(a[t], +s)}function e(){k=t;c(a[t],t,s)}function f(){k=t;n=r.next();n.done?b(null,v):c(n.value,s)}function g(){k=t;n=r.next();n.done?b(null,v):c(n.value,t,s)}function l(){k=m[t];c(a[k],s)}function q(){k=m[t];c(a[k],k,s)}function s(a,d){a?(p=A,b=E(b),b(a,L(v))):(v[k]=d,++t===h?(p=A,b(null,v),b=A):u?D(p):(u=!0,p()),u=!1)}b=b||w;var h,k,m,r,n,p,u=!1,v={},t=0;C(a)?(h=a.length,p=3===c.length?e:d):a&&(z&&a[z]?(h=Infinity,r=a[z](),p=3===c.length?g:f):"object"===typeof a&&(m=F(a),h=m.length,p=3===c.length?q:l)); +if(!h)return b(null,v);p()},mapValuesLimit:function(a,c,b,d){function e(){m=y++;mc)return d(null,x);K(c>k?k:c,v)},filter:Ta,filterSeries:Ua,filterLimit:Va,select:Ta,selectSeries:Ua,selectLimit:Va,reject:gb,rejectSeries:hb,rejectLimit:ib,detect:ja,detectSeries:ka,detectLimit:la,find:ja,findSeries:ka,findLimit:la,pick:jb,pickSeries:kb, +pickLimit:lb,omit:mb,omitSeries:nb,omitLimit:ob,reduce:$,inject:$,foldl:$,reduceRight:Ga,foldr:Ga,transform:pb,transformSeries:function(a,c,b,d){function e(){b(v,a[x],h)}function f(){b(v,a[x],x,h)}function g(){p=n.next();p.done?d(null,v):b(v,p.value,h)}function l(){p=n.next();p.done?d(null,v):b(v,p.value,x,h)}function q(){b(v,a[r[x]],h)}function s(){m=r[x];b(v,a[m],m,h)}function h(a,b){a?d(a,v):++x===k||!1===b?(u=A,d(null,v)):t?D(u):(t=!0,u());t=!1}3===arguments.length&&(d=b,b=c,c=void 0);d=E(d|| +w);var k,m,r,n,p,u,v,t=!1,x=0;C(a)?(k=a.length,v=void 0!==c?c:[],u=4===b.length?f:e):a&&(z&&a[z]?(k=Infinity,n=a[z](),v=void 0!==c?c:{},u=4===b.length?l:g):"object"===typeof a&&(r=F(a),k=r.length,v=void 0!==c?c:{},u=4===b.length?s:q));if(!k)return d(null,void 0!==c?c:v||{});u()},transformLimit:function(a,c,b,d,e){function f(){r=A++;rc)return e(null,void 0!==b?b:x||{});K(c>m?m:c,t)},sortBy:qb,sortBySeries:function(a,c,b){function d(){m=a[y];c(m,s)}function e(){m=a[y];c(m,y,s)}function f(){p=n.next();if(p.done)return b(null,P(u,v));m=p.value;u[y]=m;c(m,s)}function g(){p=n.next();if(p.done)return b(null,P(u,v));m=p.value;u[y]=m;c(m,y,s)}function l(){m=a[r[y]];u[y]=m;c(m,s)}function q(){k=r[y];m=a[k];u[y]=m;c(m,k,s)}function s(a,d){v[y]=d;a?b(a):++y===h?(t=A,b(null, +P(u,v))):x?D(t):(x=!0,t());x=!1}b=E(b||w);var h,k,m,r,n,p,u,v,t,x=!1,y=0;C(a)?(h=a.length,u=a,v=Array(h),t=3===c.length?e:d):a&&(z&&a[z]?(h=Infinity,u=[],v=[],n=a[z](),t=3===c.length?g:f):"object"===typeof a&&(r=F(a),h=r.length,u=Array(h),v=Array(h),t=3===c.length?q:l));if(!h)return b(null,[]);t()},sortByLimit:function(a,c,b,d){function e(){Bc)return d(null,[]);x=x||Array(k);K(c>k?k:c,y)},some:Ha,someSeries:Ia,someLimit:Ja,any:Ha,anySeries:Ia,anyLimit:Ja,every:Wa,everySeries:Xa,everyLimit:Ya,all:Wa,allSeries:Xa,allLimit:Ya,concat:rb,concatSeries:function(a,c,b){function d(){c(a[t],s)}function e(){c(a[t],t,s)}function f(){n=r.next();n.done?b(null,v):c(n.value,s)}function g(){n=r.next();n.done?b(null,v):c(n.value,t,s)}function l(){c(a[m[t]], +s)}function q(){k=m[t];c(a[k],k,s)}function s(a,d){C(d)?X.apply(v,d):2<=arguments.length&&X.apply(v,J(arguments,1));a?b(a,v):++t===h?(p=A,b(null,v)):u?D(p):(u=!0,p());u=!1}b=E(b||w);var h,k,m,r,n,p,u=!1,v=[],t=0;C(a)?(h=a.length,p=3===c.length?e:d):a&&(z&&a[z]?(h=Infinity,r=a[z](),p=3===c.length?g:f):"object"===typeof a&&(m=F(a),h=m.length,p=3===c.length?q:l));if(!h)return b(null,v);p()},concatLimit:function(a,c,b,d){function e(){tc)return d(null,[]);u=u||Array(k);K(c>k?k:c,p)},groupBy:sb,groupBySeries:function(a,c,b){function d(){m=a[t];c(m,s)}function e(){m=a[t];c(m,t,s)}function f(){p=n.next();m=p.value;p.done?b(null,x):c(m,s)}function g(){p=n.next();m=p.value;p.done? +b(null,x):c(m,t,s)}function l(){m=a[r[t]];c(m,s)}function q(){k=r[t];m=a[k];c(m,k,s)}function s(a,d){if(a)u=A,b=E(b),b(a,L(x));else{var c=x[d];c?c.push(m):x[d]=[m];++t===h?(u=A,b(null,x)):v?D(u):(v=!0,u());v=!1}}b=E(b||w);var h,k,m,r,n,p,u,v=!1,t=0,x={};C(a)?(h=a.length,u=3===c.length?e:d):a&&(z&&a[z]?(h=Infinity,n=a[z](),u=3===c.length?g:f):"object"===typeof a&&(r=F(a),h=r.length,u=3===c.length?q:l));if(!h)return b(null,x);u()},groupByLimit:function(a,c,b,d){function e(){yc)return d(null,B);K(c>k?k:c,t)},parallel:tb,series:function(a,c){function b(){g=k;a[k](e)}function d(){g=l[k];a[g](e)}function e(a,b){a?(s=A,c=E(c),c(a,q)):(q[g]=2>=arguments.length?b:J(arguments,1),++k===f?(s=A,c(null,q)):h?D(s):(h=!0,s()),h=!1)}c=c||w;var f,g,l,q,s,h=!1,k=0;if(C(a))f=a.length,q=Array(f), +s=b;else if(a&&"object"===typeof a)l=F(a),f=l.length,q={},s=d;else return c(null);if(!f)return c(null,q);s()},parallelLimit:function(a,c,b){function d(){l=r++;if(l=arguments.length?c:J(arguments,1),a=null,++n===g?b(null,h):m?D(k):(m=!0,k()),m=!1)}}b=b||w;var g,l,q,s,h,k,m=!1,r=0,n=0;C(a)?(g=a.length,h=Array(g),k=d):a&&"object"===typeof a&&(s=F(a),g=s.length,h= +{},k=e);if(!g||isNaN(c)||1>c)return b(null,h);K(c>g?g:c,k)},tryEach:function(a,c){function b(){a[q](e)}function d(){a[g[q]](e)}function e(a,b){a?++q===f?c(a):l():2>=arguments.length?c(null,b):c(null,J(arguments,1))}c=c||w;var f,g,l,q=0;C(a)?(f=a.length,l=b):a&&"object"===typeof a&&(g=F(a),f=g.length,l=d);if(!f)return c(null);l()},waterfall:function(a,c){function b(){ma(e,f,d(e))}function d(h){return function(k,m){void 0===h&&(c=w,A());h=void 0;k?(g=c,c=A,g(k)):++q===s?(g=c,c=A,2>=arguments.length? +g(k,m):g.apply(null,H(arguments))):(l?(f=arguments,e=a[q]||A,D(b)):(l=!0,ma(a[q]||A,arguments,d(q))),l=!1)}}c=c||w;if(Ka(a,c)){var e,f,g,l,q=0,s=a.length;ma(a[0],[],d(0))}},angelFall:La,angelfall:La,whilst:function(a,c,b){function d(){g?D(e):(g=!0,c(f));g=!1}function e(){c(f)}function f(c,e){if(c)return b(c);2>=arguments.length?a(e)?d():b(null,e):(e=J(arguments,1),a.apply(null,e)?d():b.apply(null,[null].concat(e)))}b=b||w;var g=!1;a()?d():b(null)},doWhilst:function(a,c,b){function d(){g?D(e):(g=!0, +a(f));g=!1}function e(){a(f)}function f(a,e){if(a)return b(a);2>=arguments.length?c(e)?d():b(null,e):(e=J(arguments,1),c.apply(null,e)?d():b.apply(null,[null].concat(e)))}b=b||w;var g=!1;e()},until:function(a,c,b){function d(){g?D(e):(g=!0,c(f));g=!1}function e(){c(f)}function f(c,e){if(c)return b(c);2>=arguments.length?a(e)?b(null,e):d():(e=J(arguments,1),a.apply(null,e)?b.apply(null,[null].concat(e)):d())}b=b||w;var g=!1;a()?b(null):d()},doUntil:function(a,c,b){function d(){g?D(e):(g=!0,a(f));g= +!1}function e(){a(f)}function f(a,e){if(a)return b(a);2>=arguments.length?c(e)?b(null,e):d():(e=J(arguments,1),c.apply(null,e)?b.apply(null,[null].concat(e)):d())}b=b||w;var g=!1;e()},during:function(a,c,b){function d(a,d){if(a)return b(a);d?c(e):b(null)}function e(c){if(c)return b(c);a(d)}b=b||w;a(d)},doDuring:function(a,c,b){function d(d,c){if(d)return b(d);c?a(e):b(null)}function e(a,e){if(a)return b(a);switch(arguments.length){case 0:case 1:c(d);break;case 2:c(e,d);break;default:var l=J(arguments, +1);l.push(d);c.apply(null,l)}}b=b||w;d(null,!0)},forever:function(a,c){function b(){a(d)}function d(a){if(a){if(c)return c(a);throw a;}e?D(b):(e=!0,b());e=!1}var e=!1;b()},compose:function(){return Ma.apply(null,Za(arguments))},seq:Ma,applyEach:ub,applyEachSeries:vb,queue:function(a,c){return na(!0,a,c)},priorityQueue:function(a,c){var b=na(!0,a,c);b.push=function(a,c,f){b.started=!0;c=c||0;var g=C(a)?a:[a],l=g.length;if(void 0===a||0===l)b.idle()&&D(b.drain);else{f="function"===typeof f?f:w;for(a= +b._tasks.head;a&&c>=a.priority;)a=a.next;for(;l--;){var q={data:g[l],priority:c,callback:f};a?b._tasks.insertBefore(a,q):b._tasks.push(q);D(b.process)}}};delete b.unshift;return b},cargo:function(a,c){return na(!1,a,1,c)},auto:Oa,autoInject:function(a,c,b){var d={};W(a,function(a,b){var c,l=a.length;if(C(a)){if(0===l)throw Error("autoInject task functions require explicit parameters.");c=H(a);l=c.length-1;a=c[l];if(0===l){d[b]=a;return}}else{if(1===l){d[b]=a;return}c=ab(a);if(0===l&&0===c.length)throw Error("autoInject task functions require explicit parameters."); +l=c.length-1}c[l]=function(b,d){switch(l){case 1:a(b[c[0]],d);break;case 2:a(b[c[0]],b[c[1]],d);break;case 3:a(b[c[0]],b[c[1]],b[c[2]],d);break;default:for(var f=-1;++fa)return b(null,[]);var e=Array(a);K(a,function(a){c(a,d(a))})},timesSeries:function(a,c,b){function d(){c(l, +e)}function e(c,e){f[l]=e;c?(b(c),b=A):++l>=a?(b(null,f),b=A):g?D(d):(g=!0,d());g=!1}b=b||w;a=+a;if(isNaN(a)||1>a)return b(null,[]);var f=Array(a),g=!1,l=0;d()},timesLimit:function(a,c,b,d){function e(){var c=q++;c=a?(d(null,g),d=A):l?D(e):(l=!0,e());l=!1}}d=d||w;a=+a;if(isNaN(a)||1>a||isNaN(c)||1>c)return d(null,[]);var g=Array(a),l=!1,q=0,s=0;K(c>a?a:c,e)},race:function(a,c){c=I(c||w);var b,d,e=-1;if(C(a))for(b= +a.length;++e", + "license": "MIT", + "devDependencies": { + "semver": "^7.3.5" + } +} diff --git a/node_modules/p-limit/index.d.ts b/node_modules/p-limit/index.d.ts new file mode 100644 index 0000000..caae030 --- /dev/null +++ b/node_modules/p-limit/index.d.ts @@ -0,0 +1,40 @@ +/* eslint-disable @typescript-eslint/member-ordering */ + +export interface LimitFunction { + /** + The number of promises that are currently running. + */ + readonly activeCount: number; + + /** + The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + */ + readonly pendingCount: number; + + /** + Discard pending promises that are waiting to run. + + This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + + Note: This does not cancel promises that are already running. + */ + clearQueue: () => void; + + /** + @param fn - Promise-returning/async function. + @param arguments - Any arguments to pass through to `fn`. Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a lot of functions. + @returns The promise returned by calling `fn(...arguments)`. + */ + ( + fn: (...arguments: Arguments) => PromiseLike | ReturnType, + ...arguments: Arguments + ): Promise; +} + +/** +Run multiple promise-returning & async functions with limited concurrency. + +@param concurrency - Concurrency limit. Minimum: `1`. +@returns A `limit` function. +*/ +export default function pLimit(concurrency: number): LimitFunction; diff --git a/node_modules/p-limit/index.js b/node_modules/p-limit/index.js new file mode 100644 index 0000000..b54b99b --- /dev/null +++ b/node_modules/p-limit/index.js @@ -0,0 +1,68 @@ +import Queue from 'yocto-queue'; + +export default function pLimit(concurrency) { + if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) { + throw new TypeError('Expected `concurrency` to be a number from 1 and up'); + } + + const queue = new Queue(); + let activeCount = 0; + + const next = () => { + activeCount--; + + if (queue.size > 0) { + queue.dequeue()(); + } + }; + + const run = async (fn, resolve, args) => { + activeCount++; + + const result = (async () => fn(...args))(); + + resolve(result); + + try { + await result; + } catch {} + + next(); + }; + + const enqueue = (fn, resolve, args) => { + queue.enqueue(run.bind(undefined, fn, resolve, args)); + + (async () => { + // This function needs to wait until the next microtask before comparing + // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously + // when the run function is dequeued and called. The comparison in the if-statement + // needs to happen asynchronously as well to get an up-to-date value for `activeCount`. + await Promise.resolve(); + + if (activeCount < concurrency && queue.size > 0) { + queue.dequeue()(); + } + })(); + }; + + const generator = (fn, ...args) => new Promise(resolve => { + enqueue(fn, resolve, args); + }); + + Object.defineProperties(generator, { + activeCount: { + get: () => activeCount, + }, + pendingCount: { + get: () => queue.size, + }, + clearQueue: { + value: () => { + queue.clear(); + }, + }, + }); + + return generator; +} diff --git a/node_modules/p-limit/license b/node_modules/p-limit/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/p-limit/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/p-limit/package.json b/node_modules/p-limit/package.json new file mode 100644 index 0000000..2e41e6e --- /dev/null +++ b/node_modules/p-limit/package.json @@ -0,0 +1,54 @@ +{ + "name": "p-limit", + "version": "4.0.0", + "description": "Run multiple promise-returning & async functions with limited concurrency", + "license": "MIT", + "repository": "sindresorhus/p-limit", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": "./index.js", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "promise", + "limit", + "limited", + "concurrency", + "throttle", + "throat", + "rate", + "batch", + "ratelimit", + "task", + "queue", + "async", + "await", + "promises", + "bluebird" + ], + "dependencies": { + "yocto-queue": "^1.0.0" + }, + "devDependencies": { + "ava": "^3.15.0", + "delay": "^5.0.0", + "in-range": "^3.0.0", + "random-int": "^3.0.0", + "time-span": "^5.0.0", + "tsd": "^0.17.0", + "xo": "^0.44.0" + } +} diff --git a/node_modules/p-limit/readme.md b/node_modules/p-limit/readme.md new file mode 100644 index 0000000..b02253b --- /dev/null +++ b/node_modules/p-limit/readme.md @@ -0,0 +1,99 @@ +# p-limit + +> Run multiple promise-returning & async functions with limited concurrency + +## Install + +``` +$ npm install p-limit +``` + +## Usage + +```js +import pLimit from 'p-limit'; + +const limit = pLimit(1); + +const input = [ + limit(() => fetchSomething('foo')), + limit(() => fetchSomething('bar')), + limit(() => doSomething()) +]; + +// Only one promise is run at once +const result = await Promise.all(input); +console.log(result); +``` + +## API + +### pLimit(concurrency) + +Returns a `limit` function. + +#### concurrency + +Type: `number`\ +Minimum: `1`\ +Default: `Infinity` + +Concurrency limit. + +### limit(fn, ...args) + +Returns the promise returned by calling `fn(...args)`. + +#### fn + +Type: `Function` + +Promise-returning/async function. + +#### args + +Any arguments to pass through to `fn`. + +Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions. + +### limit.activeCount + +The number of promises that are currently running. + +### limit.pendingCount + +The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + +### limit.clearQueue() + +Discard pending promises that are waiting to run. + +This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + +Note: This does not cancel promises that are already running. + +## FAQ + +### How is this different from the [`p-queue`](https://github.com/sindresorhus/p-queue) package? + +This package is only about limiting the number of concurrent executions, while `p-queue` is a fully featured queue implementation with lots of different options, introspection, and ability to pause the queue. + +## Related + +- [p-queue](https://github.com/sindresorhus/p-queue) - Promise queue with concurrency control +- [p-throttle](https://github.com/sindresorhus/p-throttle) - Throttle promise-returning & async functions +- [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions +- [p-all](https://github.com/sindresorhus/p-all) - Run promise-returning & async functions concurrently with optional limited concurrency +- [More…](https://github.com/sindresorhus/promise-fun) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/p-locate/index.d.ts b/node_modules/p-locate/index.d.ts new file mode 100644 index 0000000..43b89da --- /dev/null +++ b/node_modules/p-locate/index.d.ts @@ -0,0 +1,49 @@ +export interface Options { + /** + The number of concurrently pending promises returned by `tester`. + + Minimum: `1` + + @default Infinity + */ + readonly concurrency?: number; + + /** + Preserve `input` order when searching. + + Disable this to improve performance if you don't care about the order. + + @default true + */ + readonly preserveOrder?: boolean; +} + +/** +Get the first fulfilled promise that satisfies the provided testing function. + +@param input - An iterable of promises/values to test. +@param tester - This function will receive resolved values from `input` and is expected to return a `Promise` or `boolean`. +@returns A `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`. + +@example +``` +import {pathExists} from 'path-exists'; +import pLocate from 'p-locate'; + +const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' +]; + +const foundPath = await pLocate(files, file => pathExists(file)); + +console.log(foundPath); +//=> 'rainbow' +``` +*/ +export default function pLocate( + input: Iterable | ValueType>, + tester: (element: ValueType) => PromiseLike | boolean, + options?: Options +): Promise; diff --git a/node_modules/p-locate/index.js b/node_modules/p-locate/index.js new file mode 100644 index 0000000..5b38636 --- /dev/null +++ b/node_modules/p-locate/index.js @@ -0,0 +1,48 @@ +import pLimit from 'p-limit'; + +class EndError extends Error { + constructor(value) { + super(); + this.value = value; + } +} + +// The input can also be a promise, so we await it. +const testElement = async (element, tester) => tester(await element); + +// The input can also be a promise, so we `Promise.all()` them both. +const finder = async element => { + const values = await Promise.all(element); + if (values[1] === true) { + throw new EndError(values[0]); + } + + return false; +}; + +export default async function pLocate( + iterable, + tester, + { + concurrency = Number.POSITIVE_INFINITY, + preserveOrder = true, + } = {}, +) { + const limit = pLimit(concurrency); + + // Start all the promises concurrently with optional limit. + const items = [...iterable].map(element => [element, limit(testElement, element, tester)]); + + // Check the promises either serially or concurrently. + const checkLimit = pLimit(preserveOrder ? 1 : Number.POSITIVE_INFINITY); + + try { + await Promise.all(items.map(element => checkLimit(finder, element))); + } catch (error) { + if (error instanceof EndError) { + return error.value; + } + + throw error; + } +} diff --git a/node_modules/p-locate/license b/node_modules/p-locate/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/p-locate/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/p-locate/package.json b/node_modules/p-locate/package.json new file mode 100644 index 0000000..a20cb6f --- /dev/null +++ b/node_modules/p-locate/package.json @@ -0,0 +1,56 @@ +{ + "name": "p-locate", + "version": "6.0.0", + "description": "Get the first fulfilled promise that satisfies the provided testing function", + "license": "MIT", + "repository": "sindresorhus/p-locate", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": "./index.js", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "promise", + "locate", + "find", + "finder", + "search", + "searcher", + "test", + "array", + "collection", + "iterable", + "iterator", + "race", + "fulfilled", + "fastest", + "async", + "await", + "promises", + "bluebird" + ], + "dependencies": { + "p-limit": "^4.0.0" + }, + "devDependencies": { + "ava": "^3.15.0", + "delay": "^5.0.0", + "in-range": "^3.0.0", + "time-span": "^5.0.0", + "tsd": "^0.17.0", + "xo": "^0.44.0" + } +} diff --git a/node_modules/p-locate/readme.md b/node_modules/p-locate/readme.md new file mode 100644 index 0000000..9a2c0e3 --- /dev/null +++ b/node_modules/p-locate/readme.md @@ -0,0 +1,91 @@ +# p-locate + +> Get the first fulfilled promise that satisfies the provided testing function + +Think of it like an async version of [`Array#find`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find). + +## Install + +``` +$ npm install p-locate +``` + +## Usage + +Here we find the first file that exists on disk, in array order. + +```js +import {pathExists} from 'path-exists'; +import pLocate from 'p-locate'; + +const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' +]; + +const foundPath = await pLocate(files, file => pathExists(file)); + +console.log(foundPath); +//=> 'rainbow' +``` + +*The above is just an example. Use [`locate-path`](https://github.com/sindresorhus/locate-path) if you need this.* + +## API + +### pLocate(input, tester, options?) + +Returns a `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`. + +#### input + +Type: `Iterable` + +An iterable of promises/values to test. + +#### tester(element) + +Type: `Function` + +This function will receive resolved values from `input` and is expected to return a `Promise` or `boolean`. + +#### options + +Type: `object` + +##### concurrency + +Type: `number`\ +Default: `Infinity`\ +Minimum: `1` + +The number of concurrently pending promises returned by `tester`. + +##### preserveOrder + +Type: `boolean`\ +Default: `true` + +Preserve `input` order when searching. + +Disable this to improve performance if you don't care about the order. + +## Related + +- [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently +- [p-filter](https://github.com/sindresorhus/p-filter) - Filter promises concurrently +- [p-any](https://github.com/sindresorhus/p-any) - Wait for any promise to be fulfilled +- [More…](https://github.com/sindresorhus/promise-fun) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/path-exists/index.d.ts b/node_modules/path-exists/index.d.ts new file mode 100644 index 0000000..3251306 --- /dev/null +++ b/node_modules/path-exists/index.d.ts @@ -0,0 +1,31 @@ +/** +Check if a path exists. + +@returns Whether the path exists. + +@example +``` +// foo.ts +import {pathExists} from 'path-exists'; + +console.log(await pathExists('foo.ts')); +//=> true +``` +*/ +export function pathExists(path: string): Promise; + +/** +Synchronously check if a path exists. + +@returns Whether the path exists. + +@example +``` +// foo.ts +import {pathExistsSync} from 'path-exists'; + +console.log(pathExistsSync('foo.ts')); +//=> true +``` +*/ +export function pathExistsSync(path: string): boolean; diff --git a/node_modules/path-exists/index.js b/node_modules/path-exists/index.js new file mode 100644 index 0000000..ef6443b --- /dev/null +++ b/node_modules/path-exists/index.js @@ -0,0 +1,19 @@ +import fs, {promises as fsPromises} from 'node:fs'; + +export async function pathExists(path) { + try { + await fsPromises.access(path); + return true; + } catch { + return false; + } +} + +export function pathExistsSync(path) { + try { + fs.accessSync(path); + return true; + } catch { + return false; + } +} diff --git a/node_modules/path-exists/license b/node_modules/path-exists/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/path-exists/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/path-exists/package.json b/node_modules/path-exists/package.json new file mode 100644 index 0000000..f5bde2b --- /dev/null +++ b/node_modules/path-exists/package.json @@ -0,0 +1,41 @@ +{ + "name": "path-exists", + "version": "5.0.0", + "description": "Check if a path exists", + "license": "MIT", + "repository": "sindresorhus/path-exists", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": "./index.js", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "path", + "exists", + "exist", + "file", + "filepath", + "fs", + "filesystem", + "file-system", + "access", + "stat" + ], + "devDependencies": { + "ava": "^3.15.0", + "tsd": "^0.17.0", + "xo": "^0.44.0" + } +} diff --git a/node_modules/path-exists/readme.md b/node_modules/path-exists/readme.md new file mode 100644 index 0000000..067b00c --- /dev/null +++ b/node_modules/path-exists/readme.md @@ -0,0 +1,52 @@ +# path-exists + +> Check if a path exists + +NOTE: `fs.existsSync` has been un-deprecated in Node.js since 6.8.0. If you only need to check synchronously, this module is not needed. + +Never use this before handling a file though: + +> In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to `fs.exists()` and `fs.open()`. Just open the file and handle the error when it's not there. + +## Install + +``` +$ npm install path-exists +``` + +## Usage + +```js +// foo.js +import {pathExists} from 'path-exists'; + +console.log(await pathExists('foo.js')); +//=> true +``` + +## API + +### pathExists(path) + +Returns a `Promise` of whether the path exists. + +### pathExistsSync(path) + +Returns a `boolean` of whether the path exists. + +## Related + +- [path-exists-cli](https://github.com/sindresorhus/path-exists-cli) - CLI for this module +- [path-type](https://github.com/sindresorhus/path-type) - Check if a path exists and whether it's a file, directory, or symlink + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/picocolors/LICENSE b/node_modules/picocolors/LICENSE new file mode 100644 index 0000000..46c9b95 --- /dev/null +++ b/node_modules/picocolors/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2021-2024 Oleksii Raspopov, Kostiantyn Denysov, Anton Verinov + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/picocolors/README.md b/node_modules/picocolors/README.md new file mode 100644 index 0000000..54e3aa3 --- /dev/null +++ b/node_modules/picocolors/README.md @@ -0,0 +1,177 @@ +# picocolors + +The tiniest and the fastest library for terminal output formatting with ANSI colors. + +```javascript +import pc from "picocolors" + +console.log( + pc.green(`How are ${pc.italic(`you`)} doing?`) +) +``` + +- **No dependencies.** +- **14 times** smaller and **2 times** faster than chalk. +- Used by popular tools like PostCSS, SVGO, Stylelint, and Browserslist. +- Node.js v6+ & browsers support. Support for both CJS and ESM projects. +- TypeScript type declarations included. +- [`NO_COLOR`](https://no-color.org/) friendly. + +## Motivation + +With `picocolors` we are trying to draw attention to the `node_modules` size +problem and promote performance-first culture. + +## Prior Art + +Credits go to the following projects: + +- [Nanocolors](https://github.com/ai/nanocolors) by [@ai](https://github.com/ai) +- [Colorette](https://github.com/jorgebucaran/colorette) by [@jorgebucaran](https://github.com/jorgebucaran) +- [Kleur](https://github.com/lukeed/kleur) by [@lukeed](https://github.com/lukeed) +- [Colors.js](https://github.com/Marak/colors.js) by [@Marak](https://github.com/Marak) +- [Chalk](https://github.com/chalk/chalk) by [@sindresorhus](https://github.com/sindresorhus) + +## Benchmarks + +The space in node_modules including sub-dependencies: + +```diff +$ node ./benchmarks/size.js +Data from packagephobia.com + chalk 101 kB + cli-color 1249 kB + ansi-colors 25 kB + kleur 21 kB + colorette 17 kB + nanocolors 16 kB ++ picocolors 7 kB +``` + +Library loading time: + +```diff +$ node ./benchmarks/loading.js + chalk 6.167 ms + cli-color 31.431 ms + ansi-colors 1.585 ms + kleur 2.008 ms + kleur/colors 0.773 ms + colorette 2.476 ms + nanocolors 0.833 ms ++ picocolors 0.466 ms +``` + +Benchmark for simple use case: + +```diff +$ node ./benchmarks/simple.js + chalk 24,066,342 ops/sec + cli-color 938,700 ops/sec + ansi-colors 4,532,542 ops/sec + kleur 20,343,122 ops/sec + kleur/colors 35,415,770 ops/sec + colorette 34,244,834 ops/sec + nanocolors 33,443,265 ops/sec ++ picocolors 33,271,645 ops/sec +``` + +Benchmark for complex use cases: + +```diff +$ node ./benchmarks/complex.js + chalk 969,915 ops/sec + cli-color 131,639 ops/sec + ansi-colors 342,250 ops/sec + kleur 611,880 ops/sec + kleur/colors 1,129,526 ops/sec + colorette 1,747,277 ops/sec + nanocolors 1,251,312 ops/sec ++ picocolors 2,024,086 ops/sec +``` + +## Usage + +Picocolors provides an object which includes a variety of text coloring and formatting functions + +```javascript +import pc from "picocolors" +``` + +The object includes following coloring functions: `black`, `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, `white`, `gray`. + +```javascript +console.log(`I see a ${pc.red("red door")} and I want it painted ${pc.black("black")}`) +``` + +The object also includes following background color modifier functions: `bgBlack`, `bgRed`, `bgGreen`, `bgYellow`, `bgBlue`, `bgMagenta`, `bgCyan`, `bgWhite` and bright variants `bgBlackBright`, `bgRedBright`, `bgGreenBright`, `bgYellowBright`, `bgBlueBright`, `bgMagentaBright`, `bgCyanBright`, `bgWhiteBright`. + +```javascript +console.log( + pc.bgBlack( + pc.white(`Tom appeared on the sidewalk with a bucket of whitewash and a long-handled brush.`) + ) +) +``` + +Besides colors, the object includes following formatting functions: `dim`, `bold`, `hidden`, `italic`, `underline`, `strikethrough`, `reset`, `inverse` and bright variants `blackBright`, `redBright`, `greenBright`, `yellowBright`, `blueBright`, `magentaBright`, `cyanBright`, `whiteBright`. + +```javascript +for (let task of tasks) { + console.log(`${pc.bold(task.name)} ${pc.dim(task.durationMs + "ms")}`) +} +``` + +The library provides additional utilities to ensure the best results for the task: + +- `isColorSupported` — boolean, explicitly tells whether or not the colors or formatting appear on the screen + + ```javascript + import pc from "picocolors" + + if (pc.isColorSupported) { + console.log("Yay! This script can use colors and formatters") + } + ``` + +- `createColors(enabled)` — a function that returns a new API object with manually defined color support configuration + + ```javascript + import pc from "picocolors" + + let { red, bgWhite } = pc.createColors(options.enableColors) + ``` + +## Replacing `chalk` + +1. Replace package name in import: + + ```diff + - import chalk from 'chalk' + + import pico from 'picocolors' + ``` + +2. Replace variable: + + ```diff + - chalk.red(text) + + pico.red(text) + ``` + +3. Replace chains to nested calls: + + ```diff + - chalk.red.bold(text) + + pico.red(pico.bold(text)) + ``` + +4. You can use [`colorize-template`](https://github.com/usmanyunusov/colorize-template) + to replace chalk’s tagged template literal. + + ```diff + + import { createColorize } from 'colorize-template' + + + let colorize = createColorize(pico) + - chalk.red.bold`full {yellow ${"text"}}` + + colorize`{red.bold full {yellow ${"text"}}}` + ``` diff --git a/node_modules/picocolors/package.json b/node_modules/picocolors/package.json new file mode 100644 index 0000000..fd781f4 --- /dev/null +++ b/node_modules/picocolors/package.json @@ -0,0 +1,49 @@ +{ + "name": "picocolors", + "version": "1.1.0", + "main": "./picocolors.js", + "types": "./picocolors.d.ts", + "browser": { + "./picocolors.js": "./picocolors.browser.js" + }, + "sideEffects": false, + "description": "The tiniest and the fastest library for terminal output formatting with ANSI colors", + "scripts": { + "test": "node tests/test.js" + }, + "files": [ + "picocolors.*", + "types.ts" + ], + "keywords": [ + "terminal", + "colors", + "formatting", + "cli", + "console" + ], + "author": "Alexey Raspopov", + "repository": "alexeyraspopov/picocolors", + "license": "ISC", + "devDependencies": { + "ansi-colors": "^4.1.1", + "benchmark": "^2.1.4", + "chalk": "^4.1.2", + "clean-publish": "^3.0.3", + "cli-color": "^2.0.0", + "colorette": "^2.0.12", + "kleur": "^4.1.4", + "nanocolors": "^0.2.12", + "prettier": "^2.4.1" + }, + "prettier": { + "printWidth": 100, + "useTabs": true, + "tabWidth": 2, + "semi": false, + "arrowParens": "avoid" + }, + "clean-publish": { + "cleanDocs": true + } +} diff --git a/node_modules/picocolors/picocolors.browser.js b/node_modules/picocolors/picocolors.browser.js new file mode 100644 index 0000000..9dcf637 --- /dev/null +++ b/node_modules/picocolors/picocolors.browser.js @@ -0,0 +1,4 @@ +var x=String; +var create=function() {return {isColorSupported:false,reset:x,bold:x,dim:x,italic:x,underline:x,inverse:x,hidden:x,strikethrough:x,black:x,red:x,green:x,yellow:x,blue:x,magenta:x,cyan:x,white:x,gray:x,bgBlack:x,bgRed:x,bgGreen:x,bgYellow:x,bgBlue:x,bgMagenta:x,bgCyan:x,bgWhite:x,blackBright:x,redBright:x,greenBright:x,yellowBright:x,blueBright:x,magentaBright:x,cyanBright:x,whiteBright:x,bgBlackBright:x,bgRedBright:x,bgGreenBright:x,bgYellowBright:x,bgBlueBright:x,bgMagentaBright:x,bgCyanBright:x,bgWhiteBright:x}}; +module.exports=create(); +module.exports.createColors = create; diff --git a/node_modules/picocolors/picocolors.d.ts b/node_modules/picocolors/picocolors.d.ts new file mode 100644 index 0000000..94e146a --- /dev/null +++ b/node_modules/picocolors/picocolors.d.ts @@ -0,0 +1,5 @@ +import { Colors } from "./types" + +declare const picocolors: Colors & { createColors: (enabled?: boolean) => Colors } + +export = picocolors diff --git a/node_modules/picocolors/picocolors.js b/node_modules/picocolors/picocolors.js new file mode 100644 index 0000000..f5ea2a1 --- /dev/null +++ b/node_modules/picocolors/picocolors.js @@ -0,0 +1,85 @@ +let argv = process.argv || [], + env = process.env +let isColorSupported = + !("NO_COLOR" in env || argv.includes("--no-color")) && + ("FORCE_COLOR" in env || + argv.includes("--color") || + process.platform === "win32" || + (require != null && require("tty").isatty(1) && env.TERM !== "dumb") || + "CI" in env) + +let formatter = + (open, close, replace = open) => + input => { + let string = "" + input + let index = string.indexOf(close, open.length) + return ~index + ? open + replaceClose(string, close, replace, index) + close + : open + string + close + } + +let replaceClose = (string, close, replace, index) => { + let result = "" + let cursor = 0 + do { + result += string.substring(cursor, index) + replace + cursor = index + close.length + index = string.indexOf(close, cursor) + } while (~index) + return result + string.substring(cursor) +} + +let createColors = (enabled = isColorSupported) => { + let init = enabled ? formatter : () => String + return { + isColorSupported: enabled, + reset: init("\x1b[0m", "\x1b[0m"), + bold: init("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"), + dim: init("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"), + italic: init("\x1b[3m", "\x1b[23m"), + underline: init("\x1b[4m", "\x1b[24m"), + inverse: init("\x1b[7m", "\x1b[27m"), + hidden: init("\x1b[8m", "\x1b[28m"), + strikethrough: init("\x1b[9m", "\x1b[29m"), + + black: init("\x1b[30m", "\x1b[39m"), + red: init("\x1b[31m", "\x1b[39m"), + green: init("\x1b[32m", "\x1b[39m"), + yellow: init("\x1b[33m", "\x1b[39m"), + blue: init("\x1b[34m", "\x1b[39m"), + magenta: init("\x1b[35m", "\x1b[39m"), + cyan: init("\x1b[36m", "\x1b[39m"), + white: init("\x1b[37m", "\x1b[39m"), + gray: init("\x1b[90m", "\x1b[39m"), + + bgBlack: init("\x1b[40m", "\x1b[49m"), + bgRed: init("\x1b[41m", "\x1b[49m"), + bgGreen: init("\x1b[42m", "\x1b[49m"), + bgYellow: init("\x1b[43m", "\x1b[49m"), + bgBlue: init("\x1b[44m", "\x1b[49m"), + bgMagenta: init("\x1b[45m", "\x1b[49m"), + bgCyan: init("\x1b[46m", "\x1b[49m"), + bgWhite: init("\x1b[47m", "\x1b[49m"), + + blackBright: init("\x1b[90m", "\x1b[39m"), + redBright: init("\x1b[91m", "\x1b[39m"), + greenBright: init("\x1b[92m", "\x1b[39m"), + yellowBright: init("\x1b[93m", "\x1b[39m"), + blueBright: init("\x1b[94m", "\x1b[39m"), + magentaBright: init("\x1b[95m", "\x1b[39m"), + cyanBright: init("\x1b[96m", "\x1b[39m"), + whiteBright: init("\x1b[97m", "\x1b[39m"), + + bgBlackBright: init("\x1b[100m","\x1b[49m"), + bgRedBright: init("\x1b[101m","\x1b[49m"), + bgGreenBright: init("\x1b[102m","\x1b[49m"), + bgYellowBright: init("\x1b[103m","\x1b[49m"), + bgBlueBright: init("\x1b[104m","\x1b[49m"), + bgMagentaBright: init("\x1b[105m","\x1b[49m"), + bgCyanBright: init("\x1b[106m","\x1b[49m"), + bgWhiteBright: init("\x1b[107m","\x1b[49m"), + } +} + +module.exports = createColors() +module.exports.createColors = createColors diff --git a/node_modules/picocolors/types.ts b/node_modules/picocolors/types.ts new file mode 100644 index 0000000..8046e27 --- /dev/null +++ b/node_modules/picocolors/types.ts @@ -0,0 +1,52 @@ +export type Formatter = (input: string | number | null | undefined) => string + +export interface Colors { + isColorSupported: boolean + + reset: Formatter + bold: Formatter + dim: Formatter + italic: Formatter + underline: Formatter + inverse: Formatter + hidden: Formatter + strikethrough: Formatter + + black: Formatter + red: Formatter + green: Formatter + yellow: Formatter + blue: Formatter + magenta: Formatter + cyan: Formatter + white: Formatter + gray: Formatter + + bgBlack: Formatter + bgRed: Formatter + bgGreen: Formatter + bgYellow: Formatter + bgBlue: Formatter + bgMagenta: Formatter + bgCyan: Formatter + bgWhite: Formatter + + blackBright: Formatter + redBright: Formatter + greenBright: Formatter + yellowBright: Formatter + blueBright: Formatter + magentaBright: Formatter + cyanBright: Formatter + whiteBright: Formatter + + bgBlackBright: Formatter + bgRedBright: Formatter + bgGreenBright: Formatter + bgYellowBright: Formatter + bgBlueBright: Formatter + bgMagentaBright: Formatter + bgCyanBright: Formatter + bgWhiteBright: Formatter + +} diff --git a/node_modules/pkg-dir/index.d.ts b/node_modules/pkg-dir/index.d.ts new file mode 100644 index 0000000..9157f89 --- /dev/null +++ b/node_modules/pkg-dir/index.d.ts @@ -0,0 +1,58 @@ +export interface Options { + /** + The directory to start searching from. + + @default process.cwd() + */ + readonly cwd?: string; +} + +/** +Find the root directory of a Node.js project or npm package. + +@returns The project root path or `undefined` if it could not be found. + +@example +``` +// / +// └── Users +// └── sindresorhus +// └── foo +// ├── package.json +// └── bar +// ├── baz +// └── example.js + +// example.js +import {packageDirectory} from 'pkg-dir'; + +console.log(await packageDirectory()); +//=> '/Users/sindresorhus/foo' +``` +*/ +export function packageDirectory(options?: Options): Promise; + +/** +Synchronously find the root directory of a Node.js project or npm package. + +@returns The project root path or `undefined` if it could not be found. + +@example +``` +// / +// └── Users +// └── sindresorhus +// └── foo +// ├── package.json +// └── bar +// ├── baz +// └── example.js + +// example.js +import {packageDirectorySync} from 'pkg-dir'; + +console.log(packageDirectorySync()); +//=> '/Users/sindresorhus/foo' +``` +*/ +export function packageDirectorySync(options?: Options): string | undefined; diff --git a/node_modules/pkg-dir/index.js b/node_modules/pkg-dir/index.js new file mode 100644 index 0000000..294c767 --- /dev/null +++ b/node_modules/pkg-dir/index.js @@ -0,0 +1,12 @@ +import path from 'node:path'; +import {findUp, findUpSync} from 'find-up'; + +export async function packageDirectory({cwd} = {}) { + const filePath = await findUp('package.json', {cwd}); + return filePath && path.dirname(filePath); +} + +export function packageDirectorySync({cwd} = {}) { + const filePath = findUpSync('package.json', {cwd}); + return filePath && path.dirname(filePath); +} diff --git a/node_modules/pkg-dir/license b/node_modules/pkg-dir/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/pkg-dir/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/pkg-dir/package.json b/node_modules/pkg-dir/package.json new file mode 100644 index 0000000..7f26632 --- /dev/null +++ b/node_modules/pkg-dir/package.json @@ -0,0 +1,59 @@ +{ + "name": "pkg-dir", + "version": "7.0.0", + "description": "Find the root directory of a Node.js project or npm package", + "license": "MIT", + "repository": "sindresorhus/pkg-dir", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": "./index.js", + "engines": { + "node": ">=14.16" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "package", + "json", + "root", + "npm", + "entry", + "find", + "up", + "find-up", + "findup", + "look-up", + "look", + "file", + "search", + "match", + "resolve", + "parent", + "parents", + "folder", + "directory", + "walk", + "walking", + "path" + ], + "dependencies": { + "find-up": "^6.3.0" + }, + "devDependencies": { + "ava": "^4.3.1", + "tempy": "^3.0.0", + "tsd": "^0.22.0", + "typescript": "^4.7.4", + "xo": "^0.51.0" + } +} diff --git a/node_modules/pkg-dir/readme.md b/node_modules/pkg-dir/readme.md new file mode 100644 index 0000000..8898c24 --- /dev/null +++ b/node_modules/pkg-dir/readme.md @@ -0,0 +1,69 @@ +# pkg-dir + +> Find the root directory of a Node.js project or npm package + +## Install + +```sh +npm install pkg-dir +``` + +## Usage + +``` +/ +└── Users + └── sindresorhus + └── foo + ├── package.json + └── bar + ├── baz + └── example.js +``` + +```js +// example.js +import {packageDirectory} from 'pkg-dir'; + +console.log(await packageDirectory()); +//=> '/Users/sindresorhus/foo' +``` + +## API + +### packageDirectory(option?) + +Returns a `Promise` for either the project root path or `undefined` if it could not be found. + +### packageDirectorySync(options?) + +Returns the project root path or `undefined` if it could not be found. + +#### options + +Type: `object` + +##### cwd + +Type: `string`\ +Default: `process.cwd()` + +The directory to start searching from. + +## Related + +- [pkg-dir-cli](https://github.com/sindresorhus/pkg-dir-cli) - CLI for this module +- [pkg-up](https://github.com/sindresorhus/pkg-up) - Find the closest package.json file +- [find-up](https://github.com/sindresorhus/find-up) - Find a file by walking up parent directories + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/punycode/LICENSE-MIT.txt b/node_modules/punycode/LICENSE-MIT.txt new file mode 100644 index 0000000..a41e0a7 --- /dev/null +++ b/node_modules/punycode/LICENSE-MIT.txt @@ -0,0 +1,20 @@ +Copyright Mathias Bynens + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/punycode/README.md b/node_modules/punycode/README.md new file mode 100644 index 0000000..f611016 --- /dev/null +++ b/node_modules/punycode/README.md @@ -0,0 +1,148 @@ +# Punycode.js [![punycode on npm](https://img.shields.io/npm/v/punycode)](https://www.npmjs.com/package/punycode) [![](https://data.jsdelivr.com/v1/package/npm/punycode/badge)](https://www.jsdelivr.com/package/npm/punycode) + +Punycode.js is a robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891). + +This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: + +* [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C) +* [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) +* [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) +* [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) +* [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) + +This project was [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with Node.js from [v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) until [v7](https://github.com/nodejs/node/pull/7941) (soft-deprecated). + +This project provides a CommonJS module that uses ES2015+ features and JavaScript module, which work in modern Node.js versions and browsers. For the old Punycode.js version that offers the same functionality in a UMD build with support for older pre-ES2015 runtimes, including Rhino, Ringo, and Narwhal, see [v1.4.1](https://github.com/mathiasbynens/punycode.js/releases/tag/v1.4.1). + +## Installation + +Via [npm](https://www.npmjs.com/): + +```bash +npm install punycode --save +``` + +In [Node.js](https://nodejs.org/): + +> ⚠️ Note that userland modules don't hide core modules. +> For example, `require('punycode')` still imports the deprecated core module even if you executed `npm install punycode`. +> Use `require('punycode/')` to import userland modules rather than core modules. + +```js +const punycode = require('punycode/'); +``` + +## API + +### `punycode.decode(string)` + +Converts a Punycode string of ASCII symbols to a string of Unicode symbols. + +```js +// decode domain name parts +punycode.decode('maana-pta'); // 'mañana' +punycode.decode('--dqo34k'); // '☃-⌘' +``` + +### `punycode.encode(string)` + +Converts a string of Unicode symbols to a Punycode string of ASCII symbols. + +```js +// encode domain name parts +punycode.encode('mañana'); // 'maana-pta' +punycode.encode('☃-⌘'); // '--dqo34k' +``` + +### `punycode.toUnicode(input)` + +Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. + +```js +// decode domain names +punycode.toUnicode('xn--maana-pta.com'); +// → 'mañana.com' +punycode.toUnicode('xn----dqo34k.com'); +// → '☃-⌘.com' + +// decode email addresses +punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); +// → 'джумла@джpумлатест.bрфa' +``` + +### `punycode.toASCII(input)` + +Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII. + +```js +// encode domain names +punycode.toASCII('mañana.com'); +// → 'xn--maana-pta.com' +punycode.toASCII('☃-⌘.com'); +// → 'xn----dqo34k.com' + +// encode email addresses +punycode.toASCII('джумла@джpумлатест.bрфa'); +// → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' +``` + +### `punycode.ucs2` + +#### `punycode.ucs2.decode(string)` + +Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. + +```js +punycode.ucs2.decode('abc'); +// → [0x61, 0x62, 0x63] +// surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: +punycode.ucs2.decode('\uD834\uDF06'); +// → [0x1D306] +``` + +#### `punycode.ucs2.encode(codePoints)` + +Creates a string based on an array of numeric code point values. + +```js +punycode.ucs2.encode([0x61, 0x62, 0x63]); +// → 'abc' +punycode.ucs2.encode([0x1D306]); +// → '\uD834\uDF06' +``` + +### `punycode.version` + +A string representing the current Punycode.js version number. + +## For maintainers + +### How to publish a new release + +1. On the `main` branch, bump the version number in `package.json`: + + ```sh + npm version patch -m 'Release v%s' + ``` + + Instead of `patch`, use `minor` or `major` [as needed](https://semver.org/). + + Note that this produces a Git commit + tag. + +1. Push the release commit and tag: + + ```sh + git push && git push --tags + ``` + + Our CI then automatically publishes the new release to npm, under both the [`punycode`](https://www.npmjs.com/package/punycode) and [`punycode.js`](https://www.npmjs.com/package/punycode.js) names. + +## Author + +| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | +|---| +| [Mathias Bynens](https://mathiasbynens.be/) | + +## License + +Punycode.js is available under the [MIT](https://mths.be/mit) license. diff --git a/node_modules/punycode/package.json b/node_modules/punycode/package.json new file mode 100644 index 0000000..b8b76fc --- /dev/null +++ b/node_modules/punycode/package.json @@ -0,0 +1,58 @@ +{ + "name": "punycode", + "version": "2.3.1", + "description": "A robust Punycode converter that fully complies to RFC 3492 and RFC 5891, and works on nearly all JavaScript platforms.", + "homepage": "https://mths.be/punycode", + "main": "punycode.js", + "jsnext:main": "punycode.es6.js", + "module": "punycode.es6.js", + "engines": { + "node": ">=6" + }, + "keywords": [ + "punycode", + "unicode", + "idn", + "idna", + "dns", + "url", + "domain" + ], + "license": "MIT", + "author": { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + }, + "contributors": [ + { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/mathiasbynens/punycode.js.git" + }, + "bugs": "https://github.com/mathiasbynens/punycode.js/issues", + "files": [ + "LICENSE-MIT.txt", + "punycode.js", + "punycode.es6.js" + ], + "scripts": { + "test": "mocha tests", + "build": "node scripts/prepublish.js" + }, + "devDependencies": { + "codecov": "^3.8.3", + "nyc": "^15.1.0", + "mocha": "^10.2.0" + }, + "jspm": { + "map": { + "./punycode.js": { + "node": "@node/punycode" + } + } + } +} diff --git a/node_modules/punycode/punycode.es6.js b/node_modules/punycode/punycode.es6.js new file mode 100644 index 0000000..dadece2 --- /dev/null +++ b/node_modules/punycode/punycode.es6.js @@ -0,0 +1,444 @@ +'use strict'; + +/** Highest positive signed 32-bit float value */ +const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +const base = 36; +const tMin = 1; +const tMax = 26; +const skew = 38; +const damp = 700; +const initialBias = 72; +const initialN = 128; // 0x80 +const delimiter = '-'; // '\x2D' + +/** Regular expressions */ +const regexPunycode = /^xn--/; +const regexNonASCII = /[^\0-\x7F]/; // Note: U+007F DEL is excluded too. +const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +const errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +const baseMinusTMin = base - tMin; +const floor = Math.floor; +const stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, callback) { + const result = []; + let length = array.length; + while (length--) { + result[length] = callback(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {String} A new string of characters returned by the callback + * function. + */ +function mapDomain(domain, callback) { + const parts = domain.split('@'); + let result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + domain = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + domain = domain.replace(regexSeparators, '\x2E'); + const labels = domain.split('.'); + const encoded = map(labels, callback).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +const ucs2encode = codePoints => String.fromCodePoint(...codePoints); + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +const basicToDigit = function(codePoint) { + if (codePoint >= 0x30 && codePoint < 0x3A) { + return 26 + (codePoint - 0x30); + } + if (codePoint >= 0x41 && codePoint < 0x5B) { + return codePoint - 0x41; + } + if (codePoint >= 0x61 && codePoint < 0x7B) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +const digitToBasic = function(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +const adapt = function(delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +const decode = function(input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + const oldi = i; + for (let w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + const digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base) { + error('invalid-input'); + } + if (digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + + } + + return String.fromCodePoint(...output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +const encode = function(input) { + const output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + const inputLength = input.length; + + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; + + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + const basicLength = output.length; + let handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + if (currentValue === n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for (let k = base; /* no condition */; k += base) { + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + const qMinusT = q - t; + const baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +const toUnicode = function(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +const toASCII = function(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +const punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.3.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +export { ucs2decode, ucs2encode, decode, encode, toASCII, toUnicode }; +export default punycode; diff --git a/node_modules/punycode/punycode.js b/node_modules/punycode/punycode.js new file mode 100644 index 0000000..a1ef251 --- /dev/null +++ b/node_modules/punycode/punycode.js @@ -0,0 +1,443 @@ +'use strict'; + +/** Highest positive signed 32-bit float value */ +const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +const base = 36; +const tMin = 1; +const tMax = 26; +const skew = 38; +const damp = 700; +const initialBias = 72; +const initialN = 128; // 0x80 +const delimiter = '-'; // '\x2D' + +/** Regular expressions */ +const regexPunycode = /^xn--/; +const regexNonASCII = /[^\0-\x7F]/; // Note: U+007F DEL is excluded too. +const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +const errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +const baseMinusTMin = base - tMin; +const floor = Math.floor; +const stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, callback) { + const result = []; + let length = array.length; + while (length--) { + result[length] = callback(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {String} A new string of characters returned by the callback + * function. + */ +function mapDomain(domain, callback) { + const parts = domain.split('@'); + let result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + domain = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + domain = domain.replace(regexSeparators, '\x2E'); + const labels = domain.split('.'); + const encoded = map(labels, callback).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +const ucs2encode = codePoints => String.fromCodePoint(...codePoints); + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +const basicToDigit = function(codePoint) { + if (codePoint >= 0x30 && codePoint < 0x3A) { + return 26 + (codePoint - 0x30); + } + if (codePoint >= 0x41 && codePoint < 0x5B) { + return codePoint - 0x41; + } + if (codePoint >= 0x61 && codePoint < 0x7B) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +const digitToBasic = function(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +const adapt = function(delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +const decode = function(input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + const oldi = i; + for (let w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + const digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base) { + error('invalid-input'); + } + if (digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + + } + + return String.fromCodePoint(...output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +const encode = function(input) { + const output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + const inputLength = input.length; + + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; + + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + const basicLength = output.length; + let handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + if (currentValue === n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for (let k = base; /* no condition */; k += base) { + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + const qMinusT = q - t; + const baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +const toUnicode = function(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +const toASCII = function(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +const punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.3.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +module.exports = punycode; diff --git a/node_modules/randombytes/.travis.yml b/node_modules/randombytes/.travis.yml new file mode 100644 index 0000000..69fdf71 --- /dev/null +++ b/node_modules/randombytes/.travis.yml @@ -0,0 +1,15 @@ +sudo: false +language: node_js +matrix: + include: + - node_js: '7' + env: TEST_SUITE=test + - node_js: '6' + env: TEST_SUITE=test + - node_js: '5' + env: TEST_SUITE=test + - node_js: '4' + env: TEST_SUITE=test + - node_js: '4' + env: TEST_SUITE=phantom +script: "npm run-script $TEST_SUITE" diff --git a/node_modules/randombytes/.zuul.yml b/node_modules/randombytes/.zuul.yml new file mode 100644 index 0000000..96d9cfb --- /dev/null +++ b/node_modules/randombytes/.zuul.yml @@ -0,0 +1 @@ +ui: tape diff --git a/node_modules/randombytes/LICENSE b/node_modules/randombytes/LICENSE new file mode 100644 index 0000000..fea9d48 --- /dev/null +++ b/node_modules/randombytes/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 crypto-browserify + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/randombytes/README.md b/node_modules/randombytes/README.md new file mode 100644 index 0000000..3bacba4 --- /dev/null +++ b/node_modules/randombytes/README.md @@ -0,0 +1,14 @@ +randombytes +=== + +[![Version](http://img.shields.io/npm/v/randombytes.svg)](https://www.npmjs.org/package/randombytes) [![Build Status](https://travis-ci.org/crypto-browserify/randombytes.svg?branch=master)](https://travis-ci.org/crypto-browserify/randombytes) + +randombytes from node that works in the browser. In node you just get crypto.randomBytes, but in the browser it uses .crypto/msCrypto.getRandomValues + +```js +var randomBytes = require('randombytes'); +randomBytes(16);//get 16 random bytes +randomBytes(16, function (err, resp) { + // resp is 16 random bytes +}); +``` diff --git a/node_modules/randombytes/browser.js b/node_modules/randombytes/browser.js new file mode 100644 index 0000000..0fb0b71 --- /dev/null +++ b/node_modules/randombytes/browser.js @@ -0,0 +1,50 @@ +'use strict' + +// limit of Crypto.getRandomValues() +// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues +var MAX_BYTES = 65536 + +// Node supports requesting up to this number of bytes +// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48 +var MAX_UINT32 = 4294967295 + +function oldBrowser () { + throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') +} + +var Buffer = require('safe-buffer').Buffer +var crypto = global.crypto || global.msCrypto + +if (crypto && crypto.getRandomValues) { + module.exports = randomBytes +} else { + module.exports = oldBrowser +} + +function randomBytes (size, cb) { + // phantomjs needs to throw + if (size > MAX_UINT32) throw new RangeError('requested too many random bytes') + + var bytes = Buffer.allocUnsafe(size) + + if (size > 0) { // getRandomValues fails on IE if size == 0 + if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues + // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues + for (var generated = 0; generated < size; generated += MAX_BYTES) { + // buffer.slice automatically checks if the end is past the end of + // the buffer so we don't have to here + crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES)) + } + } else { + crypto.getRandomValues(bytes) + } + } + + if (typeof cb === 'function') { + return process.nextTick(function () { + cb(null, bytes) + }) + } + + return bytes +} diff --git a/node_modules/randombytes/index.js b/node_modules/randombytes/index.js new file mode 100644 index 0000000..a2d9e39 --- /dev/null +++ b/node_modules/randombytes/index.js @@ -0,0 +1 @@ +module.exports = require('crypto').randomBytes diff --git a/node_modules/randombytes/package.json b/node_modules/randombytes/package.json new file mode 100644 index 0000000..3623652 --- /dev/null +++ b/node_modules/randombytes/package.json @@ -0,0 +1,36 @@ +{ + "name": "randombytes", + "version": "2.1.0", + "description": "random bytes from browserify stand alone", + "main": "index.js", + "scripts": { + "test": "standard && node test.js | tspec", + "phantom": "zuul --phantom -- test.js", + "local": "zuul --local --no-coverage -- test.js" + }, + "repository": { + "type": "git", + "url": "git@github.com:crypto-browserify/randombytes.git" + }, + "keywords": [ + "crypto", + "random" + ], + "author": "", + "license": "MIT", + "bugs": { + "url": "https://github.com/crypto-browserify/randombytes/issues" + }, + "homepage": "https://github.com/crypto-browserify/randombytes", + "browser": "browser.js", + "devDependencies": { + "phantomjs": "^1.9.9", + "standard": "^10.0.2", + "tap-spec": "^2.1.2", + "tape": "^4.6.3", + "zuul": "^3.7.2" + }, + "dependencies": { + "safe-buffer": "^5.1.0" + } +} diff --git a/node_modules/randombytes/test.js b/node_modules/randombytes/test.js new file mode 100644 index 0000000..f266976 --- /dev/null +++ b/node_modules/randombytes/test.js @@ -0,0 +1,81 @@ +var test = require('tape') +var randomBytes = require('./') +var MAX_BYTES = 65536 +var MAX_UINT32 = 4294967295 + +test('sync', function (t) { + t.plan(9) + t.equals(randomBytes(0).length, 0, 'len: ' + 0) + t.equals(randomBytes(3).length, 3, 'len: ' + 3) + t.equals(randomBytes(30).length, 30, 'len: ' + 30) + t.equals(randomBytes(300).length, 300, 'len: ' + 300) + t.equals(randomBytes(17 + MAX_BYTES).length, 17 + MAX_BYTES, 'len: ' + 17 + MAX_BYTES) + t.equals(randomBytes(MAX_BYTES * 100).length, MAX_BYTES * 100, 'len: ' + MAX_BYTES * 100) + t.throws(function () { + randomBytes(MAX_UINT32 + 1) + }) + t.throws(function () { + t.equals(randomBytes(-1)) + }) + t.throws(function () { + t.equals(randomBytes('hello')) + }) +}) + +test('async', function (t) { + t.plan(9) + + randomBytes(0, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 0, 'len: ' + 0) + }) + + randomBytes(3, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 3, 'len: ' + 3) + }) + + randomBytes(30, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 30, 'len: ' + 30) + }) + + randomBytes(300, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 300, 'len: ' + 300) + }) + + randomBytes(17 + MAX_BYTES, function (err, resp) { + if (err) throw err + + t.equals(resp.length, 17 + MAX_BYTES, 'len: ' + 17 + MAX_BYTES) + }) + + randomBytes(MAX_BYTES * 100, function (err, resp) { + if (err) throw err + + t.equals(resp.length, MAX_BYTES * 100, 'len: ' + MAX_BYTES * 100) + }) + + t.throws(function () { + randomBytes(MAX_UINT32 + 1, function () { + t.ok(false, 'should not get here') + }) + }) + + t.throws(function () { + randomBytes(-1, function () { + t.ok(false, 'should not get here') + }) + }) + + t.throws(function () { + randomBytes('hello', function () { + t.ok(false, 'should not get here') + }) + }) +}) diff --git a/node_modules/require-from-string/index.js b/node_modules/require-from-string/index.js new file mode 100644 index 0000000..cb5595f --- /dev/null +++ b/node_modules/require-from-string/index.js @@ -0,0 +1,34 @@ +'use strict'; + +var Module = require('module'); +var path = require('path'); + +module.exports = function requireFromString(code, filename, opts) { + if (typeof filename === 'object') { + opts = filename; + filename = undefined; + } + + opts = opts || {}; + filename = filename || ''; + + opts.appendPaths = opts.appendPaths || []; + opts.prependPaths = opts.prependPaths || []; + + if (typeof code !== 'string') { + throw new Error('code must be a string, not ' + typeof code); + } + + var paths = Module._nodeModulePaths(path.dirname(filename)); + + var parent = module.parent; + var m = new Module(filename, parent); + m.filename = filename; + m.paths = [].concat(opts.prependPaths).concat(paths).concat(opts.appendPaths); + m._compile(code, filename); + + var exports = m.exports; + parent && parent.children && parent.children.splice(parent.children.indexOf(m), 1); + + return exports; +}; diff --git a/node_modules/require-from-string/license b/node_modules/require-from-string/license new file mode 100644 index 0000000..1aeb74f --- /dev/null +++ b/node_modules/require-from-string/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Vsevolod Strukchinsky (github.com/floatdrop) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/require-from-string/package.json b/node_modules/require-from-string/package.json new file mode 100644 index 0000000..800d46e --- /dev/null +++ b/node_modules/require-from-string/package.json @@ -0,0 +1,28 @@ +{ + "name": "require-from-string", + "version": "2.0.2", + "description": "Require module from string", + "license": "MIT", + "repository": "floatdrop/require-from-string", + "author": { + "name": "Vsevolod Strukchinsky", + "email": "floatdrop@gmail.com", + "url": "github.com/floatdrop" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha" + }, + "files": [ + "index.js" + ], + "keywords": [ + "" + ], + "dependencies": {}, + "devDependencies": { + "mocha": "*" + } +} diff --git a/node_modules/require-from-string/readme.md b/node_modules/require-from-string/readme.md new file mode 100644 index 0000000..88b3236 --- /dev/null +++ b/node_modules/require-from-string/readme.md @@ -0,0 +1,56 @@ +# require-from-string [![Build Status](https://travis-ci.org/floatdrop/require-from-string.svg?branch=master)](https://travis-ci.org/floatdrop/require-from-string) + +Load module from string in Node. + +## Install + +``` +$ npm install --save require-from-string +``` + + +## Usage + +```js +var requireFromString = require('require-from-string'); + +requireFromString('module.exports = 1'); +//=> 1 +``` + + +## API + +### requireFromString(code, [filename], [options]) + +#### code + +*Required* +Type: `string` + +Module code. + +#### filename +Type: `string` +Default: `''` + +Optional filename. + + +#### options +Type: `object` + +##### appendPaths +Type: `Array` + +List of `paths`, that will be appended to module `paths`. Useful, when you want +to be able require modules from these paths. + +##### prependPaths +Type: `Array` + +Same as `appendPaths`, but paths will be prepended. + +## License + +MIT © [Vsevolod Strukchinsky](http://github.com/floatdrop) diff --git a/node_modules/safe-buffer/LICENSE b/node_modules/safe-buffer/LICENSE new file mode 100644 index 0000000..0c068ce --- /dev/null +++ b/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/safe-buffer/README.md b/node_modules/safe-buffer/README.md new file mode 100644 index 0000000..e9a81af --- /dev/null +++ b/node_modules/safe-buffer/README.md @@ -0,0 +1,584 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/node_modules/safe-buffer/index.d.ts b/node_modules/safe-buffer/index.d.ts new file mode 100644 index 0000000..e9fed80 --- /dev/null +++ b/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/node_modules/safe-buffer/index.js b/node_modules/safe-buffer/index.js new file mode 100644 index 0000000..f8d3ec9 --- /dev/null +++ b/node_modules/safe-buffer/index.js @@ -0,0 +1,65 @@ +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/node_modules/safe-buffer/package.json b/node_modules/safe-buffer/package.json new file mode 100644 index 0000000..f2869e2 --- /dev/null +++ b/node_modules/safe-buffer/package.json @@ -0,0 +1,51 @@ +{ + "name": "safe-buffer", + "description": "Safer Node.js Buffer API", + "version": "5.2.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "devDependencies": { + "standard": "*", + "tape": "^5.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/schema-utils/LICENSE b/node_modules/schema-utils/LICENSE new file mode 100644 index 0000000..8c11fc7 --- /dev/null +++ b/node_modules/schema-utils/LICENSE @@ -0,0 +1,20 @@ +Copyright JS Foundation and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/schema-utils/README.md b/node_modules/schema-utils/README.md new file mode 100644 index 0000000..9f84bf1 --- /dev/null +++ b/node_modules/schema-utils/README.md @@ -0,0 +1,317 @@ + + +[![npm][npm]][npm-url] +[![node][node]][node-url] +[![tests][tests]][tests-url] +[![coverage][cover]][cover-url] +[![GitHub Discussions][discussion]][discussion-url] +[![size][size]][size-url] + +# schema-utils + +Package for validate options in loaders and plugins. + +## Getting Started + +To begin, you'll need to install `schema-utils`: + +```console +npm install schema-utils +``` + +## API + +**schema.json** + +```json +{ + "type": "object", + "properties": { + "option": { + "type": "boolean" + } + }, + "additionalProperties": false +} +``` + +```js +import schema from "./path/to/schema.json"; +import { validate } from "schema-utils"; + +const options = { option: true }; +const configuration = { name: "Loader Name/Plugin Name/Name" }; + +validate(schema, options, configuration); +``` + +### `schema` + +Type: `String` + +JSON schema. + +Simple example of schema: + +```json +{ + "type": "object", + "properties": { + "name": { + "description": "This is description of option.", + "type": "string" + } + }, + "additionalProperties": false +} +``` + +### `options` + +Type: `Object` + +Object with options. + +```js +import schema from "./path/to/schema.json"; +import { validate } from "schema-utils"; + +const options = { foo: "bar" }; + +validate(schema, { name: 123 }, { name: "MyPlugin" }); +``` + +### `configuration` + +Allow to configure validator. + +There is an alternative method to configure the `name` and`baseDataPath` options via the `title` property in the schema. +For example: + +```json +{ + "title": "My Loader options", + "type": "object", + "properties": { + "name": { + "description": "This is description of option.", + "type": "string" + } + }, + "additionalProperties": false +} +``` + +The last word used for the `baseDataPath` option, other words used for the `name` option. +Based on the example above the `name` option equals `My Loader`, the `baseDataPath` option equals `options`. + +#### `name` + +Type: `Object` +Default: `"Object"` + +Allow to setup name in validation errors. + +```js +import schema from "./path/to/schema.json"; +import { validate } from "schema-utils"; + +const options = { foo: "bar" }; + +validate(schema, options, { name: "MyPlugin" }); +``` + +```shell +Invalid configuration object. MyPlugin has been initialised using a configuration object that does not match the API schema. + - configuration.optionName should be a integer. +``` + +#### `baseDataPath` + +Type: `String` +Default: `"configuration"` + +Allow to setup base data path in validation errors. + +```js +import schema from "./path/to/schema.json"; +import { validate } from "schema-utils"; + +const options = { foo: "bar" }; + +validate(schema, options, { name: "MyPlugin", baseDataPath: "options" }); +``` + +```shell +Invalid options object. MyPlugin has been initialised using an options object that does not match the API schema. + - options.optionName should be a integer. +``` + +#### `postFormatter` + +Type: `Function` +Default: `undefined` + +Allow to reformat errors. + +```js +import schema from "./path/to/schema.json"; +import { validate } from "schema-utils"; + +const options = { foo: "bar" }; + +validate(schema, options, { + name: "MyPlugin", + postFormatter: (formattedError, error) => { + if (error.keyword === "type") { + return `${formattedError}\nAdditional Information.`; + } + + return formattedError; + }, +}); +``` + +```shell +Invalid options object. MyPlugin has been initialized using an options object that does not match the API schema. + - options.optionName should be a integer. + Additional Information. +``` + +## Examples + +**schema.json** + +```json +{ + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "test": { + "anyOf": [ + { "type": "array" }, + { "type": "string" }, + { "instanceof": "RegExp" } + ] + }, + "transform": { + "instanceof": "Function" + }, + "sourceMap": { + "type": "boolean" + } + }, + "additionalProperties": false +} +``` + +### `Loader` + +```js +import { getOptions } from "loader-utils"; +import { validate } from "schema-utils"; + +import schema from "path/to/schema.json"; + +function loader(src, map) { + const options = getOptions(this); + + validate(schema, options, { + name: "Loader Name", + baseDataPath: "options", + }); + + // Code... +} + +export default loader; +``` + +### `Plugin` + +```js +import { validate } from "schema-utils"; + +import schema from "path/to/schema.json"; + +class Plugin { + constructor(options) { + validate(schema, options, { + name: "Plugin Name", + baseDataPath: "options", + }); + + this.options = options; + } + + apply(compiler) { + // Code... + } +} + +export default Plugin; +``` + +### Allow to disable and enable validation (the `validate` function do nothing) + +This can be useful when you don't want to do validation for `production` builds. + +```js +import { disableValidation, enableValidation, validate } from "schema-utils"; + +// Disable validation +disableValidation(); +// Do nothing +validate(schema, options); + +// Enable validation +enableValidation(); +// Will throw an error if schema is not valid +validate(schema, options); + +// Allow to undestand do you need validation or not +const need = needValidate(); + +console.log(need); +``` + +Also you can enable/disable validation using the `process.env.SKIP_VALIDATION` env variable. + +Supported values (case insensitive): + +- `yes`/`y`/`true`/`1`/`on` +- `no`/`n`/`false`/`0`/`off` + +## Contributing + +Please take a moment to read our contributing guidelines if you haven't yet done so. + +[CONTRIBUTING](./.github/CONTRIBUTING.md) + +## License + +[MIT](./LICENSE) + +[npm]: https://img.shields.io/npm/v/schema-utils.svg +[npm-url]: https://npmjs.com/package/schema-utils +[node]: https://img.shields.io/node/v/schema-utils.svg +[node-url]: https://nodejs.org +[tests]: https://github.com/webpack/schema-utils/workflows/schema-utils/badge.svg +[tests-url]: https://github.com/webpack/schema-utils/actions +[cover]: https://codecov.io/gh/webpack/schema-utils/branch/master/graph/badge.svg +[cover-url]: https://codecov.io/gh/webpack/schema-utils +[discussion]: https://img.shields.io/github/discussions/webpack/webpack +[discussion-url]: https://github.com/webpack/webpack/discussions +[size]: https://packagephobia.com/badge?p=schema-utils +[size-url]: https://packagephobia.com/result?p=schema-utils diff --git a/node_modules/schema-utils/declarations/ValidationError.d.ts b/node_modules/schema-utils/declarations/ValidationError.d.ts new file mode 100644 index 0000000..55a8a9a --- /dev/null +++ b/node_modules/schema-utils/declarations/ValidationError.d.ts @@ -0,0 +1,74 @@ +export default ValidationError; +export type JSONSchema6 = import("json-schema").JSONSchema6; +export type JSONSchema7 = import("json-schema").JSONSchema7; +export type Schema = import("./validate").Schema; +export type ValidationErrorConfiguration = + import("./validate").ValidationErrorConfiguration; +export type PostFormatter = import("./validate").PostFormatter; +export type SchemaUtilErrorObject = import("./validate").SchemaUtilErrorObject; +declare class ValidationError extends Error { + /** + * @param {Array} errors + * @param {Schema} schema + * @param {ValidationErrorConfiguration} configuration + */ + constructor( + errors: Array, + schema: Schema, + configuration?: ValidationErrorConfiguration + ); + /** @type {Array} */ + errors: Array; + /** @type {Schema} */ + schema: Schema; + /** @type {string} */ + headerName: string; + /** @type {string} */ + baseDataPath: string; + /** @type {PostFormatter | null} */ + postFormatter: PostFormatter | null; + /** + * @param {string} path + * @returns {Schema} + */ + getSchemaPart(path: string): Schema; + /** + * @param {Schema} schema + * @param {boolean} logic + * @param {Array} prevSchemas + * @returns {string} + */ + formatSchema( + schema: Schema, + logic?: boolean, + prevSchemas?: Array + ): string; + /** + * @param {Schema=} schemaPart + * @param {(boolean | Array)=} additionalPath + * @param {boolean=} needDot + * @param {boolean=} logic + * @returns {string} + */ + getSchemaPartText( + schemaPart?: Schema | undefined, + additionalPath?: (boolean | Array) | undefined, + needDot?: boolean | undefined, + logic?: boolean | undefined + ): string; + /** + * @param {Schema=} schemaPart + * @returns {string} + */ + getSchemaPartDescription(schemaPart?: Schema | undefined): string; + /** + * @param {SchemaUtilErrorObject} error + * @returns {string} + */ + formatValidationError(error: SchemaUtilErrorObject): string; + /** + * @param {Array} errors + * @returns {string} + */ + formatValidationErrors(errors: Array): string; +} diff --git a/node_modules/schema-utils/declarations/index.d.ts b/node_modules/schema-utils/declarations/index.d.ts new file mode 100644 index 0000000..def01ba --- /dev/null +++ b/node_modules/schema-utils/declarations/index.d.ts @@ -0,0 +1,12 @@ +import { validate } from "./validate"; +import { ValidationError } from "./validate"; +import { enableValidation } from "./validate"; +import { disableValidation } from "./validate"; +import { needValidate } from "./validate"; +export { + validate, + ValidationError, + enableValidation, + disableValidation, + needValidate, +}; diff --git a/node_modules/schema-utils/declarations/keywords/absolutePath.d.ts b/node_modules/schema-utils/declarations/keywords/absolutePath.d.ts new file mode 100644 index 0000000..41a54c0 --- /dev/null +++ b/node_modules/schema-utils/declarations/keywords/absolutePath.d.ts @@ -0,0 +1,11 @@ +export default addAbsolutePathKeyword; +export type Ajv = import("ajv").default; +export type SchemaValidateFunction = import("ajv").SchemaValidateFunction; +export type AnySchemaObject = import("ajv").AnySchemaObject; +export type SchemaUtilErrorObject = import("../validate").SchemaUtilErrorObject; +/** + * + * @param {Ajv} ajv + * @returns {Ajv} + */ +declare function addAbsolutePathKeyword(ajv: Ajv): Ajv; diff --git a/node_modules/schema-utils/declarations/keywords/undefinedAsNull.d.ts b/node_modules/schema-utils/declarations/keywords/undefinedAsNull.d.ts new file mode 100644 index 0000000..62a6604 --- /dev/null +++ b/node_modules/schema-utils/declarations/keywords/undefinedAsNull.d.ts @@ -0,0 +1,15 @@ +export default addUndefinedAsNullKeyword; +export type Ajv = import("ajv").default; +export type SchemaValidateFunction = import("ajv").SchemaValidateFunction; +export type AnySchemaObject = import("ajv").AnySchemaObject; +export type ValidateFunction = import("ajv").ValidateFunction; +/** @typedef {import("ajv").default} Ajv */ +/** @typedef {import("ajv").SchemaValidateFunction} SchemaValidateFunction */ +/** @typedef {import("ajv").AnySchemaObject} AnySchemaObject */ +/** @typedef {import("ajv").ValidateFunction} ValidateFunction */ +/** + * + * @param {Ajv} ajv + * @returns {Ajv} + */ +declare function addUndefinedAsNullKeyword(ajv: Ajv): Ajv; diff --git a/node_modules/schema-utils/declarations/util/Range.d.ts b/node_modules/schema-utils/declarations/util/Range.d.ts new file mode 100644 index 0000000..2ba97fc --- /dev/null +++ b/node_modules/schema-utils/declarations/util/Range.d.ts @@ -0,0 +1,79 @@ +export = Range; +/** + * @typedef {[number, boolean]} RangeValue + */ +/** + * @callback RangeValueCallback + * @param {RangeValue} rangeValue + * @returns {boolean} + */ +declare class Range { + /** + * @param {"left" | "right"} side + * @param {boolean} exclusive + * @returns {">" | ">=" | "<" | "<="} + */ + static getOperator( + side: "left" | "right", + exclusive: boolean + ): ">" | ">=" | "<" | "<="; + /** + * @param {number} value + * @param {boolean} logic is not logic applied + * @param {boolean} exclusive is range exclusive + * @returns {string} + */ + static formatRight(value: number, logic: boolean, exclusive: boolean): string; + /** + * @param {number} value + * @param {boolean} logic is not logic applied + * @param {boolean} exclusive is range exclusive + * @returns {string} + */ + static formatLeft(value: number, logic: boolean, exclusive: boolean): string; + /** + * @param {number} start left side value + * @param {number} end right side value + * @param {boolean} startExclusive is range exclusive from left side + * @param {boolean} endExclusive is range exclusive from right side + * @param {boolean} logic is not logic applied + * @returns {string} + */ + static formatRange( + start: number, + end: number, + startExclusive: boolean, + endExclusive: boolean, + logic: boolean + ): string; + /** + * @param {Array} values + * @param {boolean} logic is not logic applied + * @return {RangeValue} computed value and it's exclusive flag + */ + static getRangeValue(values: Array, logic: boolean): RangeValue; + /** @type {Array} */ + _left: Array; + /** @type {Array} */ + _right: Array; + /** + * @param {number} value + * @param {boolean=} exclusive + */ + left(value: number, exclusive?: boolean | undefined): void; + /** + * @param {number} value + * @param {boolean=} exclusive + */ + right(value: number, exclusive?: boolean | undefined): void; + /** + * @param {boolean} logic is not logic applied + * @return {string} "smart" range string representation + */ + format(logic?: boolean): string; +} +declare namespace Range { + export { RangeValue, RangeValueCallback }; +} +type RangeValue = [number, boolean]; +type RangeValueCallback = (rangeValue: RangeValue) => boolean; diff --git a/node_modules/schema-utils/declarations/util/hints.d.ts b/node_modules/schema-utils/declarations/util/hints.d.ts new file mode 100644 index 0000000..e43e32a --- /dev/null +++ b/node_modules/schema-utils/declarations/util/hints.d.ts @@ -0,0 +1,3 @@ +export function stringHints(schema: Schema, logic: boolean): string[]; +export function numberHints(schema: Schema, logic: boolean): string[]; +export type Schema = import("../validate").Schema; diff --git a/node_modules/schema-utils/declarations/util/memorize.d.ts b/node_modules/schema-utils/declarations/util/memorize.d.ts new file mode 100644 index 0000000..5c9968f --- /dev/null +++ b/node_modules/schema-utils/declarations/util/memorize.d.ts @@ -0,0 +1,7 @@ +export default memoize; +/** + * @template T + * @param fn {(function(): any) | undefined} + * @returns {function(): T} + */ +declare function memoize(fn: (() => any) | undefined): () => T; diff --git a/node_modules/schema-utils/declarations/validate.d.ts b/node_modules/schema-utils/declarations/validate.d.ts new file mode 100644 index 0000000..fc5d2ff --- /dev/null +++ b/node_modules/schema-utils/declarations/validate.d.ts @@ -0,0 +1,41 @@ +export type JSONSchema4 = import("json-schema").JSONSchema4; +export type JSONSchema6 = import("json-schema").JSONSchema6; +export type JSONSchema7 = import("json-schema").JSONSchema7; +export type ErrorObject = import("ajv").ErrorObject; +export type Extend = { + formatMinimum?: string | undefined; + formatMaximum?: string | undefined; + formatExclusiveMinimum?: string | undefined; + formatExclusiveMaximum?: string | undefined; + link?: string | undefined; + undefinedAsNull?: boolean | undefined; +}; +export type Schema = (JSONSchema4 | JSONSchema6 | JSONSchema7) & Extend; +export type SchemaUtilErrorObject = ErrorObject & { + children?: Array; +}; +export type PostFormatter = ( + formattedError: string, + error: SchemaUtilErrorObject +) => string; +export type ValidationErrorConfiguration = { + name?: string | undefined; + baseDataPath?: string | undefined; + postFormatter?: PostFormatter | undefined; +}; +/** + * @param {Schema} schema + * @param {Array | object} options + * @param {ValidationErrorConfiguration=} configuration + * @returns {void} + */ +export function validate( + schema: Schema, + options: Array | object, + configuration?: ValidationErrorConfiguration | undefined +): void; +export function enableValidation(): void; +export function disableValidation(): void; +export function needValidate(): boolean; +import ValidationError from "./ValidationError"; +export { ValidationError }; diff --git a/node_modules/schema-utils/dist/ValidationError.js b/node_modules/schema-utils/dist/ValidationError.js new file mode 100644 index 0000000..32fbd68 --- /dev/null +++ b/node_modules/schema-utils/dist/ValidationError.js @@ -0,0 +1,1067 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _memorize = _interopRequireDefault(require("./util/memorize")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/** @typedef {import("json-schema").JSONSchema6} JSONSchema6 */ +/** @typedef {import("json-schema").JSONSchema7} JSONSchema7 */ + +/** @typedef {import("./validate").Schema} Schema */ +/** @typedef {import("./validate").ValidationErrorConfiguration} ValidationErrorConfiguration */ +/** @typedef {import("./validate").PostFormatter} PostFormatter */ +/** @typedef {import("./validate").SchemaUtilErrorObject} SchemaUtilErrorObject */ +/** @enum {number} */ +const SPECIFICITY = { + type: 1, + not: 1, + oneOf: 1, + anyOf: 1, + if: 1, + enum: 1, + const: 1, + instanceof: 1, + required: 2, + pattern: 2, + patternRequired: 2, + format: 2, + formatMinimum: 2, + formatMaximum: 2, + minimum: 2, + exclusiveMinimum: 2, + maximum: 2, + exclusiveMaximum: 2, + multipleOf: 2, + uniqueItems: 2, + contains: 2, + minLength: 2, + maxLength: 2, + minItems: 2, + maxItems: 2, + minProperties: 2, + maxProperties: 2, + dependencies: 2, + propertyNames: 2, + additionalItems: 2, + additionalProperties: 2, + absolutePath: 2 +}; + +/** + * @param {string} value + * @returns {value is number} + */ +function isNumeric(value) { + return /^-?\d+$/.test(value); +} + +/** + * + * @param {Array} array + * @param {(item: SchemaUtilErrorObject) => number} fn + * @returns {Array} + */ +function filterMax(array, fn) { + const evaluatedMax = array.reduce((max, item) => Math.max(max, fn(item)), 0); + return array.filter(item => fn(item) === evaluatedMax); +} + +/** + * + * @param {Array} children + * @returns {Array} + */ +function filterChildren(children) { + let newChildren = children; + newChildren = filterMax(newChildren, + /** + * + * @param {SchemaUtilErrorObject} error + * @returns {number} + */ + error => error.instancePath ? error.instancePath.length : 0); + newChildren = filterMax(newChildren, + /** + * @param {SchemaUtilErrorObject} error + * @returns {number} + */ + error => SPECIFICITY[/** @type {keyof typeof SPECIFICITY} */error.keyword] || 2); + return newChildren; +} + +/** + * Find all children errors + * @param {Array} children + * @param {Array} schemaPaths + * @return {number} returns index of first child + */ +function findAllChildren(children, schemaPaths) { + let i = children.length - 1; + const predicate = + /** + * @param {string} schemaPath + * @returns {boolean} + */ + schemaPath => children[i].schemaPath.indexOf(schemaPath) !== 0; + while (i > -1 && !schemaPaths.every(predicate)) { + if (children[i].keyword === "anyOf" || children[i].keyword === "oneOf") { + const refs = extractRefs(children[i]); + const childrenStart = findAllChildren(children.slice(0, i), refs.concat(children[i].schemaPath)); + i = childrenStart - 1; + } else { + i -= 1; + } + } + return i + 1; +} + +/** + * Extracts all refs from schema + * @param {SchemaUtilErrorObject} error + * @return {Array} + */ +function extractRefs(error) { + const { + schema + } = error; + if (!Array.isArray(schema)) { + return []; + } + return schema.map(({ + $ref + }) => $ref).filter(s => s); +} + +/** + * Groups children by their first level parent (assuming that error is root) + * @param {Array} children + * @return {Array} + */ +function groupChildrenByFirstChild(children) { + const result = []; + let i = children.length - 1; + while (i > 0) { + const child = children[i]; + if (child.keyword === "anyOf" || child.keyword === "oneOf") { + const refs = extractRefs(child); + const childrenStart = findAllChildren(children.slice(0, i), refs.concat(child.schemaPath)); + if (childrenStart !== i) { + result.push(Object.assign({}, child, { + children: children.slice(childrenStart, i) + })); + i = childrenStart; + } else { + result.push(child); + } + } else { + result.push(child); + } + i -= 1; + } + if (i === 0) { + result.push(children[i]); + } + return result.reverse(); +} + +/** + * @param {string} str + * @param {string} prefix + * @returns {string} + */ +function indent(str, prefix) { + return str.replace(/\n(?!$)/g, `\n${prefix}`); +} + +/** + * @param {Schema} schema + * @returns {schema is (Schema & {not: Schema})} + */ +function hasNotInSchema(schema) { + return !!schema.not; +} + +/** + * @param {Schema} schema + * @return {Schema} + */ +function findFirstTypedSchema(schema) { + if (hasNotInSchema(schema)) { + return findFirstTypedSchema(schema.not); + } + return schema; +} + +/** + * @param {Schema} schema + * @return {boolean} + */ +function canApplyNot(schema) { + const typedSchema = findFirstTypedSchema(schema); + return likeNumber(typedSchema) || likeInteger(typedSchema) || likeString(typedSchema) || likeNull(typedSchema) || likeBoolean(typedSchema); +} + +/** + * @param {any} maybeObj + * @returns {boolean} + */ +function isObject(maybeObj) { + return typeof maybeObj === "object" && maybeObj !== null; +} + +/** + * @param {Schema} schema + * @returns {boolean} + */ +function likeNumber(schema) { + return schema.type === "number" || typeof schema.minimum !== "undefined" || typeof schema.exclusiveMinimum !== "undefined" || typeof schema.maximum !== "undefined" || typeof schema.exclusiveMaximum !== "undefined" || typeof schema.multipleOf !== "undefined"; +} + +/** + * @param {Schema} schema + * @returns {boolean} + */ +function likeInteger(schema) { + return schema.type === "integer" || typeof schema.minimum !== "undefined" || typeof schema.exclusiveMinimum !== "undefined" || typeof schema.maximum !== "undefined" || typeof schema.exclusiveMaximum !== "undefined" || typeof schema.multipleOf !== "undefined"; +} + +/** + * @param {Schema} schema + * @returns {boolean} + */ +function likeString(schema) { + return schema.type === "string" || typeof schema.minLength !== "undefined" || typeof schema.maxLength !== "undefined" || typeof schema.pattern !== "undefined" || typeof schema.format !== "undefined" || typeof schema.formatMinimum !== "undefined" || typeof schema.formatMaximum !== "undefined"; +} + +/** + * @param {Schema} schema + * @returns {boolean} + */ +function likeBoolean(schema) { + return schema.type === "boolean"; +} + +/** + * @param {Schema} schema + * @returns {boolean} + */ +function likeArray(schema) { + return schema.type === "array" || typeof schema.minItems === "number" || typeof schema.maxItems === "number" || typeof schema.uniqueItems !== "undefined" || typeof schema.items !== "undefined" || typeof schema.additionalItems !== "undefined" || typeof schema.contains !== "undefined"; +} + +/** + * @param {Schema & {patternRequired?: Array}} schema + * @returns {boolean} + */ +function likeObject(schema) { + return schema.type === "object" || typeof schema.minProperties !== "undefined" || typeof schema.maxProperties !== "undefined" || typeof schema.required !== "undefined" || typeof schema.properties !== "undefined" || typeof schema.patternProperties !== "undefined" || typeof schema.additionalProperties !== "undefined" || typeof schema.dependencies !== "undefined" || typeof schema.propertyNames !== "undefined" || typeof schema.patternRequired !== "undefined"; +} + +/** + * @param {Schema} schema + * @returns {boolean} + */ +function likeNull(schema) { + return schema.type === "null"; +} + +/** + * @param {string} type + * @returns {string} + */ +function getArticle(type) { + if (/^[aeiou]/i.test(type)) { + return "an"; + } + return "a"; +} + +/** + * @param {Schema=} schema + * @returns {string} + */ +function getSchemaNonTypes(schema) { + if (!schema) { + return ""; + } + if (!schema.type) { + if (likeNumber(schema) || likeInteger(schema)) { + return " | should be any non-number"; + } + if (likeString(schema)) { + return " | should be any non-string"; + } + if (likeArray(schema)) { + return " | should be any non-array"; + } + if (likeObject(schema)) { + return " | should be any non-object"; + } + } + return ""; +} + +/** + * @param {Array} hints + * @returns {string} + */ +function formatHints(hints) { + return hints.length > 0 ? `(${hints.join(", ")})` : ""; +} +const getUtilHints = (0, _memorize.default)(() => +// eslint-disable-next-line global-require +require("./util/hints")); + +/** + * @param {Schema} schema + * @param {boolean} logic + * @returns {string[]} + */ +function getHints(schema, logic) { + if (likeNumber(schema) || likeInteger(schema)) { + const util = getUtilHints(); + return util.numberHints(schema, logic); + } else if (likeString(schema)) { + const util = getUtilHints(); + return util.stringHints(schema, logic); + } + return []; +} +class ValidationError extends Error { + /** + * @param {Array} errors + * @param {Schema} schema + * @param {ValidationErrorConfiguration} configuration + */ + constructor(errors, schema, configuration = {}) { + super(); + + /** @type {string} */ + this.name = "ValidationError"; + /** @type {Array} */ + this.errors = errors; + /** @type {Schema} */ + this.schema = schema; + let headerNameFromSchema; + let baseDataPathFromSchema; + if (schema.title && (!configuration.name || !configuration.baseDataPath)) { + const splittedTitleFromSchema = schema.title.match(/^(.+) (.+)$/); + if (splittedTitleFromSchema) { + if (!configuration.name) { + [, headerNameFromSchema] = splittedTitleFromSchema; + } + if (!configuration.baseDataPath) { + [,, baseDataPathFromSchema] = splittedTitleFromSchema; + } + } + } + + /** @type {string} */ + this.headerName = configuration.name || headerNameFromSchema || "Object"; + /** @type {string} */ + this.baseDataPath = configuration.baseDataPath || baseDataPathFromSchema || "configuration"; + + /** @type {PostFormatter | null} */ + this.postFormatter = configuration.postFormatter || null; + const header = `Invalid ${this.baseDataPath} object. ${this.headerName} has been initialized using ${getArticle(this.baseDataPath)} ${this.baseDataPath} object that does not match the API schema.\n`; + + /** @type {string} */ + this.message = `${header}${this.formatValidationErrors(errors)}`; + Error.captureStackTrace(this, this.constructor); + } + + /** + * @param {string} path + * @returns {Schema} + */ + getSchemaPart(path) { + const newPath = path.split("/"); + let schemaPart = this.schema; + for (let i = 1; i < newPath.length; i++) { + const inner = schemaPart[/** @type {keyof Schema} */newPath[i]]; + if (!inner) { + break; + } + schemaPart = inner; + } + return schemaPart; + } + + /** + * @param {Schema} schema + * @param {boolean} logic + * @param {Array} prevSchemas + * @returns {string} + */ + formatSchema(schema, logic = true, prevSchemas = []) { + let newLogic = logic; + const formatInnerSchema = + /** + * + * @param {Object} innerSchema + * @param {boolean=} addSelf + * @returns {string} + */ + (innerSchema, addSelf) => { + if (!addSelf) { + return this.formatSchema(innerSchema, newLogic, prevSchemas); + } + if (prevSchemas.includes(innerSchema)) { + return "(recursive)"; + } + return this.formatSchema(innerSchema, newLogic, prevSchemas.concat(schema)); + }; + if (hasNotInSchema(schema) && !likeObject(schema)) { + if (canApplyNot(schema.not)) { + newLogic = !logic; + return formatInnerSchema(schema.not); + } + const needApplyLogicHere = !schema.not.not; + const prefix = logic ? "" : "non "; + newLogic = !logic; + return needApplyLogicHere ? prefix + formatInnerSchema(schema.not) : formatInnerSchema(schema.not); + } + if ( /** @type {Schema & {instanceof: string | Array}} */schema.instanceof) { + const { + instanceof: value + } = /** @type {Schema & {instanceof: string | Array}} */schema; + const values = !Array.isArray(value) ? [value] : value; + return values.map( + /** + * @param {string} item + * @returns {string} + */ + item => item === "Function" ? "function" : item).join(" | "); + } + if (schema.enum) { + const enumValues = /** @type {Array} */schema.enum.map(item => { + if (item === null && schema.undefinedAsNull) { + return `${JSON.stringify(item)} | undefined`; + } + return JSON.stringify(item); + }).join(" | "); + return `${enumValues}`; + } + if (typeof schema.const !== "undefined") { + return JSON.stringify(schema.const); + } + if (schema.oneOf) { + return (/** @type {Array} */schema.oneOf.map(item => formatInnerSchema(item, true)).join(" | ") + ); + } + if (schema.anyOf) { + return (/** @type {Array} */schema.anyOf.map(item => formatInnerSchema(item, true)).join(" | ") + ); + } + if (schema.allOf) { + return (/** @type {Array} */schema.allOf.map(item => formatInnerSchema(item, true)).join(" & ") + ); + } + if ( /** @type {JSONSchema7} */schema.if) { + const { + if: ifValue, + then: thenValue, + else: elseValue + } = /** @type {JSONSchema7} */schema; + return `${ifValue ? `if ${formatInnerSchema(ifValue)}` : ""}${thenValue ? ` then ${formatInnerSchema(thenValue)}` : ""}${elseValue ? ` else ${formatInnerSchema(elseValue)}` : ""}`; + } + if (schema.$ref) { + return formatInnerSchema(this.getSchemaPart(schema.$ref), true); + } + if (likeNumber(schema) || likeInteger(schema)) { + const [type, ...hints] = getHints(schema, logic); + const str = `${type}${hints.length > 0 ? ` ${formatHints(hints)}` : ""}`; + return logic ? str : hints.length > 0 ? `non-${type} | ${str}` : `non-${type}`; + } + if (likeString(schema)) { + const [type, ...hints] = getHints(schema, logic); + const str = `${type}${hints.length > 0 ? ` ${formatHints(hints)}` : ""}`; + return logic ? str : str === "string" ? "non-string" : `non-string | ${str}`; + } + if (likeBoolean(schema)) { + return `${logic ? "" : "non-"}boolean`; + } + if (likeArray(schema)) { + // not logic already applied in formatValidationError + newLogic = true; + const hints = []; + if (typeof schema.minItems === "number") { + hints.push(`should not have fewer than ${schema.minItems} item${schema.minItems > 1 ? "s" : ""}`); + } + if (typeof schema.maxItems === "number") { + hints.push(`should not have more than ${schema.maxItems} item${schema.maxItems > 1 ? "s" : ""}`); + } + if (schema.uniqueItems) { + hints.push("should not have duplicate items"); + } + const hasAdditionalItems = typeof schema.additionalItems === "undefined" || Boolean(schema.additionalItems); + let items = ""; + if (schema.items) { + if (Array.isArray(schema.items) && schema.items.length > 0) { + items = `${ + /** @type {Array} */schema.items.map(item => formatInnerSchema(item)).join(", ")}`; + if (hasAdditionalItems) { + if (schema.additionalItems && isObject(schema.additionalItems) && Object.keys(schema.additionalItems).length > 0) { + hints.push(`additional items should be ${formatInnerSchema(schema.additionalItems)}`); + } + } + } else if (schema.items && Object.keys(schema.items).length > 0) { + // "additionalItems" is ignored + items = `${formatInnerSchema(schema.items)}`; + } else { + // Fallback for empty `items` value + items = "any"; + } + } else { + // "additionalItems" is ignored + items = "any"; + } + if (schema.contains && Object.keys(schema.contains).length > 0) { + hints.push(`should contains at least one ${this.formatSchema(schema.contains)} item`); + } + return `[${items}${hasAdditionalItems ? ", ..." : ""}]${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`; + } + if (likeObject(schema)) { + // not logic already applied in formatValidationError + newLogic = true; + const hints = []; + if (typeof schema.minProperties === "number") { + hints.push(`should not have fewer than ${schema.minProperties} ${schema.minProperties > 1 ? "properties" : "property"}`); + } + if (typeof schema.maxProperties === "number") { + hints.push(`should not have more than ${schema.maxProperties} ${schema.minProperties && schema.minProperties > 1 ? "properties" : "property"}`); + } + if (schema.patternProperties && Object.keys(schema.patternProperties).length > 0) { + const patternProperties = Object.keys(schema.patternProperties); + hints.push(`additional property names should match pattern${patternProperties.length > 1 ? "s" : ""} ${patternProperties.map(pattern => JSON.stringify(pattern)).join(" | ")}`); + } + const properties = schema.properties ? Object.keys(schema.properties) : []; + /** @type {Array} */ + // @ts-ignore + const required = schema.required ? schema.required : []; + const allProperties = [...new Set( /** @type {Array} */[].concat(required).concat(properties))]; + const objectStructure = allProperties.map(property => { + const isRequired = required.includes(property); + + // Some properties need quotes, maybe we should add check + // Maybe we should output type of property (`foo: string`), but it is looks very unreadable + return `${property}${isRequired ? "" : "?"}`; + }).concat(typeof schema.additionalProperties === "undefined" || Boolean(schema.additionalProperties) ? schema.additionalProperties && isObject(schema.additionalProperties) ? [`: ${formatInnerSchema(schema.additionalProperties)}`] : ["…"] : []).join(", "); + const { + dependencies, + propertyNames, + patternRequired + } = /** @type {Schema & {patternRequired?: Array;}} */schema; + if (dependencies) { + Object.keys(dependencies).forEach(dependencyName => { + const dependency = dependencies[dependencyName]; + if (Array.isArray(dependency)) { + hints.push(`should have ${dependency.length > 1 ? "properties" : "property"} ${dependency.map(dep => `'${dep}'`).join(", ")} when property '${dependencyName}' is present`); + } else { + hints.push(`should be valid according to the schema ${formatInnerSchema(dependency)} when property '${dependencyName}' is present`); + } + }); + } + if (propertyNames && Object.keys(propertyNames).length > 0) { + hints.push(`each property name should match format ${JSON.stringify(schema.propertyNames.format)}`); + } + if (patternRequired && patternRequired.length > 0) { + hints.push(`should have property matching pattern ${patternRequired.map( + /** + * @param {string} item + * @returns {string} + */ + item => JSON.stringify(item))}`); + } + return `object {${objectStructure ? ` ${objectStructure} ` : ""}}${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`; + } + if (likeNull(schema)) { + return `${logic ? "" : "non-"}null`; + } + if (Array.isArray(schema.type)) { + // not logic already applied in formatValidationError + return `${schema.type.join(" | ")}`; + } + + // Fallback for unknown keywords + // not logic already applied in formatValidationError + /* istanbul ignore next */ + return JSON.stringify(schema, null, 2); + } + + /** + * @param {Schema=} schemaPart + * @param {(boolean | Array)=} additionalPath + * @param {boolean=} needDot + * @param {boolean=} logic + * @returns {string} + */ + getSchemaPartText(schemaPart, additionalPath, needDot = false, logic = true) { + if (!schemaPart) { + return ""; + } + if (Array.isArray(additionalPath)) { + for (let i = 0; i < additionalPath.length; i++) { + /** @type {Schema | undefined} */ + const inner = schemaPart[/** @type {keyof Schema} */additionalPath[i]]; + if (inner) { + // eslint-disable-next-line no-param-reassign + schemaPart = inner; + } else { + break; + } + } + } + while (schemaPart.$ref) { + // eslint-disable-next-line no-param-reassign + schemaPart = this.getSchemaPart(schemaPart.$ref); + } + let schemaText = `${this.formatSchema(schemaPart, logic)}${needDot ? "." : ""}`; + if (schemaPart.description) { + schemaText += `\n-> ${schemaPart.description}`; + } + if (schemaPart.link) { + schemaText += `\n-> Read more at ${schemaPart.link}`; + } + return schemaText; + } + + /** + * @param {Schema=} schemaPart + * @returns {string} + */ + getSchemaPartDescription(schemaPart) { + if (!schemaPart) { + return ""; + } + while (schemaPart.$ref) { + // eslint-disable-next-line no-param-reassign + schemaPart = this.getSchemaPart(schemaPart.$ref); + } + let schemaText = ""; + if (schemaPart.description) { + schemaText += `\n-> ${schemaPart.description}`; + } + if (schemaPart.link) { + schemaText += `\n-> Read more at ${schemaPart.link}`; + } + return schemaText; + } + + /** + * @param {SchemaUtilErrorObject} error + * @returns {string} + */ + formatValidationError(error) { + const { + keyword, + instancePath: errorInstancePath + } = error; + const splittedInstancePath = errorInstancePath.split("/"); + /** + * @type {Array} + */ + const defaultValue = []; + const prettyInstancePath = splittedInstancePath.reduce((acc, val) => { + if (val.length > 0) { + if (isNumeric(val)) { + acc.push(`[${val}]`); + } else if (/^\[/.test(val)) { + acc.push(val); + } else { + acc.push(`.${val}`); + } + } + return acc; + }, defaultValue).join(""); + const instancePath = `${this.baseDataPath}${prettyInstancePath}`; + + // const { keyword, instancePath: errorInstancePath } = error; + // const instancePath = `${this.baseDataPath}${errorInstancePath.replace(/\//g, '.')}`; + + switch (keyword) { + case "type": + { + const { + parentSchema, + params + } = error; + switch (params.type) { + case "number": + return `${instancePath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; + case "integer": + return `${instancePath} should be an ${this.getSchemaPartText(parentSchema, false, true)}`; + case "string": + return `${instancePath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; + case "boolean": + return `${instancePath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; + case "array": + return `${instancePath} should be an array:\n${this.getSchemaPartText(parentSchema)}`; + case "object": + return `${instancePath} should be an object:\n${this.getSchemaPartText(parentSchema)}`; + case "null": + return `${instancePath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; + default: + return `${instancePath} should be:\n${this.getSchemaPartText(parentSchema)}`; + } + } + case "instanceof": + { + const { + parentSchema + } = error; + return `${instancePath} should be an instance of ${this.getSchemaPartText(parentSchema, false, true)}`; + } + case "pattern": + { + const { + params, + parentSchema + } = error; + const { + pattern + } = params; + return `${instancePath} should match pattern ${JSON.stringify(pattern)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + case "format": + { + const { + params, + parentSchema + } = error; + const { + format + } = params; + return `${instancePath} should match format ${JSON.stringify(format)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + case "formatMinimum": + case "formatExclusiveMinimum": + case "formatMaximum": + case "formatExclusiveMaximum": + { + const { + params, + parentSchema + } = error; + const { + comparison, + limit + } = params; + return `${instancePath} should be ${comparison} ${JSON.stringify(limit)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + case "minimum": + case "maximum": + case "exclusiveMinimum": + case "exclusiveMaximum": + { + const { + parentSchema, + params + } = error; + const { + comparison, + limit + } = params; + const [, ...hints] = getHints( /** @type {Schema} */parentSchema, true); + if (hints.length === 0) { + hints.push(`should be ${comparison} ${limit}`); + } + return `${instancePath} ${hints.join(" ")}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + case "multipleOf": + { + const { + params, + parentSchema + } = error; + const { + multipleOf + } = params; + return `${instancePath} should be multiple of ${multipleOf}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + case "patternRequired": + { + const { + params, + parentSchema + } = error; + const { + missingPattern + } = params; + return `${instancePath} should have property matching pattern ${JSON.stringify(missingPattern)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + case "minLength": + { + const { + params, + parentSchema + } = error; + const { + limit + } = params; + if (limit === 1) { + return `${instancePath} should be a non-empty string${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + const length = limit - 1; + return `${instancePath} should be longer than ${length} character${length > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + case "minItems": + { + const { + params, + parentSchema + } = error; + const { + limit + } = params; + if (limit === 1) { + return `${instancePath} should be a non-empty array${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + return `${instancePath} should not have fewer than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + case "minProperties": + { + const { + params, + parentSchema + } = error; + const { + limit + } = params; + if (limit === 1) { + return `${instancePath} should be a non-empty object${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + return `${instancePath} should not have fewer than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + case "maxLength": + { + const { + params, + parentSchema + } = error; + const { + limit + } = params; + const max = limit + 1; + return `${instancePath} should be shorter than ${max} character${max > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + case "maxItems": + { + const { + params, + parentSchema + } = error; + const { + limit + } = params; + return `${instancePath} should not have more than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + case "maxProperties": + { + const { + params, + parentSchema + } = error; + const { + limit + } = params; + return `${instancePath} should not have more than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + case "uniqueItems": + { + const { + params, + parentSchema + } = error; + const { + i + } = params; + return `${instancePath} should not contain the item '${ + /** @type {{ data: Array }} **/error.data[i]}' twice${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + case "additionalItems": + { + const { + params, + parentSchema + } = error; + const { + limit + } = params; + return `${instancePath} should not have more than ${limit} items${getSchemaNonTypes(parentSchema)}. These items are valid:\n${this.getSchemaPartText(parentSchema)}`; + } + case "contains": + { + const { + parentSchema + } = error; + return `${instancePath} should contains at least one ${this.getSchemaPartText(parentSchema, ["contains"])} item${getSchemaNonTypes(parentSchema)}.`; + } + case "required": + { + const { + parentSchema, + params + } = error; + const missingProperty = params.missingProperty.replace(/^\./, ""); + const hasProperty = parentSchema && Boolean( /** @type {Schema} */ + parentSchema.properties && /** @type {Schema} */ + parentSchema.properties[missingProperty]); + return `${instancePath} misses the property '${missingProperty}'${getSchemaNonTypes(parentSchema)}.${hasProperty ? ` Should be:\n${this.getSchemaPartText(parentSchema, ["properties", missingProperty])}` : this.getSchemaPartDescription(parentSchema)}`; + } + case "additionalProperties": + { + const { + params, + parentSchema + } = error; + const { + additionalProperty + } = params; + return `${instancePath} has an unknown property '${additionalProperty}'${getSchemaNonTypes(parentSchema)}. These properties are valid:\n${this.getSchemaPartText(parentSchema)}`; + } + case "dependencies": + { + const { + params, + parentSchema + } = error; + const { + property, + deps + } = params; + const dependencies = deps.split(",").map( + /** + * @param {string} dep + * @returns {string} + */ + dep => `'${dep.trim()}'`).join(", "); + return `${instancePath} should have properties ${dependencies} when property '${property}' is present${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + case "propertyNames": + { + const { + params, + parentSchema, + schema + } = error; + const { + propertyName + } = params; + return `${instancePath} property name '${propertyName}' is invalid${getSchemaNonTypes(parentSchema)}. Property names should be match format ${JSON.stringify(schema.format)}.${this.getSchemaPartDescription(parentSchema)}`; + } + case "enum": + { + const { + parentSchema + } = error; + if (parentSchema && /** @type {Schema} */ + parentSchema.enum && /** @type {Schema} */ + parentSchema.enum.length === 1) { + return `${instancePath} should be ${this.getSchemaPartText(parentSchema, false, true)}`; + } + return `${instancePath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`; + } + case "const": + { + const { + parentSchema + } = error; + return `${instancePath} should be equal to constant ${this.getSchemaPartText(parentSchema, false, true)}`; + } + case "not": + { + const postfix = likeObject( /** @type {Schema} */error.parentSchema) ? `\n${this.getSchemaPartText(error.parentSchema)}` : ""; + const schemaOutput = this.getSchemaPartText(error.schema, false, false, false); + if (canApplyNot(error.schema)) { + return `${instancePath} should be any ${schemaOutput}${postfix}.`; + } + const { + schema, + parentSchema + } = error; + return `${instancePath} should not be ${this.getSchemaPartText(schema, false, true)}${parentSchema && likeObject(parentSchema) ? `\n${this.getSchemaPartText(parentSchema)}` : ""}`; + } + case "oneOf": + case "anyOf": + { + const { + parentSchema, + children + } = error; + if (children && children.length > 0) { + if (error.schema.length === 1) { + const lastChild = children[children.length - 1]; + const remainingChildren = children.slice(0, children.length - 1); + return this.formatValidationError(Object.assign({}, lastChild, { + children: remainingChildren, + parentSchema: Object.assign({}, parentSchema, lastChild.parentSchema) + })); + } + let filteredChildren = filterChildren(children); + if (filteredChildren.length === 1) { + return this.formatValidationError(filteredChildren[0]); + } + filteredChildren = groupChildrenByFirstChild(filteredChildren); + return `${instancePath} should be one of these:\n${this.getSchemaPartText(parentSchema)}\nDetails:\n${filteredChildren.map( + /** + * @param {SchemaUtilErrorObject} nestedError + * @returns {string} + */ + nestedError => ` * ${indent(this.formatValidationError(nestedError), " ")}`).join("\n")}`; + } + return `${instancePath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`; + } + case "if": + { + const { + params, + parentSchema + } = error; + const { + failingKeyword + } = params; + return `${instancePath} should match "${failingKeyword}" schema:\n${this.getSchemaPartText(parentSchema, [failingKeyword])}`; + } + case "absolutePath": + { + const { + message, + parentSchema + } = error; + return `${instancePath}: ${message}${this.getSchemaPartDescription(parentSchema)}`; + } + /* istanbul ignore next */ + default: + { + const { + message, + parentSchema + } = error; + const ErrorInJSON = JSON.stringify(error, null, 2); + + // For `custom`, `false schema`, `$ref` keywords + // Fallback for unknown keywords + return `${instancePath} ${message} (${ErrorInJSON}).\n${this.getSchemaPartText(parentSchema, false)}`; + } + } + } + + /** + * @param {Array} errors + * @returns {string} + */ + formatValidationErrors(errors) { + return errors.map(error => { + let formattedError = this.formatValidationError(error); + if (this.postFormatter) { + formattedError = this.postFormatter(formattedError, error); + } + return ` - ${indent(formattedError, " ")}`; + }).join("\n"); + } +} +var _default = ValidationError; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/schema-utils/dist/index.js b/node_modules/schema-utils/dist/index.js new file mode 100644 index 0000000..4574912 --- /dev/null +++ b/node_modules/schema-utils/dist/index.js @@ -0,0 +1,16 @@ +"use strict"; + +const { + validate, + ValidationError, + enableValidation, + disableValidation, + needValidate +} = require("./validate"); +module.exports = { + validate, + ValidationError, + enableValidation, + disableValidation, + needValidate +}; \ No newline at end of file diff --git a/node_modules/schema-utils/dist/keywords/absolutePath.js b/node_modules/schema-utils/dist/keywords/absolutePath.js new file mode 100644 index 0000000..349f6b9 --- /dev/null +++ b/node_modules/schema-utils/dist/keywords/absolutePath.js @@ -0,0 +1,88 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +/** @typedef {import("ajv").default} Ajv */ +/** @typedef {import("ajv").SchemaValidateFunction} SchemaValidateFunction */ +/** @typedef {import("ajv").AnySchemaObject} AnySchemaObject */ +/** @typedef {import("../validate").SchemaUtilErrorObject} SchemaUtilErrorObject */ + +/** + * @param {string} message + * @param {object} schema + * @param {string} data + * @returns {SchemaUtilErrorObject} + */ +function errorMessage(message, schema, data) { + return { + // @ts-ignore + // eslint-disable-next-line no-undefined + dataPath: undefined, + // @ts-ignore + // eslint-disable-next-line no-undefined + schemaPath: undefined, + keyword: "absolutePath", + params: { + absolutePath: data + }, + message, + parentSchema: schema + }; +} + +/** + * @param {boolean} shouldBeAbsolute + * @param {object} schema + * @param {string} data + * @returns {SchemaUtilErrorObject} + */ +function getErrorFor(shouldBeAbsolute, schema, data) { + const message = shouldBeAbsolute ? `The provided value ${JSON.stringify(data)} is not an absolute path!` : `A relative path is expected. However, the provided value ${JSON.stringify(data)} is an absolute path!`; + return errorMessage(message, schema, data); +} + +/** + * + * @param {Ajv} ajv + * @returns {Ajv} + */ +function addAbsolutePathKeyword(ajv) { + ajv.addKeyword({ + keyword: "absolutePath", + type: "string", + errors: true, + /** + * @param {boolean} schema + * @param {AnySchemaObject} parentSchema + * @returns {SchemaValidateFunction} + */ + compile(schema, parentSchema) { + /** @type {SchemaValidateFunction} */ + const callback = data => { + let passes = true; + const isExclamationMarkPresent = data.includes("!"); + if (isExclamationMarkPresent) { + callback.errors = [errorMessage(`The provided value ${JSON.stringify(data)} contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.`, parentSchema, data)]; + passes = false; + } + + // ?:[A-Za-z]:\\ - Windows absolute path + // \\\\ - Windows network absolute path + // \/ - Unix-like OS absolute path + const isCorrectAbsolutePath = schema === /^(?:[A-Za-z]:(\\|\/)|\\\\|\/)/.test(data); + if (!isCorrectAbsolutePath) { + callback.errors = [getErrorFor(schema, parentSchema, data)]; + passes = false; + } + return passes; + }; + callback.errors = []; + return callback; + } + }); + return ajv; +} +var _default = addAbsolutePathKeyword; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/schema-utils/dist/keywords/undefinedAsNull.js b/node_modules/schema-utils/dist/keywords/undefinedAsNull.js new file mode 100644 index 0000000..48a08b4 --- /dev/null +++ b/node_modules/schema-utils/dist/keywords/undefinedAsNull.js @@ -0,0 +1,37 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +/** @typedef {import("ajv").default} Ajv */ +/** @typedef {import("ajv").SchemaValidateFunction} SchemaValidateFunction */ +/** @typedef {import("ajv").AnySchemaObject} AnySchemaObject */ +/** @typedef {import("ajv").ValidateFunction} ValidateFunction */ + +/** + * + * @param {Ajv} ajv + * @returns {Ajv} + */ +function addUndefinedAsNullKeyword(ajv) { + ajv.addKeyword({ + keyword: "undefinedAsNull", + before: "enum", + modifying: true, + /** @type {SchemaValidateFunction} */ + validate(kwVal, data, metadata, dataCxt) { + if (kwVal && dataCxt && metadata && typeof metadata.enum !== "undefined") { + const idx = dataCxt.parentDataProperty; + if (typeof dataCxt.parentData[idx] === "undefined") { + // eslint-disable-next-line no-param-reassign + dataCxt.parentData[dataCxt.parentDataProperty] = null; + } + } + return true; + } + }); + return ajv; +} +var _default = addUndefinedAsNullKeyword; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/schema-utils/dist/util/Range.js b/node_modules/schema-utils/dist/util/Range.js new file mode 100644 index 0000000..318ebab --- /dev/null +++ b/node_modules/schema-utils/dist/util/Range.js @@ -0,0 +1,143 @@ +"use strict"; + +/** + * @typedef {[number, boolean]} RangeValue + */ + +/** + * @callback RangeValueCallback + * @param {RangeValue} rangeValue + * @returns {boolean} + */ + +class Range { + /** + * @param {"left" | "right"} side + * @param {boolean} exclusive + * @returns {">" | ">=" | "<" | "<="} + */ + static getOperator(side, exclusive) { + if (side === "left") { + return exclusive ? ">" : ">="; + } + return exclusive ? "<" : "<="; + } + + /** + * @param {number} value + * @param {boolean} logic is not logic applied + * @param {boolean} exclusive is range exclusive + * @returns {string} + */ + static formatRight(value, logic, exclusive) { + if (logic === false) { + return Range.formatLeft(value, !logic, !exclusive); + } + return `should be ${Range.getOperator("right", exclusive)} ${value}`; + } + + /** + * @param {number} value + * @param {boolean} logic is not logic applied + * @param {boolean} exclusive is range exclusive + * @returns {string} + */ + static formatLeft(value, logic, exclusive) { + if (logic === false) { + return Range.formatRight(value, !logic, !exclusive); + } + return `should be ${Range.getOperator("left", exclusive)} ${value}`; + } + + /** + * @param {number} start left side value + * @param {number} end right side value + * @param {boolean} startExclusive is range exclusive from left side + * @param {boolean} endExclusive is range exclusive from right side + * @param {boolean} logic is not logic applied + * @returns {string} + */ + static formatRange(start, end, startExclusive, endExclusive, logic) { + let result = "should be"; + result += ` ${Range.getOperator(logic ? "left" : "right", logic ? startExclusive : !startExclusive)} ${start} `; + result += logic ? "and" : "or"; + result += ` ${Range.getOperator(logic ? "right" : "left", logic ? endExclusive : !endExclusive)} ${end}`; + return result; + } + + /** + * @param {Array} values + * @param {boolean} logic is not logic applied + * @return {RangeValue} computed value and it's exclusive flag + */ + static getRangeValue(values, logic) { + let minMax = logic ? Infinity : -Infinity; + let j = -1; + const predicate = logic ? /** @type {RangeValueCallback} */ + ([value]) => value <= minMax : /** @type {RangeValueCallback} */ + ([value]) => value >= minMax; + for (let i = 0; i < values.length; i++) { + if (predicate(values[i])) { + [minMax] = values[i]; + j = i; + } + } + if (j > -1) { + return values[j]; + } + return [Infinity, true]; + } + constructor() { + /** @type {Array} */ + this._left = []; + /** @type {Array} */ + this._right = []; + } + + /** + * @param {number} value + * @param {boolean=} exclusive + */ + left(value, exclusive = false) { + this._left.push([value, exclusive]); + } + + /** + * @param {number} value + * @param {boolean=} exclusive + */ + right(value, exclusive = false) { + this._right.push([value, exclusive]); + } + + /** + * @param {boolean} logic is not logic applied + * @return {string} "smart" range string representation + */ + format(logic = true) { + const [start, leftExclusive] = Range.getRangeValue(this._left, logic); + const [end, rightExclusive] = Range.getRangeValue(this._right, !logic); + if (!Number.isFinite(start) && !Number.isFinite(end)) { + return ""; + } + const realStart = leftExclusive ? start + 1 : start; + const realEnd = rightExclusive ? end - 1 : end; + + // e.g. 5 < x < 7, 5 < x <= 6, 6 <= x <= 6 + if (realStart === realEnd) { + return `should be ${logic ? "" : "!"}= ${realStart}`; + } + + // e.g. 4 < x < ∞ + if (Number.isFinite(start) && !Number.isFinite(end)) { + return Range.formatLeft(start, logic, leftExclusive); + } + + // e.g. ∞ < x < 4 + if (!Number.isFinite(start) && Number.isFinite(end)) { + return Range.formatRight(end, logic, rightExclusive); + } + return Range.formatRange(start, end, leftExclusive, rightExclusive, logic); + } +} +module.exports = Range; \ No newline at end of file diff --git a/node_modules/schema-utils/dist/util/hints.js b/node_modules/schema-utils/dist/util/hints.js new file mode 100644 index 0000000..53783d1 --- /dev/null +++ b/node_modules/schema-utils/dist/util/hints.js @@ -0,0 +1,85 @@ +"use strict"; + +const Range = require("./Range"); + +/** @typedef {import("../validate").Schema} Schema */ + +/** + * @param {Schema} schema + * @param {boolean} logic + * @return {string[]} + */ +module.exports.stringHints = function stringHints(schema, logic) { + const hints = []; + let type = "string"; + const currentSchema = { + ...schema + }; + if (!logic) { + const tmpLength = currentSchema.minLength; + const tmpFormat = currentSchema.formatMinimum; + currentSchema.minLength = currentSchema.maxLength; + currentSchema.maxLength = tmpLength; + currentSchema.formatMinimum = currentSchema.formatMaximum; + currentSchema.formatMaximum = tmpFormat; + } + if (typeof currentSchema.minLength === "number") { + if (currentSchema.minLength === 1) { + type = "non-empty string"; + } else { + const length = Math.max(currentSchema.minLength - 1, 0); + hints.push(`should be longer than ${length} character${length > 1 ? "s" : ""}`); + } + } + if (typeof currentSchema.maxLength === "number") { + if (currentSchema.maxLength === 0) { + type = "empty string"; + } else { + const length = currentSchema.maxLength + 1; + hints.push(`should be shorter than ${length} character${length > 1 ? "s" : ""}`); + } + } + if (currentSchema.pattern) { + hints.push(`should${logic ? "" : " not"} match pattern ${JSON.stringify(currentSchema.pattern)}`); + } + if (currentSchema.format) { + hints.push(`should${logic ? "" : " not"} match format ${JSON.stringify(currentSchema.format)}`); + } + if (currentSchema.formatMinimum) { + hints.push(`should be ${currentSchema.formatExclusiveMinimum ? ">" : ">="} ${JSON.stringify(currentSchema.formatMinimum)}`); + } + if (currentSchema.formatMaximum) { + hints.push(`should be ${currentSchema.formatExclusiveMaximum ? "<" : "<="} ${JSON.stringify(currentSchema.formatMaximum)}`); + } + return [type].concat(hints); +}; + +/** + * @param {Schema} schema + * @param {boolean} logic + * @return {string[]} + */ +module.exports.numberHints = function numberHints(schema, logic) { + const hints = [schema.type === "integer" ? "integer" : "number"]; + const range = new Range(); + if (typeof schema.minimum === "number") { + range.left(schema.minimum); + } + if (typeof schema.exclusiveMinimum === "number") { + range.left(schema.exclusiveMinimum, true); + } + if (typeof schema.maximum === "number") { + range.right(schema.maximum); + } + if (typeof schema.exclusiveMaximum === "number") { + range.right(schema.exclusiveMaximum, true); + } + const rangeFormat = range.format(logic); + if (rangeFormat) { + hints.push(rangeFormat); + } + if (typeof schema.multipleOf === "number") { + hints.push(`should${logic ? "" : " not"} be multiple of ${schema.multipleOf}`); + } + return hints; +}; \ No newline at end of file diff --git a/node_modules/schema-utils/dist/util/memorize.js b/node_modules/schema-utils/dist/util/memorize.js new file mode 100644 index 0000000..a2ae3f5 --- /dev/null +++ b/node_modules/schema-utils/dist/util/memorize.js @@ -0,0 +1,30 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +/** + * @template T + * @param fn {(function(): any) | undefined} + * @returns {function(): T} + */ +const memoize = fn => { + let cache = false; + /** @type {T} */ + let result; + return () => { + if (cache) { + return result; + } + result = /** @type {function(): any} */fn(); + cache = true; + // Allow to clean up memory for fn + // and all dependent resources + // eslint-disable-next-line no-undefined, no-param-reassign + fn = undefined; + return result; + }; +}; +var _default = memoize; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/schema-utils/dist/validate.js b/node_modules/schema-utils/dist/validate.js new file mode 100644 index 0000000..3abc3bf --- /dev/null +++ b/node_modules/schema-utils/dist/validate.js @@ -0,0 +1,207 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function () { + return _ValidationError.default; + } +}); +exports.disableValidation = disableValidation; +exports.enableValidation = enableValidation; +exports.needValidate = needValidate; +exports.validate = validate; +var _ValidationError = _interopRequireDefault(require("./ValidationError")); +var _memorize = _interopRequireDefault(require("./util/memorize")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +const getAjv = (0, _memorize.default)(() => { + // Use CommonJS require for ajv libs so TypeScript consumers aren't locked into esModuleInterop (see #110). + // eslint-disable-next-line global-require + const Ajv = require("ajv").default; + // eslint-disable-next-line global-require + const ajvKeywords = require("ajv-keywords").default; + // eslint-disable-next-line global-require + const addFormats = require("ajv-formats").default; + + /** + * @type {Ajv} + */ + const ajv = new Ajv({ + strict: false, + allErrors: true, + verbose: true, + $data: true + }); + ajvKeywords(ajv, ["instanceof", "patternRequired"]); + addFormats(ajv, { + keywords: true + }); + + // Custom keywords + // eslint-disable-next-line global-require + const addAbsolutePathKeyword = require("./keywords/absolutePath").default; + addAbsolutePathKeyword(ajv); + const addUndefinedAsNullKeyword = + // eslint-disable-next-line global-require + require("./keywords/undefinedAsNull").default; + addUndefinedAsNullKeyword(ajv); + return ajv; +}); + +/** @typedef {import("json-schema").JSONSchema4} JSONSchema4 */ +/** @typedef {import("json-schema").JSONSchema6} JSONSchema6 */ +/** @typedef {import("json-schema").JSONSchema7} JSONSchema7 */ +/** @typedef {import("ajv").ErrorObject} ErrorObject */ + +/** + * @typedef {Object} Extend + * @property {string=} formatMinimum + * @property {string=} formatMaximum + * @property {string=} formatExclusiveMinimum + * @property {string=} formatExclusiveMaximum + * @property {string=} link + * @property {boolean=} undefinedAsNull + */ + +/** @typedef {(JSONSchema4 | JSONSchema6 | JSONSchema7) & Extend} Schema */ + +/** @typedef {ErrorObject & { children?: Array }} SchemaUtilErrorObject */ + +/** + * @callback PostFormatter + * @param {string} formattedError + * @param {SchemaUtilErrorObject} error + * @returns {string} + */ + +/** + * @typedef {Object} ValidationErrorConfiguration + * @property {string=} name + * @property {string=} baseDataPath + * @property {PostFormatter=} postFormatter + */ + +/** + * @param {SchemaUtilErrorObject} error + * @param {number} idx + * @returns {SchemaUtilErrorObject} + */ +function applyPrefix(error, idx) { + // eslint-disable-next-line no-param-reassign + error.instancePath = `[${idx}]${error.instancePath}`; + if (error.children) { + error.children.forEach(err => applyPrefix(err, idx)); + } + return error; +} +let skipValidation = false; + +// We use `process.env.SKIP_VALIDATION` because you can have multiple `schema-utils` with different version, +// so we want to disable it globally, `process.env` doesn't supported by browsers, so we have the local `skipValidation` variables + +// Enable validation +function enableValidation() { + skipValidation = false; + + // Disable validation for any versions + if (process && process.env) { + process.env.SKIP_VALIDATION = "n"; + } +} + +// Disable validation +function disableValidation() { + skipValidation = true; + if (process && process.env) { + process.env.SKIP_VALIDATION = "y"; + } +} + +// Check if we need to confirm +function needValidate() { + if (skipValidation) { + return false; + } + if (process && process.env && process.env.SKIP_VALIDATION) { + const value = process.env.SKIP_VALIDATION.trim(); + if (/^(?:y|yes|true|1|on)$/i.test(value)) { + return false; + } + if (/^(?:n|no|false|0|off)$/i.test(value)) { + return true; + } + } + return true; +} + +/** + * @param {Schema} schema + * @param {Array | object} options + * @param {ValidationErrorConfiguration=} configuration + * @returns {void} + */ +function validate(schema, options, configuration) { + if (!needValidate()) { + return; + } + let errors = []; + if (Array.isArray(options)) { + for (let i = 0; i <= options.length - 1; i++) { + errors.push(...validateObject(schema, options[i]).map(err => applyPrefix(err, i))); + } + } else { + errors = validateObject(schema, options); + } + if (errors.length > 0) { + throw new _ValidationError.default(errors, schema, configuration); + } +} + +/** + * @param {Schema} schema + * @param {Array | object} options + * @returns {Array} + */ +function validateObject(schema, options) { + // Not need to cache, because `ajv@8` has built-in cache + const compiledSchema = getAjv().compile(schema); + const valid = compiledSchema(options); + if (valid) return []; + return compiledSchema.errors ? filterErrors(compiledSchema.errors) : []; +} + +/** + * @param {Array} errors + * @returns {Array} + */ +function filterErrors(errors) { + /** @type {Array} */ + let newErrors = []; + for (const error of /** @type {Array} */errors) { + const { + instancePath + } = error; + /** @type {Array} */ + let children = []; + newErrors = newErrors.filter(oldError => { + if (oldError.instancePath.includes(instancePath)) { + if (oldError.children) { + children = children.concat(oldError.children.slice(0)); + } + + // eslint-disable-next-line no-undefined, no-param-reassign + oldError.children = undefined; + children.push(oldError); + return false; + } + return true; + }); + if (children.length) { + error.children = children; + } + newErrors.push(error); + } + return newErrors; +} \ No newline at end of file diff --git a/node_modules/schema-utils/package.json b/node_modules/schema-utils/package.json new file mode 100644 index 0000000..e119e72 --- /dev/null +++ b/node_modules/schema-utils/package.json @@ -0,0 +1,79 @@ +{ + "name": "schema-utils", + "version": "4.2.0", + "description": "webpack Validation Utils", + "license": "MIT", + "repository": "webpack/schema-utils", + "author": "webpack Contrib (https://github.com/webpack-contrib)", + "homepage": "https://github.com/webpack/schema-utils", + "bugs": "https://github.com/webpack/schema-utils/issues", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "main": "dist/index.js", + "types": "declarations/index.d.ts", + "engines": { + "node": ">= 12.13.0" + }, + "scripts": { + "start": "npm run build -- -w", + "clean": "del-cli dist declarations", + "prebuild": "npm run clean", + "build:types": "tsc --declaration --emitDeclarationOnly --outDir declarations && prettier \"declarations/**/*.ts\" --write", + "build:code": "cross-env NODE_ENV=production babel src -d dist --copy-files", + "build": "npm-run-all -p \"build:**\"", + "commitlint": "commitlint --from=master", + "security": "npm audit --production", + "fmt:check": "prettier \"{**/*,*}.{js,json,md,yml,css,ts}\" --list-different", + "lint:js": "eslint --cache .", + "lint:types": "tsc --pretty --noEmit", + "lint": "npm-run-all lint:js lint:types fmt:check", + "fmt": "npm run fmt:check -- --write", + "fix:js": "npm run lint:js -- --fix", + "fix": "npm-run-all fix:js fmt", + "test:only": "cross-env NODE_ENV=test jest", + "test:watch": "npm run test:only -- --watch", + "test:coverage": "npm run test:only -- --collectCoverageFrom=\"src/**/*.js\" --coverage", + "pretest": "npm run lint", + "test": "npm run test:coverage", + "prepare": "npm run build && husky install", + "release": "standard-version" + }, + "files": [ + "dist", + "declarations" + ], + "dependencies": { + "@types/json-schema": "^7.0.9", + "ajv": "^8.9.0", + "ajv-formats": "^2.1.1", + "ajv-keywords": "^5.1.0" + }, + "devDependencies": { + "@babel/cli": "^7.17.0", + "@babel/core": "^7.17.0", + "@babel/preset-env": "^7.16.11", + "@commitlint/cli": "^17.6.1", + "@commitlint/config-conventional": "^16.0.0", + "@webpack-contrib/eslint-config-webpack": "^3.0.0", + "babel-jest": "^27.4.6", + "cross-env": "^7.0.3", + "del": "^6.0.0", + "del-cli": "^4.0.1", + "eslint": "^8.8.0", + "eslint-config-prettier": "^8.3.0", + "eslint-plugin-import": "^2.25.4", + "husky": "^7.0.4", + "jest": "^27.4.7", + "lint-staged": "^13.2.1", + "npm-run-all": "^4.1.5", + "prettier": "^2.5.1", + "standard-version": "^9.3.2", + "typescript": "^4.9.5", + "webpack": "^5.68.0" + }, + "keywords": [ + "webpack" + ] +} diff --git a/node_modules/semver/LICENSE b/node_modules/semver/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/semver/README.md b/node_modules/semver/README.md new file mode 100644 index 0000000..2293a14 --- /dev/null +++ b/node_modules/semver/README.md @@ -0,0 +1,443 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Install + +```bash +npm install semver +```` + +## Usage + +As a node module: + +```js +const semver = require('semver') + +semver.valid('1.2.3') // '1.2.3' +semver.valid('a.b.c') // null +semver.clean(' =v1.2.3 ') // '1.2.3' +semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true +semver.gt('1.2.3', '9.8.7') // false +semver.lt('1.2.3', '9.8.7') // true +semver.minVersion('>=1.0.0') // '1.0.0' +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' +``` + +As a command-line utility: + +``` +$ semver -h + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them. +``` + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` which specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional, but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. The +version `3.4.5` *would* satisfy the range, because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose for this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range matching +semantics. + +Second, a user who has opted into using a prerelease version has +clearly indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +Note that this behavior can be suppressed (treating all prerelease +versions as if they were normal versions, for the purpose of range +matching) by setting the `includePrerelease` flag on the options +object to any +[functions](https://github.com/npm/node-semver#functions) that do +range matching. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta') +// '1.2.4-beta.0' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```bash +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any version satisfies) +* `1.x` := `>=1.0.0 <2.0.0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero element in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0` +* `^0.2.3` := `>=0.2.3 <0.3.0` +* `^0.0.3` := `>=0.0.3 <0.0.4` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0` +* `^0.0.x` := `>=0.0.0 <0.1.0` +* `^0.0` := `>=0.0.0 <0.1.0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0` +* `^0.x` := `>=0.0.0 <1.0.0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `options` object argument. All +options in this object are `false` by default. The options supported +are: + +- `loose` Be more forgiving about not-quite-valid semver strings. + (Any resulting output will always be 100% strict compliant, of + course.) For backwards compatibility reasons, if the `options` + argument is a boolean value instead of an object, it is interpreted + to be the `loose` param. +- `includePrerelease` Set to suppress the [default + behavior](https://github.com/npm/node-semver#prerelease-tags) of + excluding prerelease tagged versions from ranges unless they are + explicitly opted into. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release)`: Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, the `prerelease` will work the + same as `prepatch`. It increments the patch version, then makes a + prerelease. If the input version is already a prerelease it simply + increments it. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. +* `intersects(r1, r2, loose)`: Return true if the two supplied ranges + or comparators intersect. +* `parse(v)`: Attempt to parse a string as a semantic version, returning either + a `SemVer` object or `null`. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the exact same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions + are equal. Sorts in ascending order if passed to `Array.sort()`. + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `diff(v1, v2)`: Returns difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + +### Comparators + +* `intersects(comparator)`: Return true if the comparators intersect + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `minVersion(range)`: Return the lowest version that can possibly match + the given range. +* `gtr(version, range)`: Return `true` if version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) +* `intersects(range)`: Return true if any of the ranges comparators intersect + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so the version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version, options)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver string to +semver. It looks for the first digit in a string, and consumes all +remaining characters which satisfy at least a partial semver (e.g., `1`, +`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer +versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All +surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes +`3.4.0`). Only text which lacks digits will fail coercion (`version one` +is not valid). The maximum length for any semver component considered for +coercion is 16 characters; longer components will be ignored +(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any +semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value +components are invalid (`9999999999999999.4.7.4` is likely invalid). + +If the `options.rtl` flag is set, then `coerce` will return the right-most +coercible tuple that does not share an ending index with a longer coercible +tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not +`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of +any other overlapping SemVer tuple. + +### Clean + +* `clean(version)`: Clean a string to be a valid semver if possible + +This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges. + +ex. +* `s.clean(' = v 2.1.5foo')`: `null` +* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean(' = v 2.1.5-foo')`: `null` +* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean('=v2.1.5')`: `'2.1.5'` +* `s.clean(' =v2.1.5')`: `2.1.5` +* `s.clean(' 2.1.5 ')`: `'2.1.5'` +* `s.clean('~1.0.0')`: `null` diff --git a/node_modules/semver/bin/semver.js b/node_modules/semver/bin/semver.js new file mode 100755 index 0000000..666034a --- /dev/null +++ b/node_modules/semver/bin/semver.js @@ -0,0 +1,174 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +var argv = process.argv.slice(2) + +var versions = [] + +var range = [] + +var inc = null + +var version = require('../package.json').version + +var loose = false + +var includePrerelease = false + +var coerce = false + +var rtl = false + +var identifier + +var semver = require('../semver') + +var reverse = false + +var options = {} + +main() + +function main () { + if (!argv.length) return help() + while (argv.length) { + var a = argv.shift() + var indexOfEqualSign = a.indexOf('=') + if (indexOfEqualSign !== -1) { + a = a.slice(0, indexOfEqualSign) + argv.unshift(a.slice(indexOfEqualSign + 1)) + } + switch (a) { + case '-rv': case '-rev': case '--rev': case '--reverse': + reverse = true + break + case '-l': case '--loose': + loose = true + break + case '-p': case '--include-prerelease': + includePrerelease = true + break + case '-v': case '--version': + versions.push(argv.shift()) + break + case '-i': case '--inc': case '--increment': + switch (argv[0]) { + case 'major': case 'minor': case 'patch': case 'prerelease': + case 'premajor': case 'preminor': case 'prepatch': + inc = argv.shift() + break + default: + inc = 'patch' + break + } + break + case '--preid': + identifier = argv.shift() + break + case '-r': case '--range': + range.push(argv.shift()) + break + case '-c': case '--coerce': + coerce = true + break + case '--rtl': + rtl = true + break + case '--ltr': + rtl = false + break + case '-h': case '--help': case '-?': + return help() + default: + versions.push(a) + break + } + } + + var options = { loose: loose, includePrerelease: includePrerelease, rtl: rtl } + + versions = versions.map(function (v) { + return coerce ? (semver.coerce(v, options) || { version: v }).version : v + }).filter(function (v) { + return semver.valid(v) + }) + if (!versions.length) return fail() + if (inc && (versions.length !== 1 || range.length)) { return failInc() } + + for (var i = 0, l = range.length; i < l; i++) { + versions = versions.filter(function (v) { + return semver.satisfies(v, range[i], options) + }) + if (!versions.length) return fail() + } + return success(versions) +} + +function failInc () { + console.error('--inc can only be used on a single version with no range') + fail() +} + +function fail () { process.exit(1) } + +function success () { + var compare = reverse ? 'rcompare' : 'compare' + versions.sort(function (a, b) { + return semver[compare](a, b, options) + }).map(function (v) { + return semver.clean(v, options) + }).map(function (v) { + return inc ? semver.inc(v, inc, options, identifier) : v + }).forEach(function (v, i, _) { console.log(v) }) +} + +function help () { + console.log(['SemVer ' + version, + '', + 'A JavaScript implementation of the https://semver.org/ specification', + 'Copyright Isaac Z. Schlueter', + '', + 'Usage: semver [options] [ [...]]', + 'Prints valid versions sorted by SemVer precedence', + '', + 'Options:', + '-r --range ', + ' Print versions that match the specified range.', + '', + '-i --increment []', + ' Increment a version by the specified level. Level can', + ' be one of: major, minor, patch, premajor, preminor,', + " prepatch, or prerelease. Default level is 'patch'.", + ' Only one version may be specified.', + '', + '--preid ', + ' Identifier to be used to prefix premajor, preminor,', + ' prepatch or prerelease version increments.', + '', + '-l --loose', + ' Interpret versions and ranges loosely', + '', + '-p --include-prerelease', + ' Always include prerelease versions in range matching', + '', + '-c --coerce', + ' Coerce a string into SemVer if possible', + ' (does not imply --loose)', + '', + '--rtl', + ' Coerce version strings right to left', + '', + '--ltr', + ' Coerce version strings left to right (default)', + '', + 'Program exits successfully if any valid version satisfies', + 'all supplied ranges, and prints all satisfying versions.', + '', + 'If no satisfying versions are found, then exits failure.', + '', + 'Versions are printed in ascending order, so supplying', + 'multiple versions to the utility will just sort them.' + ].join('\n')) +} diff --git a/node_modules/semver/package.json b/node_modules/semver/package.json new file mode 100644 index 0000000..6b970a6 --- /dev/null +++ b/node_modules/semver/package.json @@ -0,0 +1,38 @@ +{ + "name": "semver", + "version": "6.3.1", + "description": "The semantic version parser used by npm.", + "main": "semver.js", + "scripts": { + "test": "tap test/ --100 --timeout=30", + "lint": "echo linting disabled", + "postlint": "template-oss-check", + "template-oss-apply": "template-oss-apply --force", + "lintfix": "npm run lint -- --fix", + "snap": "tap test/ --100 --timeout=30", + "posttest": "npm run lint" + }, + "devDependencies": { + "@npmcli/template-oss": "4.17.0", + "tap": "^12.7.0" + }, + "license": "ISC", + "repository": { + "type": "git", + "url": "https://github.com/npm/node-semver.git" + }, + "bin": { + "semver": "./bin/semver.js" + }, + "files": [ + "bin", + "range.bnf", + "semver.js" + ], + "author": "GitHub Inc.", + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "content": "./scripts/template-oss", + "version": "4.17.0" + } +} diff --git a/node_modules/semver/range.bnf b/node_modules/semver/range.bnf new file mode 100644 index 0000000..d4c6ae0 --- /dev/null +++ b/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | [1-9] ( [0-9] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/node_modules/semver/semver.js b/node_modules/semver/semver.js new file mode 100644 index 0000000..39319c1 --- /dev/null +++ b/node_modules/semver/semver.js @@ -0,0 +1,1643 @@ +exports = module.exports = SemVer + +var debug +/* istanbul ignore next */ +if (typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG)) { + debug = function () { + var args = Array.prototype.slice.call(arguments, 0) + args.unshift('SEMVER') + console.log.apply(console, args) + } +} else { + debug = function () {} +} + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0' + +var MAX_LENGTH = 256 +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16 + +var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 + +// The actual regexps go on exports.re +var re = exports.re = [] +var safeRe = exports.safeRe = [] +var src = exports.src = [] +var t = exports.tokens = {} +var R = 0 + +function tok (n) { + t[n] = R++ +} + +var LETTERDASHNUMBER = '[a-zA-Z0-9-]' + +// Replace some greedy regex tokens to prevent regex dos issues. These regex are +// used internally via the safeRe object since all inputs in this library get +// normalized first to trim and collapse all extra whitespace. The original +// regexes are exported for userland consumption and lower level usage. A +// future breaking change could export the safer regex only with a note that +// all input should have extra whitespace removed. +var safeRegexReplacements = [ + ['\\s', 1], + ['\\d', MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], +] + +function makeSafeRe (value) { + for (var i = 0; i < safeRegexReplacements.length; i++) { + var token = safeRegexReplacements[i][0] + var max = safeRegexReplacements[i][1] + value = value + .split(token + '*').join(token + '{0,' + max + '}') + .split(token + '+').join(token + '{1,' + max + '}') + } + return value +} + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +tok('NUMERICIDENTIFIER') +src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*' +tok('NUMERICIDENTIFIERLOOSE') +src[t.NUMERICIDENTIFIERLOOSE] = '\\d+' + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +tok('NONNUMERICIDENTIFIER') +src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-]' + LETTERDASHNUMBER + '*' + +// ## Main Version +// Three dot-separated numeric identifiers. + +tok('MAINVERSION') +src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIER] + ')' + +tok('MAINVERSIONLOOSE') +src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')' + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +tok('PRERELEASEIDENTIFIER') +src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] + + '|' + src[t.NONNUMERICIDENTIFIER] + ')' + +tok('PRERELEASEIDENTIFIERLOOSE') +src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] + + '|' + src[t.NONNUMERICIDENTIFIER] + ')' + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +tok('PRERELEASE') +src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] + + '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))' + +tok('PRERELEASELOOSE') +src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))' + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +tok('BUILDIDENTIFIER') +src[t.BUILDIDENTIFIER] = LETTERDASHNUMBER + '+' + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +tok('BUILD') +src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] + + '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))' + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +tok('FULL') +tok('FULLPLAIN') +src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] + + src[t.PRERELEASE] + '?' + + src[t.BUILD] + '?' + +src[t.FULL] = '^' + src[t.FULLPLAIN] + '$' + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +tok('LOOSEPLAIN') +src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] + + src[t.PRERELEASELOOSE] + '?' + + src[t.BUILD] + '?' + +tok('LOOSE') +src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$' + +tok('GTLT') +src[t.GTLT] = '((?:<|>)?=?)' + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +tok('XRANGEIDENTIFIERLOOSE') +src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' +tok('XRANGEIDENTIFIER') +src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*' + +tok('XRANGEPLAIN') +src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + + '(?:' + src[t.PRERELEASE] + ')?' + + src[t.BUILD] + '?' + + ')?)?' + +tok('XRANGEPLAINLOOSE') +src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[t.PRERELEASELOOSE] + ')?' + + src[t.BUILD] + '?' + + ')?)?' + +tok('XRANGE') +src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$' +tok('XRANGELOOSE') +src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$' + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +tok('COERCE') +src[t.COERCE] = '(^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])' +tok('COERCERTL') +re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g') +safeRe[t.COERCERTL] = new RegExp(makeSafeRe(src[t.COERCE]), 'g') + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +tok('LONETILDE') +src[t.LONETILDE] = '(?:~>?)' + +tok('TILDETRIM') +src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+' +re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g') +safeRe[t.TILDETRIM] = new RegExp(makeSafeRe(src[t.TILDETRIM]), 'g') +var tildeTrimReplace = '$1~' + +tok('TILDE') +src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$' +tok('TILDELOOSE') +src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$' + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +tok('LONECARET') +src[t.LONECARET] = '(?:\\^)' + +tok('CARETTRIM') +src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+' +re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g') +safeRe[t.CARETTRIM] = new RegExp(makeSafeRe(src[t.CARETTRIM]), 'g') +var caretTrimReplace = '$1^' + +tok('CARET') +src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$' +tok('CARETLOOSE') +src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$' + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +tok('COMPARATORLOOSE') +src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$' +tok('COMPARATOR') +src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$' + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +tok('COMPARATORTRIM') +src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] + + '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')' + +// this one has to use the /g flag +re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g') +safeRe[t.COMPARATORTRIM] = new RegExp(makeSafeRe(src[t.COMPARATORTRIM]), 'g') +var comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +tok('HYPHENRANGE') +src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[t.XRANGEPLAIN] + ')' + + '\\s*$' + +tok('HYPHENRANGELOOSE') +src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[t.XRANGEPLAINLOOSE] + ')' + + '\\s*$' + +// Star ranges basically just allow anything at all. +tok('STAR') +src[t.STAR] = '(<|>)?=?\\s*\\*' + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]) + if (!re[i]) { + re[i] = new RegExp(src[i]) + + // Replace all greedy whitespace to prevent regex dos issues. These regex are + // used internally via the safeRe object since all inputs in this library get + // normalized first to trim and collapse all extra whitespace. The original + // regexes are exported for userland consumption and lower level usage. A + // future breaking change could export the safer regex only with a note that + // all input should have extra whitespace removed. + safeRe[i] = new RegExp(makeSafeRe(src[i])) + } +} + +exports.parse = parse +function parse (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + var r = options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL] + if (!r.test(version)) { + return null + } + + try { + return new SemVer(version, options) + } catch (er) { + return null + } +} + +exports.valid = valid +function valid (version, options) { + var v = parse(version, options) + return v ? v.version : null +} + +exports.clean = clean +function clean (version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} + +exports.SemVer = SemVer + +function SemVer (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + } + + if (!(this instanceof SemVer)) { + return new SemVer(version, options) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + + var m = version.trim().match(options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL]) + + if (!m) { + throw new TypeError('Invalid Version: ' + version) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map(function (id) { + if (/^[0-9]+$/.test(id)) { + var num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() +} + +SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch + if (this.prerelease.length) { + this.version += '-' + this.prerelease.join('.') + } + return this.version +} + +SemVer.prototype.toString = function () { + return this.version +} + +SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return this.compareMain(other) || this.comparePre(other) +} + +SemVer.prototype.compareMain = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) +} + +SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + var i = 0 + do { + var a = this.prerelease[i] + var b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) +} + +SemVer.prototype.compareBuild = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + var i = 0 + do { + var a = this.build[i] + var b = other.build[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) +} + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + var i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break + + default: + throw new Error('invalid increment argument: ' + release) + } + this.format() + this.raw = this.version + return this +} + +exports.inc = inc +function inc (version, release, loose, identifier) { + if (typeof (loose) === 'string') { + identifier = loose + loose = undefined + } + + try { + return new SemVer(version, loose).inc(release, identifier).version + } catch (er) { + return null + } +} + +exports.diff = diff +function diff (version1, version2) { + if (eq(version1, version2)) { + return null + } else { + var v1 = parse(version1) + var v2 = parse(version2) + var prefix = '' + if (v1.prerelease.length || v2.prerelease.length) { + prefix = 'pre' + var defaultResult = 'prerelease' + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } +} + +exports.compareIdentifiers = compareIdentifiers + +var numeric = /^[0-9]+$/ +function compareIdentifiers (a, b) { + var anum = numeric.test(a) + var bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +exports.rcompareIdentifiers = rcompareIdentifiers +function rcompareIdentifiers (a, b) { + return compareIdentifiers(b, a) +} + +exports.major = major +function major (a, loose) { + return new SemVer(a, loose).major +} + +exports.minor = minor +function minor (a, loose) { + return new SemVer(a, loose).minor +} + +exports.patch = patch +function patch (a, loose) { + return new SemVer(a, loose).patch +} + +exports.compare = compare +function compare (a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)) +} + +exports.compareLoose = compareLoose +function compareLoose (a, b) { + return compare(a, b, true) +} + +exports.compareBuild = compareBuild +function compareBuild (a, b, loose) { + var versionA = new SemVer(a, loose) + var versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) +} + +exports.rcompare = rcompare +function rcompare (a, b, loose) { + return compare(b, a, loose) +} + +exports.sort = sort +function sort (list, loose) { + return list.sort(function (a, b) { + return exports.compareBuild(a, b, loose) + }) +} + +exports.rsort = rsort +function rsort (list, loose) { + return list.sort(function (a, b) { + return exports.compareBuild(b, a, loose) + }) +} + +exports.gt = gt +function gt (a, b, loose) { + return compare(a, b, loose) > 0 +} + +exports.lt = lt +function lt (a, b, loose) { + return compare(a, b, loose) < 0 +} + +exports.eq = eq +function eq (a, b, loose) { + return compare(a, b, loose) === 0 +} + +exports.neq = neq +function neq (a, b, loose) { + return compare(a, b, loose) !== 0 +} + +exports.gte = gte +function gte (a, b, loose) { + return compare(a, b, loose) >= 0 +} + +exports.lte = lte +function lte (a, b, loose) { + return compare(a, b, loose) <= 0 +} + +exports.cmp = cmp +function cmp (a, op, b, loose) { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError('Invalid operator: ' + op) + } +} + +exports.Comparator = Comparator +function Comparator (comp, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + if (!(this instanceof Comparator)) { + return new Comparator(comp, options) + } + + comp = comp.trim().split(/\s+/).join(' ') + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) +} + +var ANY = {} +Comparator.prototype.parse = function (comp) { + var r = this.options.loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR] + var m = comp.match(r) + + if (!m) { + throw new TypeError('Invalid comparator: ' + comp) + } + + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } +} + +Comparator.prototype.toString = function () { + return this.value +} + +Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY || version === ANY) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) +} + +Comparator.prototype.intersects = function (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + var rangeTmp + + if (this.operator === '') { + if (this.value === '') { + return true + } + rangeTmp = new Range(comp.value, options) + return satisfies(this.value, rangeTmp, options) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + rangeTmp = new Range(this.value, options) + return satisfies(comp.semver, rangeTmp, options) + } + + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + var sameSemVer = this.semver.version === comp.semver.version + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')) + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')) + + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan +} + +exports.Range = Range +function Range (range, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (range instanceof Range) { + if (range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + return new Range(range.value, options) + } + + if (!(this instanceof Range)) { + return new Range(range, options) + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First reduce all whitespace as much as possible so we do not have to rely + // on potentially slow regexes like \s*. This is then stored and used for + // future error messages as well. + this.raw = range + .trim() + .split(/\s+/) + .join(' ') + + // First, split based on boolean or || + this.set = this.raw.split('||').map(function (range) { + return this.parseRange(range.trim()) + }, this).filter(function (c) { + // throw out any that are not relevant for whatever reason + return c.length + }) + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + this.raw) + } + + this.format() +} + +Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim() + }).join('||').trim() + return this.range +} + +Range.prototype.toString = function () { + return this.range +} + +Range.prototype.parseRange = function (range) { + var loose = this.options.loose + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? safeRe[t.HYPHENRANGELOOSE] : safeRe[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(safeRe[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range, safeRe[t.COMPARATORTRIM]) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(safeRe[t.TILDETRIM], tildeTrimReplace) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(safeRe[t.CARETTRIM], caretTrimReplace) + + // normalize spaces + range = range.split(/\s+/).join(' ') + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR] + var set = range.split(' ').map(function (comp) { + return parseComparator(comp, this.options) + }, this).join(' ').split(/\s+/) + if (this.options.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function (comp) { + return !!comp.match(compRe) + }) + } + set = set.map(function (comp) { + return new Comparator(comp, this.options) + }, this) + + return set +} + +Range.prototype.intersects = function (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some(function (thisComparators) { + return ( + isSatisfiable(thisComparators, options) && + range.set.some(function (rangeComparators) { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every(function (thisComparator) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) +} + +// take a set of comparators and determine whether there +// exists a version which can satisfy it +function isSatisfiable (comparators, options) { + var result = true + var remainingComparators = comparators.slice() + var testComparator = remainingComparators.pop() + + while (result && remainingComparators.length) { + result = remainingComparators.every(function (otherComparator) { + return testComparator.intersects(otherComparator, options) + }) + + testComparator = remainingComparators.pop() + } + + return result +} + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators +function toComparators (range, options) { + return new Range(range, options).set.map(function (comp) { + return comp.map(function (c) { + return c.value + }).join(' ').trim().split(' ') + }) +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator (comp, options) { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +function isX (id) { + return !id || id.toLowerCase() === 'x' || id === '*' +} + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, options) + }).join(' ') +} + +function replaceTilde (comp, options) { + var r = options.loose ? safeRe[t.TILDELOOSE] : safeRe[t.TILDE] + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr) + var ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else if (pr) { + debug('replaceTilde pr', pr) + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } else { + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, options) + }).join(' ') +} + +function replaceCaret (comp, options) { + debug('caret', comp, options) + var r = options.loose ? safeRe[t.CARETLOOSE] : safeRe[t.CARET] + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr) + var ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + if (M === '0') { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else { + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + (+M + 1) + '.0.0' + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0' + } + } + + debug('caret return', ret) + return ret + }) +} + +function replaceXRanges (comp, options) { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options) + }).join(' ') +} + +function replaceXRange (comp, options) { + comp = comp.trim() + var r = options.loose ? safeRe[t.XRANGELOOSE] : safeRe[t.XRANGE] + return comp.replace(r, function (ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + var xM = isX(M) + var xm = xM || isX(m) + var xp = xm || isX(p) + var anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + ret = gtlt + M + '.' + m + '.' + p + pr + } else if (xm) { + ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr + } else if (xp) { + ret = '>=' + M + '.' + m + '.0' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + pr + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars (comp, options) { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(safeRe[t.STAR], '') +} + +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = '>=' + fM + '.0.0' + } else if (isX(fp)) { + from = '>=' + fM + '.' + fm + '.0' + } else { + from = '>=' + from + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = '<' + (+tM + 1) + '.0.0' + } else if (isX(tp)) { + to = '<' + tM + '.' + (+tm + 1) + '.0' + } else if (tpr) { + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr + } else { + to = '<=' + to + } + + return (from + ' ' + to).trim() +} + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false +} + +function testSet (set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} + +exports.satisfies = satisfies +function satisfies (version, range, options) { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} + +exports.maxSatisfying = maxSatisfying +function maxSatisfying (versions, range, options) { + var max = null + var maxSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} + +exports.minSatisfying = minSatisfying +function minSatisfying (versions, range, options) { + var min = null + var minSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} + +exports.minVersion = minVersion +function minVersion (range, loose) { + range = new Range(range, loose) + + var minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + comparators.forEach(function (comparator) { + // Clone to avoid manipulating the comparator's semver object. + var compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error('Unexpected operation: ' + comparator.operator) + } + }) + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} + +exports.validRange = validRange +function validRange (range, options) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} + +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr +function ltr (version, range, options) { + return outside(version, range, '<', options) +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr +function gtr (version, range, options) { + return outside(version, range, '>', options) +} + +exports.outside = outside +function outside (version, range, hilo, options) { + version = new SemVer(version, options) + range = new Range(range, options) + + var gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + var high = null + var low = null + + comparators.forEach(function (comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} + +exports.prerelease = prerelease +function prerelease (version, options) { + var parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} + +exports.intersects = intersects +function intersects (r1, r2, options) { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) +} + +exports.coerce = coerce +function coerce (version, options) { + if (version instanceof SemVer) { + return version + } + + if (typeof version === 'number') { + version = String(version) + } + + if (typeof version !== 'string') { + return null + } + + options = options || {} + + var match = null + if (!options.rtl) { + match = version.match(safeRe[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + var next + while ((next = safeRe[t.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + safeRe[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length + } + // leave it in a clean state + safeRe[t.COERCERTL].lastIndex = -1 + } + + if (match === null) { + return null + } + + return parse(match[2] + + '.' + (match[3] || '0') + + '.' + (match[4] || '0'), options) +} diff --git a/node_modules/serialize-javascript/LICENSE b/node_modules/serialize-javascript/LICENSE new file mode 100644 index 0000000..263382a --- /dev/null +++ b/node_modules/serialize-javascript/LICENSE @@ -0,0 +1,27 @@ +Copyright 2014 Yahoo! Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the Yahoo! Inc. nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL YAHOO! INC. BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/serialize-javascript/README.md b/node_modules/serialize-javascript/README.md new file mode 100644 index 0000000..e6523ba --- /dev/null +++ b/node_modules/serialize-javascript/README.md @@ -0,0 +1,143 @@ +Serialize JavaScript +==================== + +Serialize JavaScript to a _superset_ of JSON that includes regular expressions, dates and functions. + +[![npm Version][npm-badge]][npm] +[![Dependency Status][david-badge]][david] +![Test](https://github.com/yahoo/serialize-javascript/workflows/Test/badge.svg) + +## Overview + +The code in this package began its life as an internal module to [express-state][]. To expand its usefulness, it now lives as `serialize-javascript` — an independent package on npm. + +You're probably wondering: **What about `JSON.stringify()`!?** We've found that sometimes we need to serialize JavaScript **functions**, **regexps**, **dates**, **sets** or **maps**. A great example is a web app that uses client-side URL routing where the route definitions are regexps that need to be shared from the server to the client. But this module is also great for communicating between node processes. + +The string returned from this package's single export function is literal JavaScript which can be saved to a `.js` file, or be embedded into an HTML document by making the content of a `' +}); +``` + +The above will produce the following string, HTML-escaped output which is safe to put into an HTML document as it will not cause the inline script element to terminate: + +```js +'{"haxorXSS":"\\u003C\\u002Fscript\\u003E"}' +``` + +> You can pass an optional `unsafe` argument to `serialize()` for straight serialization. + +### Options + +The `serialize()` function accepts an `options` object as its second argument. All options are being defaulted to `undefined`: + +#### `options.space` + +This option is the same as the `space` argument that can be passed to [`JSON.stringify`][JSON.stringify]. It can be used to add whitespace and indentation to the serialized output to make it more readable. + +```js +serialize(obj, {space: 2}); +``` + +#### `options.isJSON` + +This option is a signal to `serialize()` that the object being serialized does not contain any function or regexps values. This enables a hot-path that allows serialization to be over 3x faster. If you're serializing a lot of data, and know its pure JSON, then you can enable this option for a speed-up. + +**Note:** That when using this option, the output will still be escaped to protect against XSS. + +```js +serialize(obj, {isJSON: true}); +``` + +#### `options.unsafe` + +This option is to signal `serialize()` that we want to do a straight conversion, without the XSS protection. This options needs to be explicitly set to `true`. HTML characters and JavaScript line terminators will not be escaped. You will have to roll your own. + +```js +serialize(obj, {unsafe: true}); +``` + +#### `options.ignoreFunction` + +This option is to signal `serialize()` that we do not want serialize JavaScript function. +Just treat function like `JSON.stringify` do, but other features will work as expected. + +```js +serialize(obj, {ignoreFunction: true}); +``` + +## Deserializing + +For some use cases you might also need to deserialize the string. This is explicitly not part of this module. However, you can easily write it yourself: + +```js +function deserialize(serializedJavascript){ + return eval('(' + serializedJavascript + ')'); +} +``` + +**Note:** Don't forget the parentheses around the serialized javascript, as the opening bracket `{` will be considered to be the start of a body. + +## License + +This software is free to use under the Yahoo! Inc. BSD license. +See the [LICENSE file][LICENSE] for license text and copyright information. + + +[npm]: https://www.npmjs.org/package/serialize-javascript +[npm-badge]: https://img.shields.io/npm/v/serialize-javascript.svg?style=flat-square +[david]: https://david-dm.org/yahoo/serialize-javascript +[david-badge]: https://img.shields.io/david/yahoo/serialize-javascript.svg?style=flat-square +[express-state]: https://github.com/yahoo/express-state +[JSON.stringify]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify +[LICENSE]: https://github.com/yahoo/serialize-javascript/blob/main/LICENSE diff --git a/node_modules/serialize-javascript/index.js b/node_modules/serialize-javascript/index.js new file mode 100644 index 0000000..156f8f9 --- /dev/null +++ b/node_modules/serialize-javascript/index.js @@ -0,0 +1,268 @@ +/* +Copyright (c) 2014, Yahoo! Inc. All rights reserved. +Copyrights licensed under the New BSD License. +See the accompanying LICENSE file for terms. +*/ + +'use strict'; + +var randomBytes = require('randombytes'); + +// Generate an internal UID to make the regexp pattern harder to guess. +var UID_LENGTH = 16; +var UID = generateUID(); +var PLACE_HOLDER_REGEXP = new RegExp('(\\\\)?"@__(F|R|D|M|S|A|U|I|B|L)-' + UID + '-(\\d+)__@"', 'g'); + +var IS_NATIVE_CODE_REGEXP = /\{\s*\[native code\]\s*\}/g; +var IS_PURE_FUNCTION = /function.*?\(/; +var IS_ARROW_FUNCTION = /.*?=>.*?/; +var UNSAFE_CHARS_REGEXP = /[<>\/\u2028\u2029]/g; + +var RESERVED_SYMBOLS = ['*', 'async']; + +// Mapping of unsafe HTML and invalid JavaScript line terminator chars to their +// Unicode char counterparts which are safe to use in JavaScript strings. +var ESCAPED_CHARS = { + '<' : '\\u003C', + '>' : '\\u003E', + '/' : '\\u002F', + '\u2028': '\\u2028', + '\u2029': '\\u2029' +}; + +function escapeUnsafeChars(unsafeChar) { + return ESCAPED_CHARS[unsafeChar]; +} + +function generateUID() { + var bytes = randomBytes(UID_LENGTH); + var result = ''; + for(var i=0; i arg1+5 + if(IS_ARROW_FUNCTION.test(serializedFn)) { + return serializedFn; + } + + var argsStartsAt = serializedFn.indexOf('('); + var def = serializedFn.substr(0, argsStartsAt) + .trim() + .split(' ') + .filter(function(val) { return val.length > 0 }); + + var nonReservedSymbols = def.filter(function(val) { + return RESERVED_SYMBOLS.indexOf(val) === -1 + }); + + // enhanced literal objects, example: {key() {}} + if(nonReservedSymbols.length > 0) { + return (def.indexOf('async') > -1 ? 'async ' : '') + 'function' + + (def.join('').indexOf('*') > -1 ? '*' : '') + + serializedFn.substr(argsStartsAt); + } + + // arrow functions + return serializedFn; + } + + // Check if the parameter is function + if (options.ignoreFunction && typeof obj === "function") { + obj = undefined; + } + // Protects against `JSON.stringify()` returning `undefined`, by serializing + // to the literal string: "undefined". + if (obj === undefined) { + return String(obj); + } + + var str; + + // Creates a JSON string representation of the value. + // NOTE: Node 0.12 goes into slow mode with extra JSON.stringify() args. + if (options.isJSON && !options.space) { + str = JSON.stringify(obj); + } else { + str = JSON.stringify(obj, options.isJSON ? null : replacer, options.space); + } + + // Protects against `JSON.stringify()` returning `undefined`, by serializing + // to the literal string: "undefined". + if (typeof str !== 'string') { + return String(str); + } + + // Replace unsafe HTML and invalid JavaScript line terminator chars with + // their safe Unicode char counterpart. This _must_ happen before the + // regexps and functions are serialized and added back to the string. + if (options.unsafe !== true) { + str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars); + } + + if (functions.length === 0 && regexps.length === 0 && dates.length === 0 && maps.length === 0 && sets.length === 0 && arrays.length === 0 && undefs.length === 0 && infinities.length === 0 && bigInts.length === 0 && urls.length === 0) { + return str; + } + + // Replaces all occurrences of function, regexp, date, map and set placeholders in the + // JSON string with their string representations. If the original value can + // not be found, then `undefined` is used. + return str.replace(PLACE_HOLDER_REGEXP, function (match, backSlash, type, valueIndex) { + // The placeholder may not be preceded by a backslash. This is to prevent + // replacing things like `"a\"@__R--0__@"` and thus outputting + // invalid JS. + if (backSlash) { + return match; + } + + if (type === 'D') { + return "new Date(\"" + dates[valueIndex].toISOString() + "\")"; + } + + if (type === 'R') { + return "new RegExp(" + serialize(regexps[valueIndex].source) + ", \"" + regexps[valueIndex].flags + "\")"; + } + + if (type === 'M') { + return "new Map(" + serialize(Array.from(maps[valueIndex].entries()), options) + ")"; + } + + if (type === 'S') { + return "new Set(" + serialize(Array.from(sets[valueIndex].values()), options) + ")"; + } + + if (type === 'A') { + return "Array.prototype.slice.call(" + serialize(Object.assign({ length: arrays[valueIndex].length }, arrays[valueIndex]), options) + ")"; + } + + if (type === 'U') { + return 'undefined' + } + + if (type === 'I') { + return infinities[valueIndex]; + } + + if (type === 'B') { + return "BigInt(\"" + bigInts[valueIndex] + "\")"; + } + + if (type === 'L') { + return "new URL(" + serialize(urls[valueIndex].toString(), options) + ")"; + } + + var fn = functions[valueIndex]; + + return serializeFunc(fn); + }); +} diff --git a/node_modules/serialize-javascript/package.json b/node_modules/serialize-javascript/package.json new file mode 100644 index 0000000..ee71672 --- /dev/null +++ b/node_modules/serialize-javascript/package.json @@ -0,0 +1,36 @@ +{ + "name": "serialize-javascript", + "version": "6.0.2", + "description": "Serialize JavaScript to a superset of JSON that includes regular expressions and functions.", + "main": "index.js", + "scripts": { + "benchmark": "node -v && node test/benchmark/serialize.js", + "test": "nyc --reporter=lcov mocha test/unit" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/yahoo/serialize-javascript.git" + }, + "keywords": [ + "serialize", + "serialization", + "javascript", + "js", + "json" + ], + "author": "Eric Ferraiuolo ", + "license": "BSD-3-Clause", + "bugs": { + "url": "https://github.com/yahoo/serialize-javascript/issues" + }, + "homepage": "https://github.com/yahoo/serialize-javascript", + "devDependencies": { + "benchmark": "^2.1.4", + "chai": "^4.1.0", + "mocha": "^10.0.0", + "nyc": "^15.0.0" + }, + "dependencies": { + "randombytes": "^2.1.0" + } +} diff --git a/node_modules/source-map-support/LICENSE.md b/node_modules/source-map-support/LICENSE.md new file mode 100644 index 0000000..6247ca9 --- /dev/null +++ b/node_modules/source-map-support/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Evan Wallace + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/source-map-support/README.md b/node_modules/source-map-support/README.md new file mode 100644 index 0000000..40228b7 --- /dev/null +++ b/node_modules/source-map-support/README.md @@ -0,0 +1,284 @@ +# Source Map Support +[![Build Status](https://travis-ci.org/evanw/node-source-map-support.svg?branch=master)](https://travis-ci.org/evanw/node-source-map-support) + +This module provides source map support for stack traces in node via the [V8 stack trace API](https://github.com/v8/v8/wiki/Stack-Trace-API). It uses the [source-map](https://github.com/mozilla/source-map) module to replace the paths and line numbers of source-mapped files with their original paths and line numbers. The output mimics node's stack trace format with the goal of making every compile-to-JS language more of a first-class citizen. Source maps are completely general (not specific to any one language) so you can use source maps with multiple compile-to-JS languages in the same node process. + +## Installation and Usage + +#### Node support + +``` +$ npm install source-map-support +``` + +Source maps can be generated using libraries such as [source-map-index-generator](https://github.com/twolfson/source-map-index-generator). Once you have a valid source map, place a source mapping comment somewhere in the file (usually done automatically or with an option by your transpiler): + +``` +//# sourceMappingURL=path/to/source.map +``` + +If multiple sourceMappingURL comments exist in one file, the last sourceMappingURL comment will be +respected (e.g. if a file mentions the comment in code, or went through multiple transpilers). +The path should either be absolute or relative to the compiled file. + +From here you have two options. + +##### CLI Usage + +```bash +node -r source-map-support/register compiled.js +``` + +##### Programmatic Usage + +Put the following line at the top of the compiled file. + +```js +require('source-map-support').install(); +``` + +It is also possible to install the source map support directly by +requiring the `register` module which can be handy with ES6: + +```js +import 'source-map-support/register' + +// Instead of: +import sourceMapSupport from 'source-map-support' +sourceMapSupport.install() +``` +Note: if you're using babel-register, it includes source-map-support already. + +It is also very useful with Mocha: + +``` +$ mocha --require source-map-support/register tests/ +``` + +#### Browser support + +This library also works in Chrome. While the DevTools console already supports source maps, the V8 engine doesn't and `Error.prototype.stack` will be incorrect without this library. Everything will just work if you deploy your source files using [browserify](http://browserify.org/). Just make sure to pass the `--debug` flag to the browserify command so your source maps are included in the bundled code. + +This library also works if you use another build process or just include the source files directly. In this case, include the file `browser-source-map-support.js` in your page and call `sourceMapSupport.install()`. It contains the whole library already bundled for the browser using browserify. + +```html + + +``` + +This library also works if you use AMD (Asynchronous Module Definition), which is used in tools like [RequireJS](http://requirejs.org/). Just list `browser-source-map-support` as a dependency: + +```html + +``` + +## Options + +This module installs two things: a change to the `stack` property on `Error` objects and a handler for uncaught exceptions that mimics node's default exception handler (the handler can be seen in the demos below). You may want to disable the handler if you have your own uncaught exception handler. This can be done by passing an argument to the installer: + +```js +require('source-map-support').install({ + handleUncaughtExceptions: false +}); +``` + +This module loads source maps from the filesystem by default. You can provide alternate loading behavior through a callback as shown below. For example, [Meteor](https://github.com/meteor) keeps all source maps cached in memory to avoid disk access. + +```js +require('source-map-support').install({ + retrieveSourceMap: function(source) { + if (source === 'compiled.js') { + return { + url: 'original.js', + map: fs.readFileSync('compiled.js.map', 'utf8') + }; + } + return null; + } +}); +``` + +The module will by default assume a browser environment if XMLHttpRequest and window are defined. If either of these do not exist it will instead assume a node environment. +In some rare cases, e.g. when running a browser emulation and where both variables are also set, you can explictly specify the environment to be either 'browser' or 'node'. + +```js +require('source-map-support').install({ + environment: 'node' +}); +``` + +To support files with inline source maps, the `hookRequire` options can be specified, which will monitor all source files for inline source maps. + + +```js +require('source-map-support').install({ + hookRequire: true +}); +``` + +This monkey patches the `require` module loading chain, so is not enabled by default and is not recommended for any sort of production usage. + +## Demos + +#### Basic Demo + +original.js: + +```js +throw new Error('test'); // This is the original code +``` + +compiled.js: + +```js +require('source-map-support').install(); + +throw new Error('test'); // This is the compiled code +// The next line defines the sourceMapping. +//# sourceMappingURL=compiled.js.map +``` + +compiled.js.map: + +```json +{ + "version": 3, + "file": "compiled.js", + "sources": ["original.js"], + "names": [], + "mappings": ";;AAAA,MAAM,IAAI" +} +``` + +Run compiled.js using node (notice how the stack trace uses original.js instead of compiled.js): + +``` +$ node compiled.js + +original.js:1 +throw new Error('test'); // This is the original code + ^ +Error: test + at Object. (original.js:1:7) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +#### TypeScript Demo + +demo.ts: + +```typescript +declare function require(name: string); +require('source-map-support').install(); +class Foo { + constructor() { this.bar(); } + bar() { throw new Error('this is a demo'); } +} +new Foo(); +``` + +Compile and run the file using the TypeScript compiler from the terminal: + +``` +$ npm install source-map-support typescript +$ node_modules/typescript/bin/tsc -sourcemap demo.ts +$ node demo.js + +demo.ts:5 + bar() { throw new Error('this is a demo'); } + ^ +Error: this is a demo + at Foo.bar (demo.ts:5:17) + at new Foo (demo.ts:4:24) + at Object. (demo.ts:7:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +There is also the option to use `-r source-map-support/register` with typescript, without the need add the `require('source-map-support').install()` in the code base: + +``` +$ npm install source-map-support typescript +$ node_modules/typescript/bin/tsc -sourcemap demo.ts +$ node -r source-map-support/register demo.js + +demo.ts:5 + bar() { throw new Error('this is a demo'); } + ^ +Error: this is a demo + at Foo.bar (demo.ts:5:17) + at new Foo (demo.ts:4:24) + at Object. (demo.ts:7:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +#### CoffeeScript Demo + +demo.coffee: + +```coffee +require('source-map-support').install() +foo = -> + bar = -> throw new Error 'this is a demo' + bar() +foo() +``` + +Compile and run the file using the CoffeeScript compiler from the terminal: + +```sh +$ npm install source-map-support coffeescript +$ node_modules/.bin/coffee --map --compile demo.coffee +$ node demo.js + +demo.coffee:3 + bar = -> throw new Error 'this is a demo' + ^ +Error: this is a demo + at bar (demo.coffee:3:22) + at foo (demo.coffee:4:3) + at Object. (demo.coffee:5:1) + at Object. (demo.coffee:1:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) +``` + +## Tests + +This repo contains both automated tests for node and manual tests for the browser. The automated tests can be run using mocha (type `mocha` in the root directory). To run the manual tests: + +* Build the tests using `build.js` +* Launch the HTTP server (`npm run serve-tests`) and visit + * http://127.0.0.1:1336/amd-test + * http://127.0.0.1:1336/browser-test + * http://127.0.0.1:1336/browserify-test - **Currently not working** due to a bug with browserify (see [pull request #66](https://github.com/evanw/node-source-map-support/pull/66) for details). +* For `header-test`, run `server.js` inside that directory and visit http://127.0.0.1:1337/ + +## License + +This code is available under the [MIT license](http://opensource.org/licenses/MIT). diff --git a/node_modules/source-map-support/browser-source-map-support.js b/node_modules/source-map-support/browser-source-map-support.js new file mode 100644 index 0000000..782da50 --- /dev/null +++ b/node_modules/source-map-support/browser-source-map-support.js @@ -0,0 +1,114 @@ +/* + * Support for source maps in V8 stack traces + * https://github.com/evanw/node-source-map-support + */ +/* + The buffer module from node.js, for the browser. + + @author Feross Aboukhadijeh + license MIT +*/ +(this.define||function(R,U){this.sourceMapSupport=U()})("browser-source-map-support",function(R){(function e(C,J,A){function p(f,c){if(!J[f]){if(!C[f]){var l="function"==typeof require&&require;if(!c&&l)return l(f,!0);if(t)return t(f,!0);throw Error("Cannot find module '"+f+"'");}l=J[f]={exports:{}};C[f][0].call(l.exports,function(q){var r=C[f][1][q];return p(r?r:q)},l,l.exports,e,C,J,A)}return J[f].exports}for(var t="function"==typeof require&&require,m=0;mm)return-1;if(58>m)return m-48+52;if(91>m)return m-65;if(123>m)return m-97+26}var t="undefined"!==typeof Uint8Array?Uint8Array:Array;e.toByteArray=function(m){function f(d){q[k++]=d}if(0>16);f((u&65280)>>8);f(u&255)}2===l?(u=p(m.charAt(c))<<2|p(m.charAt(c+1))>>4,f(u&255)):1===l&&(u=p(m.charAt(c))<<10|p(m.charAt(c+1))<<4|p(m.charAt(c+2))>>2,f(u>>8&255),f(u&255));return q};e.fromByteArray=function(m){var f=m.length%3,c="",l;var q=0;for(l=m.length-f;q> +18&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>12&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>6&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r&63);c+=r}switch(f){case 1:r=m[m.length-1];c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>2);c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<4&63);c+="==";break;case 2:r=(m[m.length-2]<<8)+ +m[m.length-1],c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>10),c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>4&63),c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<2&63),c+="="}return c}})("undefined"===typeof A?this.base64js={}:A)},{}],3:[function(C,J,A){},{}],4:[function(C,J,A){(function(e){var p=Object.prototype.toString,t="function"===typeof e.alloc&&"function"===typeof e.allocUnsafe&&"function"=== +typeof e.from;J.exports=function(m,f,c){if("number"===typeof m)throw new TypeError('"value" argument must not be a number');if("ArrayBuffer"===p.call(m).slice(8,-1)){f>>>=0;var l=m.byteLength-f;if(0>l)throw new RangeError("'offset' is out of bounds");if(void 0===c)c=l;else if(c>>>=0,c>l)throw new RangeError("'length' is out of bounds");return t?e.from(m.slice(f,f+c)):new e(new Uint8Array(m.slice(f,f+c)))}if("string"===typeof m){c=f;if("string"!==typeof c||""===c)c="utf8";if(!e.isEncoding(c))throw new TypeError('"encoding" must be a valid string encoding'); +return t?e.from(m,c):new e(m,c)}return t?e.from(m):new e(m)}}).call(this,C("buffer").Buffer)},{buffer:5}],5:[function(C,J,A){function e(a,b,h){if(!(this instanceof e))return new e(a,b,h);var w=typeof a;if("number"===w)var y=0>>0:0;else if("string"===w){if("base64"===b)for(a=(a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")).replace(L,"");0!==a.length%4;)a+="=";y=e.byteLength(a,b)}else if("object"===w&&null!==a)"Buffer"===a.type&&z(a.data)&&(a=a.data),y=0<+a.length?Math.floor(+a.length):0;else throw new TypeError("must start with number, buffer, array or string"); +if(this.length>G)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+G.toString(16)+" bytes");if(e.TYPED_ARRAY_SUPPORT)var I=e._augment(new Uint8Array(y));else I=this,I.length=y,I._isBuffer=!0;if(e.TYPED_ARRAY_SUPPORT&&"number"===typeof a.byteLength)I._set(a);else{var K=a;if(z(K)||e.isBuffer(K)||K&&"object"===typeof K&&"number"===typeof K.length)if(e.isBuffer(a))for(b=0;ba)throw new RangeError("offset is not uint");if(a+b>h)throw new RangeError("Trying to access beyond buffer length");}function m(a,b,h,w,y,I){if(!e.isBuffer(a))throw new TypeError("buffer must be a Buffer instance");if(b>y||ba.length)throw new TypeError("index out of range"); +}function f(a,b,h,w){0>b&&(b=65535+b+1);for(var y=0,I=Math.min(a.length-h,2);y>>8*(w?y:1-y)}function c(a,b,h,w){0>b&&(b=4294967295+b+1);for(var y=0,I=Math.min(a.length-h,4);y>>8*(w?y:3-y)&255}function l(a,b,h,w,y,I){if(b>y||ba.length)throw new TypeError("index out of range");}function q(a,b,h,w,y){y||l(a,b,h,4,3.4028234663852886E38,-3.4028234663852886E38);v.write(a,b,h,w,23,4);return h+4}function r(a, +b,h,w,y){y||l(a,b,h,8,1.7976931348623157E308,-1.7976931348623157E308);v.write(a,b,h,w,52,8);return h+8}function k(a){for(var b=[],h=0;h=w)b.push(w);else{var y=h;55296<=w&&57343>=w&&h++;w=encodeURIComponent(a.slice(y,h+1)).substr(1).split("%");for(y=0;y=b.length||y>=a.length);y++)b[y+ +h]=a[y];return y}function g(a){try{return decodeURIComponent(a)}catch(b){return String.fromCharCode(65533)}}var n=C("base64-js"),v=C("ieee754"),z=C("is-array");A.Buffer=e;A.SlowBuffer=e;A.INSPECT_MAX_BYTES=50;e.poolSize=8192;var G=1073741823;e.TYPED_ARRAY_SUPPORT=function(){try{var a=new ArrayBuffer(0),b=new Uint8Array(a);b.foo=function(){return 42};return 42===b.foo()&&"function"===typeof b.subarray&&0===(new Uint8Array(1)).subarray(1,1).byteLength}catch(h){return!1}}();e.isBuffer=function(a){return!(null== +a||!a._isBuffer)};e.compare=function(a,b){if(!e.isBuffer(a)||!e.isBuffer(b))throw new TypeError("Arguments must be Buffers");for(var h=a.length,w=b.length,y=0,I=Math.min(h,w);y>>1;break;case "utf8":case "utf-8":h=k(a).length;break;case "base64":h=n.toByteArray(a).length; +break;default:h=a.length}return h};e.prototype.length=void 0;e.prototype.parent=void 0;e.prototype.toString=function(a,b,h){var w=!1;b>>>=0;h=void 0===h||Infinity===h?this.length:h>>>0;a||(a="utf8");0>b&&(b=0);h>this.length&&(h=this.length);if(h<=b)return"";for(;;)switch(a){case "hex":a=b;b=h;h=this.length;if(!a||0>a)a=0;if(!b||0>b||b>h)b=h;w="";for(h=a;hw?"0"+w.toString(16):w.toString(16),w=a+w;return w;case "utf8":case "utf-8":w=a="";for(h=Math.min(this.length,h);b= +this[b]?(a+=g(w)+String.fromCharCode(this[b]),w=""):w+="%"+this[b].toString(16);return a+g(w);case "ascii":return p(this,b,h);case "binary":return p(this,b,h);case "base64":return b=0===b&&h===this.length?n.fromByteArray(this):n.fromByteArray(this.slice(b,h)),b;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":b=this.slice(b,h);h="";for(a=0;ab&&(a+=" ... "));return""};e.prototype.compare=function(a){if(!e.isBuffer(a))throw new TypeError("Argument must be a Buffer");return e.compare(this,a)};e.prototype.get=function(a){console.log(".get() is deprecated. Access using array indexes instead."); +return this.readUInt8(a)};e.prototype.set=function(a,b){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(a,b)};e.prototype.write=function(a,b,h,w){if(isFinite(b))isFinite(h)||(w=h,h=void 0);else{var y=w;w=b;b=h;h=y}b=Number(b)||0;y=this.length-b;h?(h=Number(h),h>y&&(h=y)):h=y;w=String(w||"utf8").toLowerCase();switch(w){case "hex":b=Number(b)||0;w=this.length-b;h?(h=Number(h),h>w&&(h=w)):h=w;w=a.length;if(0!==w%2)throw Error("Invalid hex string");h>w/ +2&&(h=w/2);for(w=0;w>8;K%=256;y.push(K);y.push(w)}a=d(y,this,b,h,2);break;default:throw new TypeError("Unknown encoding: "+ +w);}return a};e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};e.prototype.slice=function(a,b){var h=this.length;a=~~a;b=void 0===b?h:~~b;0>a?(a+=h,0>a&&(a=0)):a>h&&(a=h);0>b?(b+=h,0>b&&(b=0)):b>h&&(b=h);b>>=0;h||m(this,a,b,1,255,0);e.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));this[b]=a;return b+1};e.prototype.writeUInt16LE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,2,65535,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8):f(this,a,b,!0);return b+2};e.prototype.writeUInt16BE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,2,65535,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=a):f(this,a,b,!1);return b+2};e.prototype.writeUInt32LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,4294967295,0);e.TYPED_ARRAY_SUPPORT?(this[b+3]=a>>>24,this[b+2]=a>>>16,this[b+1]=a>>>8,this[b]=a):c(this,a,b,!0);return b+4};e.prototype.writeUInt32BE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,4,4294967295,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+2]=a>>>8,this[b+3]=a):c(this,a,b,!1);return b+4};e.prototype.writeInt8=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,1,127,-128);e.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));0>a&&(a=255+a+1);this[b]=a;return b+1};e.prototype.writeInt16LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,2,32767,-32768);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8):f(this,a,b,!0);return b+2};e.prototype.writeInt16BE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,2,32767,-32768);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=a):f(this,a,b,!1);return b+2};e.prototype.writeInt32LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,2147483647,-2147483648);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8,this[b+2]=a>>>16,this[b+3]=a>>>24):c(this,a,b,!0);return b+4};e.prototype.writeInt32BE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,2147483647,-2147483648);0>a&&(a=4294967295+a+1);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+ +2]=a>>>8,this[b+3]=a):c(this,a,b,!1);return b+4};e.prototype.writeFloatLE=function(a,b,h){return q(this,a,b,!0,h)};e.prototype.writeFloatBE=function(a,b,h){return q(this,a,b,!1,h)};e.prototype.writeDoubleLE=function(a,b,h){return r(this,a,b,!0,h)};e.prototype.writeDoubleBE=function(a,b,h){return r(this,a,b,!1,h)};e.prototype.copy=function(a,b,h,w){h||(h=0);w||0===w||(w=this.length);b||(b=0);if(w!==h&&0!==a.length&&0!==this.length){if(wb||b>=a.length)throw new TypeError("targetStart out of bounds"); +if(0>h||h>=this.length)throw new TypeError("sourceStart out of bounds");if(0>w||w>this.length)throw new TypeError("sourceEnd out of bounds");w>this.length&&(w=this.length);a.length-bw||!e.TYPED_ARRAY_SUPPORT)for(var y=0;yb||b>=this.length)throw new TypeError("start out of bounds"); +if(0>h||h>this.length)throw new TypeError("end out of bounds");if("number"===typeof a)for(;b>1,r=-7;f=t?f-1:0;var k=t?-1:1,u=e[p+f];f+=k;t=u&(1<<-r)-1;u>>=-r;for(r+=c;0>=-r;for(r+=m;0>1,u=23===f?Math.pow(2,-24)-Math.pow(2,-77):0;c=m?0:c-1;var d=m?1:-1,g=0>p||0===p&&0>1/p?1:0;p=Math.abs(p);isNaN(p)||Infinity===p?(p=isNaN(p)?1:0,m=r):(m=Math.floor(Math.log(p)/Math.LN2),1>p*(l=Math.pow(2,-m))&&(m--,l*=2),p=1<=m+k?p+u/l:p+u*Math.pow(2,1-k),2<=p*l&&(m++,l/=2),m+k>=r?(p=0,m=r):1<=m+k?(p=(p*l-1)*Math.pow(2,f),m+=k):(p=p*Math.pow(2,k-1)*Math.pow(2,f),m=0));for(;8<=f;e[t+c]=p&255,c+= +d,p/=256,f-=8);m=m<z?[]:n.slice(v,z-v+1)}c=A.resolve(c).substr(1);l=A.resolve(l).substr(1); +for(var r=q(c.split("/")),k=q(l.split("/")),u=Math.min(r.length,k.length),d=u,g=0;gl&&(l=c.length+l);return c.substr(l,q)}}).call(this,C("g5I+bs"))},{"g5I+bs":9}],9:[function(C,J,A){function e(){}C=J.exports={};C.nextTick=function(){if("undefined"!==typeof window&&window.setImmediate)return function(t){return window.setImmediate(t)};if("undefined"!==typeof window&&window.postMessage&&window.addEventListener){var p=[];window.addEventListener("message",function(t){var m=t.source;m!==window&&null!== +m||"process-tick"!==t.data||(t.stopPropagation(),0p?(-p<<1)+1:p<<1;do p=m&31,m>>>=5,0=f)throw Error("Expected more digits in base 64 VLQ value.");var q=e.decode(p.charCodeAt(t++));if(-1===q)throw Error("Invalid base64 digit: "+p.charAt(t-1));var r=!!(q&32);q&=31;c+=q<>1;m.value=1===(c&1)?-p:p;m.rest=t}},{"./base64":12}],12:[function(C, +J,A){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");A.encode=function(p){if(0<=p&&p=p?p-65:97<=p&&122>=p?p-97+26:48<=p&&57>=p?p-48+52:43==p?62:47==p?63:-1}},{}],13:[function(C,J,A){function e(p,t,m,f,c,l){var q=Math.floor((t-p)/2)+p,r=c(m,f[q],!0);return 0===r?q:0p?-1:p}A.GREATEST_LOWER_BOUND=1;A.LEAST_UPPER_BOUND=2;A.search=function(p,t,m,f){if(0===t.length)return-1;p=e(-1,t.length,p,t,m,f||A.GREATEST_LOWER_BOUND);if(0>p)return-1;for(;0<=p-1&&0===m(t[p],t[p-1],!0);)--p;return p}},{}],14:[function(C,J,A){function e(){this._array=[];this._sorted=!0;this._last={generatedLine:-1,generatedColumn:0}}var p=C("./util");e.prototype.unsortedForEach=function(t,m){this._array.forEach(t,m)};e.prototype.add=function(t){var m=this._last,f=m.generatedLine, +c=t.generatedLine,l=m.generatedColumn,q=t.generatedColumn;c>f||c==f&&q>=l||0>=p.compareByGeneratedPositionsInflated(m,t)?this._last=t:this._sorted=!1;this._array.push(t)};e.prototype.toArray=function(){this._sorted||(this._array.sort(p.compareByGeneratedPositionsInflated),this._sorted=!0);return this._array};A.MappingList=e},{"./util":19}],15:[function(C,J,A){function e(t,m,f){var c=t[m];t[m]=t[f];t[f]=c}function p(t,m,f,c){if(f=m(t[r],q)&&(l+=1,e(t,l,r));e(t,l+1,r);l+=1;p(t,m,f,l-1);p(t,m,l+1,c)}}A.quickSort=function(t,m){p(t,m,0,t.length-1)}},{}],16:[function(C,J,A){function e(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));return null!=d.sections?new m(d,u):new p(d,u)}function p(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));var g=f.getArg(d,"version"),n=f.getArg(d,"sources"),v=f.getArg(d,"names",[]),z=f.getArg(d,"sourceRoot",null),G=f.getArg(d,"sourcesContent",null),D=f.getArg(d, +"mappings");d=f.getArg(d,"file",null);if(g!=this._version)throw Error("Unsupported version: "+g);z&&(z=f.normalize(z));n=n.map(String).map(f.normalize).map(function(L){return z&&f.isAbsolute(z)&&f.isAbsolute(L)?f.relative(z,L):L});this._names=l.fromArray(v.map(String),!0);this._sources=l.fromArray(n,!0);this.sourceRoot=z;this.sourcesContent=G;this._mappings=D;this._sourceMapURL=u;this.file=d}function t(){this.generatedColumn=this.generatedLine=0;this.name=this.originalColumn=this.originalLine=this.source= +null}function m(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));var g=f.getArg(d,"version");d=f.getArg(d,"sections");if(g!=this._version)throw Error("Unsupported version: "+g);this._sources=new l;this._names=new l;var n={line:-1,column:0};this._sections=d.map(function(v){if(v.url)throw Error("Support for url field in sections not implemented.");var z=f.getArg(v,"offset"),G=f.getArg(z,"line"),D=f.getArg(z,"column");if(G=k[d])throw new TypeError("Line must be greater than or equal to 1, got "+ +k[d]);if(0>k[g])throw new TypeError("Column must be greater than or equal to 0, got "+k[g]);return c.search(k,u,n,v)};p.prototype.computeColumnSpans=function(){for(var k=0;k=this._sources.size()&&!this.sourcesContent.some(function(k){return null==k}):!1};p.prototype.sourceContentFor=function(k,u){if(!this.sourcesContent)return null;var d=k;null!=this.sourceRoot&&(d=f.relative(this.sourceRoot,d));if(this._sources.has(d))return this.sourcesContent[this._sources.indexOf(d)]; +var g=this.sources,n;for(n=0;n +g||95!==d.charCodeAt(g-1)||95!==d.charCodeAt(g-2)||111!==d.charCodeAt(g-3)||116!==d.charCodeAt(g-4)||111!==d.charCodeAt(g-5)||114!==d.charCodeAt(g-6)||112!==d.charCodeAt(g-7)||95!==d.charCodeAt(g-8)||95!==d.charCodeAt(g-9))return!1;for(g-=10;0<=g;g--)if(36!==d.charCodeAt(g))return!1;return!0}function r(d,g){return d===g?0:null===d?1:null===g?-1:d>g?1:-1}A.getArg=function(d,g,n){if(g in d)return d[g];if(3===arguments.length)return n;throw Error('"'+g+'" is a required argument.');};var k=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/, +u=/^data:.+,.+$/;A.urlParse=e;A.urlGenerate=p;A.normalize=t;A.join=m;A.isAbsolute=function(d){return"/"===d.charAt(0)||k.test(d)};A.relative=function(d,g){""===d&&(d=".");d=d.replace(/\/$/,"");for(var n=0;0!==g.indexOf(d+"/");){var v=d.lastIndexOf("/");if(0>v)return g;d=d.slice(0,v);if(d.match(/^([^\/]+:\/)?\/*$/))return g;++n}return Array(n+1).join("../")+g.substr(d.length+1)};C=!("__proto__"in Object.create(null));A.toSetString=C?f:c;A.fromSetString=C?f:l;A.compareByOriginalPositions=function(d, +g,n){var v=r(d.source,g.source);if(0!==v)return v;v=d.originalLine-g.originalLine;if(0!==v)return v;v=d.originalColumn-g.originalColumn;if(0!==v||n)return v;v=d.generatedColumn-g.generatedColumn;if(0!==v)return v;v=d.generatedLine-g.generatedLine;return 0!==v?v:r(d.name,g.name)};A.compareByGeneratedPositionsDeflated=function(d,g,n){var v=d.generatedLine-g.generatedLine;if(0!==v)return v;v=d.generatedColumn-g.generatedColumn;if(0!==v||n)return v;v=r(d.source,g.source);if(0!==v)return v;v=d.originalLine- +g.originalLine;if(0!==v)return v;v=d.originalColumn-g.originalColumn;return 0!==v?v:r(d.name,g.name)};A.compareByGeneratedPositionsInflated=function(d,g){var n=d.generatedLine-g.generatedLine;if(0!==n)return n;n=d.generatedColumn-g.generatedColumn;if(0!==n)return n;n=r(d.source,g.source);if(0!==n)return n;n=d.originalLine-g.originalLine;if(0!==n)return n;n=d.originalColumn-g.originalColumn;return 0!==n?n:r(d.name,g.name)};A.parseSourceMapInput=function(d){return JSON.parse(d.replace(/^\)]}'[^\n]*\n/, +""))};A.computeSourceURL=function(d,g,n){g=g||"";d&&("/"!==d[d.length-1]&&"/"!==g[0]&&(d+="/"),g=d+g);if(n){d=e(n);if(!d)throw Error("sourceMapURL could not be parsed");d.path&&(n=d.path.lastIndexOf("/"),0<=n&&(d.path=d.path.substring(0,n+1)));g=m(p(d),g)}return t(g)}},{}],20:[function(C,J,A){A.SourceMapGenerator=C("./lib/source-map-generator").SourceMapGenerator;A.SourceMapConsumer=C("./lib/source-map-consumer").SourceMapConsumer;A.SourceNode=C("./lib/source-node").SourceNode},{"./lib/source-map-consumer":16, +"./lib/source-map-generator":17,"./lib/source-node":18}],21:[function(C,J,A){(function(e){function p(){return"browser"===a?!0:"node"===a?!1:"undefined"!==typeof window&&"function"===typeof XMLHttpRequest&&!(window.require&&window.module&&window.process&&"renderer"===window.process.type)}function t(x){return function(B){for(var F=0;F";B=this.getLineNumber();null!=B&&(x+=":"+B,(B= +this.getColumnNumber())&&(x+=":"+B))}B="";var F=this.getFunctionName(),E=!0,H=this.isConstructor();if(this.isToplevel()||H)H?B+="new "+(F||""):F?B+=F:(B+=x,E=!1);else{H=this.getTypeName();"[object Object]"===H&&(H="null");var M=this.getMethodName();F?(H&&0!=F.indexOf(H)&&(B+=H+"."),B+=F,M&&F.indexOf("."+M)!=F.length-M.length-1&&(B+=" [as "+M+"]")):B+=H+"."+(M||"")}E&&(B+=" ("+x+")");return B}function q(x){var B={};Object.getOwnPropertyNames(Object.getPrototypeOf(x)).forEach(function(F){B[F]= +/^(?:is|get)/.test(F)?function(){return x[F].call(x)}:x[F]});B.toString=l;return B}function r(x,B){void 0===B&&(B={nextPosition:null,curPosition:null});if(x.isNative())return B.curPosition=null,x;var F=x.getFileName()||x.getScriptNameOrSourceURL();if(F){var E=x.getLineNumber(),H=x.getColumnNumber()-1,M=/^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/,S=M.test;var V="object"===typeof e&&null!==e?e.version:"";M=S.call(M,V)?0:62;1===E&&H>M&&!p()&&!x.isEval()&&(H-=M);var O= +f({source:F,line:E,column:H});B.curPosition=O;x=q(x);var T=x.getFunctionName;x.getFunctionName=function(){return null==B.nextPosition?T():B.nextPosition.name||T()};x.getFileName=function(){return O.source};x.getLineNumber=function(){return O.line};x.getColumnNumber=function(){return O.column+1};x.getScriptNameOrSourceURL=function(){return O.source};return x}var Q=x.isEval()&&x.getEvalOrigin();Q&&(Q=c(Q),x=q(x),x.getEvalOrigin=function(){return Q});return x}function k(x,B){L&&(b={},h={});for(var F= +(x.name||"Error")+": "+(x.message||""),E={nextPosition:null,curPosition:null},H=[],M=B.length-1;0<=M;M--)H.push("\n at "+r(B[M],E)),E.nextPosition=E.curPosition;E.curPosition=E.nextPosition=null;return F+H.reverse().join("")}function u(x){var B=/\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(x.stack);if(B){x=B[1];var F=+B[2];B=+B[3];var E=b[x];if(!E&&v&&v.existsSync(x))try{E=v.readFileSync(x,"utf8")}catch(H){E=""}if(E&&(E=E.split(/(?:\r\n|\r|\n)/)[F-1]))return x+":"+F+"\n"+E+"\n"+Array(B).join(" ")+ +"^"}return null}function d(){var x=e.emit;e.emit=function(B){if("uncaughtException"===B){var F=arguments[1]&&arguments[1].stack,E=0 C:/dir/file + '/'; // file:///root-dir/file -> /root-dir/file + }); + } + if (path in fileContentsCache) { + return fileContentsCache[path]; + } + + var contents = ''; + try { + if (!fs) { + // Use SJAX if we are in the browser + var xhr = new XMLHttpRequest(); + xhr.open('GET', path, /** async */ false); + xhr.send(null); + if (xhr.readyState === 4 && xhr.status === 200) { + contents = xhr.responseText; + } + } else if (fs.existsSync(path)) { + // Otherwise, use the filesystem + contents = fs.readFileSync(path, 'utf8'); + } + } catch (er) { + /* ignore any errors */ + } + + return fileContentsCache[path] = contents; +}); + +// Support URLs relative to a directory, but be careful about a protocol prefix +// in case we are in the browser (i.e. directories may start with "http://" or "file:///") +function supportRelativeURL(file, url) { + if (!file) return url; + var dir = path.dirname(file); + var match = /^\w+:\/\/[^\/]*/.exec(dir); + var protocol = match ? match[0] : ''; + var startPath = dir.slice(protocol.length); + if (protocol && /^\/\w\:/.test(startPath)) { + // handle file:///C:/ paths + protocol += '/'; + return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, '/'); + } + return protocol + path.resolve(dir.slice(protocol.length), url); +} + +function retrieveSourceMapURL(source) { + var fileData; + + if (isInBrowser()) { + try { + var xhr = new XMLHttpRequest(); + xhr.open('GET', source, false); + xhr.send(null); + fileData = xhr.readyState === 4 ? xhr.responseText : null; + + // Support providing a sourceMappingURL via the SourceMap header + var sourceMapHeader = xhr.getResponseHeader("SourceMap") || + xhr.getResponseHeader("X-SourceMap"); + if (sourceMapHeader) { + return sourceMapHeader; + } + } catch (e) { + } + } + + // Get the URL of the source map + fileData = retrieveFile(source); + var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg; + // Keep executing the search to find the *last* sourceMappingURL to avoid + // picking up sourceMappingURLs from comments, strings, etc. + var lastMatch, match; + while (match = re.exec(fileData)) lastMatch = match; + if (!lastMatch) return null; + return lastMatch[1]; +}; + +// Can be overridden by the retrieveSourceMap option to install. Takes a +// generated source filename; returns a {map, optional url} object, or null if +// there is no source map. The map field may be either a string or the parsed +// JSON object (ie, it must be a valid argument to the SourceMapConsumer +// constructor). +var retrieveSourceMap = handlerExec(retrieveMapHandlers); +retrieveMapHandlers.push(function(source) { + var sourceMappingURL = retrieveSourceMapURL(source); + if (!sourceMappingURL) return null; + + // Read the contents of the source map + var sourceMapData; + if (reSourceMap.test(sourceMappingURL)) { + // Support source map URL as a data url + var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1); + sourceMapData = bufferFrom(rawData, "base64").toString(); + sourceMappingURL = source; + } else { + // Support source map URLs relative to the source URL + sourceMappingURL = supportRelativeURL(source, sourceMappingURL); + sourceMapData = retrieveFile(sourceMappingURL); + } + + if (!sourceMapData) { + return null; + } + + return { + url: sourceMappingURL, + map: sourceMapData + }; +}); + +function mapSourcePosition(position) { + var sourceMap = sourceMapCache[position.source]; + if (!sourceMap) { + // Call the (overrideable) retrieveSourceMap function to get the source map. + var urlAndMap = retrieveSourceMap(position.source); + if (urlAndMap) { + sourceMap = sourceMapCache[position.source] = { + url: urlAndMap.url, + map: new SourceMapConsumer(urlAndMap.map) + }; + + // Load all sources stored inline with the source map into the file cache + // to pretend like they are already loaded. They may not exist on disk. + if (sourceMap.map.sourcesContent) { + sourceMap.map.sources.forEach(function(source, i) { + var contents = sourceMap.map.sourcesContent[i]; + if (contents) { + var url = supportRelativeURL(sourceMap.url, source); + fileContentsCache[url] = contents; + } + }); + } + } else { + sourceMap = sourceMapCache[position.source] = { + url: null, + map: null + }; + } + } + + // Resolve the source URL relative to the URL of the source map + if (sourceMap && sourceMap.map && typeof sourceMap.map.originalPositionFor === 'function') { + var originalPosition = sourceMap.map.originalPositionFor(position); + + // Only return the original position if a matching line was found. If no + // matching line is found then we return position instead, which will cause + // the stack trace to print the path and line for the compiled file. It is + // better to give a precise location in the compiled file than a vague + // location in the original file. + if (originalPosition.source !== null) { + originalPosition.source = supportRelativeURL( + sourceMap.url, originalPosition.source); + return originalPosition; + } + } + + return position; +} + +// Parses code generated by FormatEvalOrigin(), a function inside V8: +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js +function mapEvalOrigin(origin) { + // Most eval() calls are in this format + var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin); + if (match) { + var position = mapSourcePosition({ + source: match[2], + line: +match[3], + column: match[4] - 1 + }); + return 'eval at ' + match[1] + ' (' + position.source + ':' + + position.line + ':' + (position.column + 1) + ')'; + } + + // Parse nested eval() calls using recursion + match = /^eval at ([^(]+) \((.+)\)$/.exec(origin); + if (match) { + return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')'; + } + + // Make sure we still return useful information if we didn't find anything + return origin; +} + +// This is copied almost verbatim from the V8 source code at +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The +// implementation of wrapCallSite() used to just forward to the actual source +// code of CallSite.prototype.toString but unfortunately a new release of V8 +// did something to the prototype chain and broke the shim. The only fix I +// could find was copy/paste. +function CallSiteToString() { + var fileName; + var fileLocation = ""; + if (this.isNative()) { + fileLocation = "native"; + } else { + fileName = this.getScriptNameOrSourceURL(); + if (!fileName && this.isEval()) { + fileLocation = this.getEvalOrigin(); + fileLocation += ", "; // Expecting source position to follow. + } + + if (fileName) { + fileLocation += fileName; + } else { + // Source code does not originate from a file and is not native, but we + // can still get the source position inside the source string, e.g. in + // an eval string. + fileLocation += ""; + } + var lineNumber = this.getLineNumber(); + if (lineNumber != null) { + fileLocation += ":" + lineNumber; + var columnNumber = this.getColumnNumber(); + if (columnNumber) { + fileLocation += ":" + columnNumber; + } + } + } + + var line = ""; + var functionName = this.getFunctionName(); + var addSuffix = true; + var isConstructor = this.isConstructor(); + var isMethodCall = !(this.isToplevel() || isConstructor); + if (isMethodCall) { + var typeName = this.getTypeName(); + // Fixes shim to be backward compatable with Node v0 to v4 + if (typeName === "[object Object]") { + typeName = "null"; + } + var methodName = this.getMethodName(); + if (functionName) { + if (typeName && functionName.indexOf(typeName) != 0) { + line += typeName + "."; + } + line += functionName; + if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) { + line += " [as " + methodName + "]"; + } + } else { + line += typeName + "." + (methodName || ""); + } + } else if (isConstructor) { + line += "new " + (functionName || ""); + } else if (functionName) { + line += functionName; + } else { + line += fileLocation; + addSuffix = false; + } + if (addSuffix) { + line += " (" + fileLocation + ")"; + } + return line; +} + +function cloneCallSite(frame) { + var object = {}; + Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) { + object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name]; + }); + object.toString = CallSiteToString; + return object; +} + +function wrapCallSite(frame, state) { + // provides interface backward compatibility + if (state === undefined) { + state = { nextPosition: null, curPosition: null } + } + if(frame.isNative()) { + state.curPosition = null; + return frame; + } + + // Most call sites will return the source file from getFileName(), but code + // passed to eval() ending in "//# sourceURL=..." will return the source file + // from getScriptNameOrSourceURL() instead + var source = frame.getFileName() || frame.getScriptNameOrSourceURL(); + if (source) { + var line = frame.getLineNumber(); + var column = frame.getColumnNumber() - 1; + + // Fix position in Node where some (internal) code is prepended. + // See https://github.com/evanw/node-source-map-support/issues/36 + // Header removed in node at ^10.16 || >=11.11.0 + // v11 is not an LTS candidate, we can just test the one version with it. + // Test node versions for: 10.16-19, 10.20+, 12-19, 20-99, 100+, or 11.11 + var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/; + var headerLength = noHeader.test(globalProcessVersion()) ? 0 : 62; + if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) { + column -= headerLength; + } + + var position = mapSourcePosition({ + source: source, + line: line, + column: column + }); + state.curPosition = position; + frame = cloneCallSite(frame); + var originalFunctionName = frame.getFunctionName; + frame.getFunctionName = function() { + if (state.nextPosition == null) { + return originalFunctionName(); + } + return state.nextPosition.name || originalFunctionName(); + }; + frame.getFileName = function() { return position.source; }; + frame.getLineNumber = function() { return position.line; }; + frame.getColumnNumber = function() { return position.column + 1; }; + frame.getScriptNameOrSourceURL = function() { return position.source; }; + return frame; + } + + // Code called using eval() needs special handling + var origin = frame.isEval() && frame.getEvalOrigin(); + if (origin) { + origin = mapEvalOrigin(origin); + frame = cloneCallSite(frame); + frame.getEvalOrigin = function() { return origin; }; + return frame; + } + + // If we get here then we were unable to change the source position + return frame; +} + +// This function is part of the V8 stack trace API, for more info see: +// https://v8.dev/docs/stack-trace-api +function prepareStackTrace(error, stack) { + if (emptyCacheBetweenOperations) { + fileContentsCache = {}; + sourceMapCache = {}; + } + + var name = error.name || 'Error'; + var message = error.message || ''; + var errorString = name + ": " + message; + + var state = { nextPosition: null, curPosition: null }; + var processedStack = []; + for (var i = stack.length - 1; i >= 0; i--) { + processedStack.push('\n at ' + wrapCallSite(stack[i], state)); + state.nextPosition = state.curPosition; + } + state.curPosition = state.nextPosition = null; + return errorString + processedStack.reverse().join(''); +} + +// Generate position and snippet of original source with pointer +function getErrorSource(error) { + var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack); + if (match) { + var source = match[1]; + var line = +match[2]; + var column = +match[3]; + + // Support the inline sourceContents inside the source map + var contents = fileContentsCache[source]; + + // Support files on disk + if (!contents && fs && fs.existsSync(source)) { + try { + contents = fs.readFileSync(source, 'utf8'); + } catch (er) { + contents = ''; + } + } + + // Format the line from the original source code like node does + if (contents) { + var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1]; + if (code) { + return source + ':' + line + '\n' + code + '\n' + + new Array(column).join(' ') + '^'; + } + } + } + return null; +} + +function printErrorAndExit (error) { + var source = getErrorSource(error); + + // Ensure error is printed synchronously and not truncated + var stderr = globalProcessStderr(); + if (stderr && stderr._handle && stderr._handle.setBlocking) { + stderr._handle.setBlocking(true); + } + + if (source) { + console.error(); + console.error(source); + } + + console.error(error.stack); + globalProcessExit(1); +} + +function shimEmitUncaughtException () { + var origEmit = process.emit; + + process.emit = function (type) { + if (type === 'uncaughtException') { + var hasStack = (arguments[1] && arguments[1].stack); + var hasListeners = (this.listeners(type).length > 0); + + if (hasStack && !hasListeners) { + return printErrorAndExit(arguments[1]); + } + } + + return origEmit.apply(this, arguments); + }; +} + +var originalRetrieveFileHandlers = retrieveFileHandlers.slice(0); +var originalRetrieveMapHandlers = retrieveMapHandlers.slice(0); + +exports.wrapCallSite = wrapCallSite; +exports.getErrorSource = getErrorSource; +exports.mapSourcePosition = mapSourcePosition; +exports.retrieveSourceMap = retrieveSourceMap; + +exports.install = function(options) { + options = options || {}; + + if (options.environment) { + environment = options.environment; + if (["node", "browser", "auto"].indexOf(environment) === -1) { + throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}") + } + } + + // Allow sources to be found by methods other than reading the files + // directly from disk. + if (options.retrieveFile) { + if (options.overrideRetrieveFile) { + retrieveFileHandlers.length = 0; + } + + retrieveFileHandlers.unshift(options.retrieveFile); + } + + // Allow source maps to be found by methods other than reading the files + // directly from disk. + if (options.retrieveSourceMap) { + if (options.overrideRetrieveSourceMap) { + retrieveMapHandlers.length = 0; + } + + retrieveMapHandlers.unshift(options.retrieveSourceMap); + } + + // Support runtime transpilers that include inline source maps + if (options.hookRequire && !isInBrowser()) { + // Use dynamicRequire to avoid including in browser bundles + var Module = dynamicRequire(module, 'module'); + var $compile = Module.prototype._compile; + + if (!$compile.__sourceMapSupport) { + Module.prototype._compile = function(content, filename) { + fileContentsCache[filename] = content; + sourceMapCache[filename] = undefined; + return $compile.call(this, content, filename); + }; + + Module.prototype._compile.__sourceMapSupport = true; + } + } + + // Configure options + if (!emptyCacheBetweenOperations) { + emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ? + options.emptyCacheBetweenOperations : false; + } + + // Install the error reformatter + if (!errorFormatterInstalled) { + errorFormatterInstalled = true; + Error.prepareStackTrace = prepareStackTrace; + } + + if (!uncaughtShimInstalled) { + var installHandler = 'handleUncaughtExceptions' in options ? + options.handleUncaughtExceptions : true; + + // Do not override 'uncaughtException' with our own handler in Node.js + // Worker threads. Workers pass the error to the main thread as an event, + // rather than printing something to stderr and exiting. + try { + // We need to use `dynamicRequire` because `require` on it's own will be optimized by WebPack/Browserify. + var worker_threads = dynamicRequire(module, 'worker_threads'); + if (worker_threads.isMainThread === false) { + installHandler = false; + } + } catch(e) {} + + // Provide the option to not install the uncaught exception handler. This is + // to support other uncaught exception handlers (in test frameworks, for + // example). If this handler is not installed and there are no other uncaught + // exception handlers, uncaught exceptions will be caught by node's built-in + // exception handler and the process will still be terminated. However, the + // generated JavaScript code will be shown above the stack trace instead of + // the original source code. + if (installHandler && hasGlobalProcessEventEmitter()) { + uncaughtShimInstalled = true; + shimEmitUncaughtException(); + } + } +}; + +exports.resetRetrieveHandlers = function() { + retrieveFileHandlers.length = 0; + retrieveMapHandlers.length = 0; + + retrieveFileHandlers = originalRetrieveFileHandlers.slice(0); + retrieveMapHandlers = originalRetrieveMapHandlers.slice(0); + + retrieveSourceMap = handlerExec(retrieveMapHandlers); + retrieveFile = handlerExec(retrieveFileHandlers); +} diff --git a/node_modules/source-map/CHANGELOG.md b/node_modules/source-map/CHANGELOG.md new file mode 100644 index 0000000..3a8c066 --- /dev/null +++ b/node_modules/source-map/CHANGELOG.md @@ -0,0 +1,301 @@ +# Change Log + +## 0.5.6 + +* Fix for regression when people were using numbers as names in source maps. See + #236. + +## 0.5.5 + +* Fix "regression" of unsupported, implementation behavior that half the world + happens to have come to depend on. See #235. + +* Fix regression involving function hoisting in SpiderMonkey. See #233. + +## 0.5.4 + +* Large performance improvements to source-map serialization. See #228 and #229. + +## 0.5.3 + +* Do not include unnecessary distribution files. See + commit ef7006f8d1647e0a83fdc60f04f5a7ca54886f86. + +## 0.5.2 + +* Include browser distributions of the library in package.json's `files`. See + issue #212. + +## 0.5.1 + +* Fix latent bugs in IndexedSourceMapConsumer.prototype._parseMappings. See + ff05274becc9e6e1295ed60f3ea090d31d843379. + +## 0.5.0 + +* Node 0.8 is no longer supported. + +* Use webpack instead of dryice for bundling. + +* Big speedups serializing source maps. See pull request #203. + +* Fix a bug with `SourceMapConsumer.prototype.sourceContentFor` and sources that + explicitly start with the source root. See issue #199. + +## 0.4.4 + +* Fix an issue where using a `SourceMapGenerator` after having created a + `SourceMapConsumer` from it via `SourceMapConsumer.fromSourceMap` failed. See + issue #191. + +* Fix an issue with where `SourceMapGenerator` would mistakenly consider + different mappings as duplicates of each other and avoid generating them. See + issue #192. + +## 0.4.3 + +* A very large number of performance improvements, particularly when parsing + source maps. Collectively about 75% of time shaved off of the source map + parsing benchmark! + +* Fix a bug in `SourceMapConsumer.prototype.allGeneratedPositionsFor` and fuzzy + searching in the presence of a column option. See issue #177. + +* Fix a bug with joining a source and its source root when the source is above + the root. See issue #182. + +* Add the `SourceMapConsumer.prototype.hasContentsOfAllSources` method to + determine when all sources' contents are inlined into the source map. See + issue #190. + +## 0.4.2 + +* Add an `.npmignore` file so that the benchmarks aren't pulled down by + dependent projects. Issue #169. + +* Add an optional `column` argument to + `SourceMapConsumer.prototype.allGeneratedPositionsFor` and better handle lines + with no mappings. Issues #172 and #173. + +## 0.4.1 + +* Fix accidentally defining a global variable. #170. + +## 0.4.0 + +* The default direction for fuzzy searching was changed back to its original + direction. See #164. + +* There is now a `bias` option you can supply to `SourceMapConsumer` to control + the fuzzy searching direction. See #167. + +* About an 8% speed up in parsing source maps. See #159. + +* Added a benchmark for parsing and generating source maps. + +## 0.3.0 + +* Change the default direction that searching for positions fuzzes when there is + not an exact match. See #154. + +* Support for environments using json2.js for JSON serialization. See #156. + +## 0.2.0 + +* Support for consuming "indexed" source maps which do not have any remote + sections. See pull request #127. This introduces a minor backwards + incompatibility if you are monkey patching `SourceMapConsumer.prototype` + methods. + +## 0.1.43 + +* Performance improvements for `SourceMapGenerator` and `SourceNode`. See issue + #148 for some discussion and issues #150, #151, and #152 for implementations. + +## 0.1.42 + +* Fix an issue where `SourceNode`s from different versions of the source-map + library couldn't be used in conjunction with each other. See issue #142. + +## 0.1.41 + +* Fix a bug with getting the source content of relative sources with a "./" + prefix. See issue #145 and [Bug 1090768](bugzil.la/1090768). + +* Add the `SourceMapConsumer.prototype.computeColumnSpans` method to compute the + column span of each mapping. + +* Add the `SourceMapConsumer.prototype.allGeneratedPositionsFor` method to find + all generated positions associated with a given original source and line. + +## 0.1.40 + +* Performance improvements for parsing source maps in SourceMapConsumer. + +## 0.1.39 + +* Fix a bug where setting a source's contents to null before any source content + had been set before threw a TypeError. See issue #131. + +## 0.1.38 + +* Fix a bug where finding relative paths from an empty path were creating + absolute paths. See issue #129. + +## 0.1.37 + +* Fix a bug where if the source root was an empty string, relative source paths + would turn into absolute source paths. Issue #124. + +## 0.1.36 + +* Allow the `names` mapping property to be an empty string. Issue #121. + +## 0.1.35 + +* A third optional parameter was added to `SourceNode.fromStringWithSourceMap` + to specify a path that relative sources in the second parameter should be + relative to. Issue #105. + +* If no file property is given to a `SourceMapGenerator`, then the resulting + source map will no longer have a `null` file property. The property will + simply not exist. Issue #104. + +* Fixed a bug where consecutive newlines were ignored in `SourceNode`s. + Issue #116. + +## 0.1.34 + +* Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103. + +* Fix bug involving source contents and the + `SourceMapGenerator.prototype.applySourceMap`. Issue #100. + +## 0.1.33 + +* Fix some edge cases surrounding path joining and URL resolution. + +* Add a third parameter for relative path to + `SourceMapGenerator.prototype.applySourceMap`. + +* Fix issues with mappings and EOLs. + +## 0.1.32 + +* Fixed a bug where SourceMapConsumer couldn't handle negative relative columns + (issue 92). + +* Fixed test runner to actually report number of failed tests as its process + exit code. + +* Fixed a typo when reporting bad mappings (issue 87). + +## 0.1.31 + +* Delay parsing the mappings in SourceMapConsumer until queried for a source + location. + +* Support Sass source maps (which at the time of writing deviate from the spec + in small ways) in SourceMapConsumer. + +## 0.1.30 + +* Do not join source root with a source, when the source is a data URI. + +* Extend the test runner to allow running single specific test files at a time. + +* Performance improvements in `SourceNode.prototype.walk` and + `SourceMapConsumer.prototype.eachMapping`. + +* Source map browser builds will now work inside Workers. + +* Better error messages when attempting to add an invalid mapping to a + `SourceMapGenerator`. + +## 0.1.29 + +* Allow duplicate entries in the `names` and `sources` arrays of source maps + (usually from TypeScript) we are parsing. Fixes github issue 72. + +## 0.1.28 + +* Skip duplicate mappings when creating source maps from SourceNode; github + issue 75. + +## 0.1.27 + +* Don't throw an error when the `file` property is missing in SourceMapConsumer, + we don't use it anyway. + +## 0.1.26 + +* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70. + +## 0.1.25 + +* Make compatible with browserify + +## 0.1.24 + +* Fix issue with absolute paths and `file://` URIs. See + https://bugzilla.mozilla.org/show_bug.cgi?id=885597 + +## 0.1.23 + +* Fix issue with absolute paths and sourcesContent, github issue 64. + +## 0.1.22 + +* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21. + +## 0.1.21 + +* Fixed handling of sources that start with a slash so that they are relative to + the source root's host. + +## 0.1.20 + +* Fixed github issue #43: absolute URLs aren't joined with the source root + anymore. + +## 0.1.19 + +* Using Travis CI to run tests. + +## 0.1.18 + +* Fixed a bug in the handling of sourceRoot. + +## 0.1.17 + +* Added SourceNode.fromStringWithSourceMap. + +## 0.1.16 + +* Added missing documentation. + +* Fixed the generating of empty mappings in SourceNode. + +## 0.1.15 + +* Added SourceMapGenerator.applySourceMap. + +## 0.1.14 + +* The sourceRoot is now handled consistently. + +## 0.1.13 + +* Added SourceMapGenerator.fromSourceMap. + +## 0.1.12 + +* SourceNode now generates empty mappings too. + +## 0.1.11 + +* Added name support to SourceNode. + +## 0.1.10 + +* Added sourcesContent support to the customer and generator. diff --git a/node_modules/source-map/LICENSE b/node_modules/source-map/LICENSE new file mode 100644 index 0000000..ed1b7cf --- /dev/null +++ b/node_modules/source-map/LICENSE @@ -0,0 +1,28 @@ + +Copyright (c) 2009-2011, Mozilla Foundation and contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the names of the Mozilla Foundation nor the names of project + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/source-map/README.md b/node_modules/source-map/README.md new file mode 100644 index 0000000..fea4beb --- /dev/null +++ b/node_modules/source-map/README.md @@ -0,0 +1,742 @@ +# Source Map + +[![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map) + +[![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map) + +This is a library to generate and consume the source map format +[described here][format]. + +[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit + +## Use with Node + + $ npm install source-map + +## Use on the Web + + + +-------------------------------------------------------------------------------- + + + + + +## Table of Contents + +- [Examples](#examples) + - [Consuming a source map](#consuming-a-source-map) + - [Generating a source map](#generating-a-source-map) + - [With SourceNode (high level API)](#with-sourcenode-high-level-api) + - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api) +- [API](#api) + - [SourceMapConsumer](#sourcemapconsumer) + - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap) + - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans) + - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition) + - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition) + - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition) + - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources) + - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing) + - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order) + - [SourceMapGenerator](#sourcemapgenerator) + - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap) + - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer) + - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping) + - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath) + - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring) + - [SourceNode](#sourcenode) + - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name) + - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath) + - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk) + - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk) + - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn) + - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn) + - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep) + - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement) + - [SourceNode.prototype.toString()](#sourcenodeprototypetostring) + - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap) + + + +## Examples + +### Consuming a source map + +```js +var rawSourceMap = { + version: 3, + file: 'min.js', + names: ['bar', 'baz', 'n'], + sources: ['one.js', 'two.js'], + sourceRoot: 'http://example.com/www/js/', + mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' +}; + +var smc = new SourceMapConsumer(rawSourceMap); + +console.log(smc.sources); +// [ 'http://example.com/www/js/one.js', +// 'http://example.com/www/js/two.js' ] + +console.log(smc.originalPositionFor({ + line: 2, + column: 28 +})); +// { source: 'http://example.com/www/js/two.js', +// line: 2, +// column: 10, +// name: 'n' } + +console.log(smc.generatedPositionFor({ + source: 'http://example.com/www/js/two.js', + line: 2, + column: 10 +})); +// { line: 2, column: 28 } + +smc.eachMapping(function (m) { + // ... +}); +``` + +### Generating a source map + +In depth guide: +[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) + +#### With SourceNode (high level API) + +```js +function compile(ast) { + switch (ast.type) { + case 'BinaryExpression': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + [compile(ast.left), " + ", compile(ast.right)] + ); + case 'Literal': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + String(ast.value) + ); + // ... + default: + throw new Error("Bad AST"); + } +} + +var ast = parse("40 + 2", "add.js"); +console.log(compile(ast).toStringWithSourceMap({ + file: 'add.js' +})); +// { code: '40 + 2', +// map: [object SourceMapGenerator] } +``` + +#### With SourceMapGenerator (low level API) + +```js +var map = new SourceMapGenerator({ + file: "source-mapped.js" +}); + +map.addMapping({ + generated: { + line: 10, + column: 35 + }, + source: "foo.js", + original: { + line: 33, + column: 2 + }, + name: "christopher" +}); + +console.log(map.toString()); +// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' +``` + +## API + +Get a reference to the module: + +```js +// Node.js +var sourceMap = require('source-map'); + +// Browser builds +var sourceMap = window.sourceMap; + +// Inside Firefox +const sourceMap = require("devtools/toolkit/sourcemap/source-map.js"); +``` + +### SourceMapConsumer + +A SourceMapConsumer instance represents a parsed source map which we can query +for information about the original file positions by giving it a file position +in the generated source. + +#### new SourceMapConsumer(rawSourceMap) + +The only parameter is the raw source map (either as a string which can be +`JSON.parse`'d, or an object). According to the spec, source maps have the +following attributes: + +* `version`: Which version of the source map spec this map is following. + +* `sources`: An array of URLs to the original source files. + +* `names`: An array of identifiers which can be referenced by individual + mappings. + +* `sourceRoot`: Optional. The URL root from which all sources are relative. + +* `sourcesContent`: Optional. An array of contents of the original source files. + +* `mappings`: A string of base64 VLQs which contain the actual mappings. + +* `file`: Optional. The generated filename this source map is associated with. + +```js +var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData); +``` + +#### SourceMapConsumer.prototype.computeColumnSpans() + +Compute the last column for each generated mapping. The last column is +inclusive. + +```js +// Before: +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] + +consumer.computeColumnSpans(); + +// After: +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1, +// lastColumn: 9 }, +// { line: 2, +// column: 10, +// lastColumn: 19 }, +// { line: 2, +// column: 20, +// lastColumn: Infinity } ] + +``` + +#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) + +Returns the original source, line, and column information for the generated +source's line and column positions provided. The only argument is an object with +the following properties: + +* `line`: The line number in the generated source. Line numbers in + this library are 1-based (note that the underlying source map + specification uses 0-based line numbers -- this library handles the + translation). + +* `column`: The column number in the generated source. Column numbers + in this library are 0-based. + +* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or + `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest + element that is smaller than or greater than the one we are searching for, + respectively, if the exact element cannot be found. Defaults to + `SourceMapConsumer.GREATEST_LOWER_BOUND`. + +and an object is returned with the following properties: + +* `source`: The original source file, or null if this information is not + available. + +* `line`: The line number in the original source, or null if this information is + not available. The line number is 1-based. + +* `column`: The column number in the original source, or null if this + information is not available. The column number is 0-based. + +* `name`: The original identifier, or null if this information is not available. + +```js +consumer.originalPositionFor({ line: 2, column: 10 }) +// { source: 'foo.coffee', +// line: 2, +// column: 2, +// name: null } + +consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 }) +// { source: null, +// line: null, +// column: null, +// name: null } +``` + +#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) + +Returns the generated line and column information for the original source, +line, and column positions provided. The only argument is an object with +the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. The line number is + 1-based. + +* `column`: The column number in the original source. The column + number is 0-based. + +and an object is returned with the following properties: + +* `line`: The line number in the generated source, or null. The line + number is 1-based. + +* `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }) +// { line: 1, +// column: 56 } +``` + +#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition) + +Returns all generated line and column information for the original source, line, +and column provided. If no column is provided, returns all mappings +corresponding to a either the line we are searching for or the next closest line +that has any mappings. Otherwise, returns all mappings corresponding to the +given line and either the column we are searching for or the next closest column +that has any offsets. + +The only argument is an object with the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. The line number is + 1-based. + +* `column`: Optional. The column number in the original source. The + column number is 0-based. + +and an array of objects is returned, each with the following properties: + +* `line`: The line number in the generated source, or null. The line + number is 1-based. + +* `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] +``` + +#### SourceMapConsumer.prototype.hasContentsOfAllSources() + +Return true if we have the embedded source content for every source listed in +the source map, false otherwise. + +In other words, if this method returns `true`, then +`consumer.sourceContentFor(s)` will succeed for every source `s` in +`consumer.sources`. + +```js +// ... +if (consumer.hasContentsOfAllSources()) { + consumerReadyCallback(consumer); +} else { + fetchSources(consumer, consumerReadyCallback); +} +// ... +``` + +#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing]) + +Returns the original source content for the source provided. The only +argument is the URL of the original source file. + +If the source content for the given source is not found, then an error is +thrown. Optionally, pass `true` as the second param to have `null` returned +instead. + +```js +consumer.sources +// [ "my-cool-lib.clj" ] + +consumer.sourceContentFor("my-cool-lib.clj") +// "..." + +consumer.sourceContentFor("this is not in the source map"); +// Error: "this is not in the source map" is not in the source map + +consumer.sourceContentFor("this is not in the source map", true); +// null +``` + +#### SourceMapConsumer.prototype.eachMapping(callback, context, order) + +Iterate over each mapping between an original source/line/column and a +generated line/column in this source map. + +* `callback`: The function that is called with each mapping. Mappings have the + form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, + name }` + +* `context`: Optional. If specified, this object will be the value of `this` + every time that `callback` is called. + +* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or + `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over + the mappings sorted by the generated file's line/column order or the + original's source/line/column order, respectively. Defaults to + `SourceMapConsumer.GENERATED_ORDER`. + +```js +consumer.eachMapping(function (m) { console.log(m); }) +// ... +// { source: 'illmatic.js', +// generatedLine: 1, +// generatedColumn: 0, +// originalLine: 1, +// originalColumn: 0, +// name: null } +// { source: 'illmatic.js', +// generatedLine: 2, +// generatedColumn: 0, +// originalLine: 2, +// originalColumn: 0, +// name: null } +// ... +``` +### SourceMapGenerator + +An instance of the SourceMapGenerator represents a source map which is being +built incrementally. + +#### new SourceMapGenerator([startOfSourceMap]) + +You may pass an object with the following properties: + +* `file`: The filename of the generated source that this source map is + associated with. + +* `sourceRoot`: A root for all relative URLs in this source map. + +* `skipValidation`: Optional. When `true`, disables validation of mappings as + they are added. This can improve performance but should be used with + discretion, as a last resort. Even then, one should avoid using this flag when + running tests, if possible. + +```js +var generator = new sourceMap.SourceMapGenerator({ + file: "my-generated-javascript-file.js", + sourceRoot: "http://example.com/app/js/" +}); +``` + +#### SourceMapGenerator.fromSourceMap(sourceMapConsumer) + +Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance. + +* `sourceMapConsumer` The SourceMap. + +```js +var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer); +``` + +#### SourceMapGenerator.prototype.addMapping(mapping) + +Add a single mapping from original source line and column to the generated +source's line and column for this source map being created. The mapping object +should have the following properties: + +* `generated`: An object with the generated line and column positions. + +* `original`: An object with the original line and column positions. + +* `source`: The original source file (relative to the sourceRoot). + +* `name`: An optional original token name for this mapping. + +```js +generator.addMapping({ + source: "module-one.scm", + original: { line: 128, column: 0 }, + generated: { line: 3, column: 456 } +}) +``` + +#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for an original source file. + +* `sourceFile` the URL of the original source file. + +* `sourceContent` the content of the source file. + +```js +generator.setSourceContent("module-one.scm", + fs.readFileSync("path/to/module-one.scm")) +``` + +#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) + +Applies a SourceMap for a source file to the SourceMap. +Each mapping to the supplied source file is rewritten using the +supplied SourceMap. Note: The resolution for the resulting mappings +is the minimum of this map and the supplied map. + +* `sourceMapConsumer`: The SourceMap to be applied. + +* `sourceFile`: Optional. The filename of the source file. + If omitted, sourceMapConsumer.file will be used, if it exists. + Otherwise an error will be thrown. + +* `sourceMapPath`: Optional. The dirname of the path to the SourceMap + to be applied. If relative, it is relative to the SourceMap. + + This parameter is needed when the two SourceMaps aren't in the same + directory, and the SourceMap to be applied contains relative source + paths. If so, those relative source paths need to be rewritten + relative to the SourceMap. + + If omitted, it is assumed that both SourceMaps are in the same directory, + thus not needing any rewriting. (Supplying `'.'` has the same effect.) + +#### SourceMapGenerator.prototype.toString() + +Renders the source map being generated to a string. + +```js +generator.toString() +// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}' +``` + +### SourceNode + +SourceNodes provide a way to abstract over interpolating and/or concatenating +snippets of generated JavaScript source code, while maintaining the line and +column information associated between those snippets and the original source +code. This is useful as the final intermediate representation a compiler might +use before outputting the generated JS and source map. + +#### new SourceNode([line, column, source[, chunk[, name]]]) + +* `line`: The original line number associated with this source node, or null if + it isn't associated with an original line. The line number is 1-based. + +* `column`: The original column number associated with this source node, or null + if it isn't associated with an original column. The column number + is 0-based. + +* `source`: The original source's filename; null if no filename is provided. + +* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see + below. + +* `name`: Optional. The original identifier. + +```js +var node = new SourceNode(1, 2, "a.cpp", [ + new SourceNode(3, 4, "b.cpp", "extern int status;\n"), + new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"), + new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"), +]); +``` + +#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) + +Creates a SourceNode from generated code and a SourceMapConsumer. + +* `code`: The generated code + +* `sourceMapConsumer` The SourceMap for the generated code + +* `relativePath` The optional path that relative sources in `sourceMapConsumer` + should be relative to. + +```js +var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8")); +var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"), + consumer); +``` + +#### SourceNode.prototype.add(chunk) + +Add a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.add(" + "); +node.add(otherNode); +node.add([leftHandOperandNode, " + ", rightHandOperandNode]); +``` + +#### SourceNode.prototype.prepend(chunk) + +Prepend a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.prepend("/** Build Id: f783haef86324gf **/\n\n"); +``` + +#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for a source file. This will be added to the +`SourceMap` in the `sourcesContent` field. + +* `sourceFile`: The filename of the source file + +* `sourceContent`: The content of the source file + +```js +node.setSourceContent("module-one.scm", + fs.readFileSync("path/to/module-one.scm")) +``` + +#### SourceNode.prototype.walk(fn) + +Walk over the tree of JS snippets in this node and its children. The walking +function is called once for each snippet of JS and is passed that snippet and +the its original associated source's line/column location. + +* `fn`: The traversal function. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.walk(function (code, loc) { console.log("WALK:", code, loc); }) +// WALK: uno { source: 'b.js', line: 3, column: 4, name: null } +// WALK: dos { source: 'a.js', line: 1, column: 2, name: null } +// WALK: tres { source: 'a.js', line: 1, column: 2, name: null } +// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null } +``` + +#### SourceNode.prototype.walkSourceContents(fn) + +Walk over the tree of SourceNodes. The walking function is called for each +source file content and is passed the filename and source content. + +* `fn`: The traversal function. + +```js +var a = new SourceNode(1, 2, "a.js", "generated from a"); +a.setSourceContent("a.js", "original a"); +var b = new SourceNode(1, 2, "b.js", "generated from b"); +b.setSourceContent("b.js", "original b"); +var c = new SourceNode(1, 2, "c.js", "generated from c"); +c.setSourceContent("c.js", "original c"); + +var node = new SourceNode(null, null, null, [a, b, c]); +node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); }) +// WALK: a.js : original a +// WALK: b.js : original b +// WALK: c.js : original c +``` + +#### SourceNode.prototype.join(sep) + +Like `Array.prototype.join` except for SourceNodes. Inserts the separator +between each of this source node's children. + +* `sep`: The separator. + +```js +var lhs = new SourceNode(1, 2, "a.rs", "my_copy"); +var operand = new SourceNode(3, 4, "a.rs", "="); +var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()"); + +var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]); +var joinedNode = node.join(" "); +``` + +#### SourceNode.prototype.replaceRight(pattern, replacement) + +Call `String.prototype.replace` on the very right-most source snippet. Useful +for trimming white space from the end of a source node, etc. + +* `pattern`: The pattern to replace. + +* `replacement`: The thing to replace the pattern with. + +```js +// Trim trailing white space. +node.replaceRight(/\s*$/, ""); +``` + +#### SourceNode.prototype.toString() + +Return the string representation of this source node. Walks over the tree and +concatenates all the various snippets together to one string. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.toString() +// 'unodostresquatro' +``` + +#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) + +Returns the string representation of this tree of source nodes, plus a +SourceMapGenerator which contains all the mappings between the generated and +original sources. + +The arguments are the same as those to `new SourceMapGenerator`. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.toStringWithSourceMap({ file: "my-output-file.js" }) +// { code: 'unodostresquatro', +// map: [object SourceMapGenerator] } +``` diff --git a/node_modules/source-map/dist/source-map.debug.js b/node_modules/source-map/dist/source-map.debug.js new file mode 100644 index 0000000..aad0620 --- /dev/null +++ b/node_modules/source-map/dist/source-map.debug.js @@ -0,0 +1,3234 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["sourceMap"] = factory(); + else + root["sourceMap"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; +/******/ +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + /* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ + exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; + exports.SourceNode = __webpack_require__(10).SourceNode; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var base64VLQ = __webpack_require__(2); + var util = __webpack_require__(4); + var ArraySet = __webpack_require__(5).ArraySet; + var MappingList = __webpack_require__(6).MappingList; + + /** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ + function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; + } + + SourceMapGenerator.prototype._version = 3; + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + + /** + * Set the source content for a source file. + */ + SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + + SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + + /** + * Externalize the source map. + */ + SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + + /** + * Render the source map being generated to a string. + */ + SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + + exports.SourceMapGenerator = SourceMapGenerator; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + var base64 = __webpack_require__(3); + + // A single base 64 digit can contain 6 bits of data. For the base 64 variable + // length quantities we use in the source map spec, the first bit is the sign, + // the next four bits are the actual value, and the 6th bit is the + // continuation bit. The continuation bit tells us whether there are more + // digits in this value following this digit. + // + // Continuation + // | Sign + // | | + // V V + // 101011 + + var VLQ_BASE_SHIFT = 5; + + // binary: 100000 + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + + // binary: 011111 + var VLQ_BASE_MASK = VLQ_BASE - 1; + + // binary: 100000 + var VLQ_CONTINUATION_BIT = VLQ_BASE; + + /** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ + function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; + } + + /** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; + } + + /** + * Returns the base 64 VLQ encoded value. + */ + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; + }; + + /** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ + exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; + }; + + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + + /** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ + exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); + }; + + /** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ + exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; + }; + + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); + }; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); + } + exports.relative = relative; + + var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); + }()); + + function identity (s) { + return s; + } + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; + } + exports.toSetString = supportsNullProto ? identity : toSetString; + + function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; + } + exports.fromSetString = supportsNullProto ? identity : fromSetString; + + function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; + } + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; + } + + /** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ + function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + + /** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ + function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); + } + exports.parseSourceMapInput = parseSourceMapInput; + + /** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ + function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); + } + exports.computeSourceURL = computeSourceURL; + + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var has = Object.prototype.hasOwnProperty; + var hasNativeMap = typeof Map !== "undefined"; + + /** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ + function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; + }; + + /** + * Add the given string to this set. + * + * @param String aStr + */ + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } + }; + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } + }; + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); + }; + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + + exports.ArraySet = ArraySet; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + + /** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ + function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; + } + + /** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ + function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + }; + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + }; + + exports.MappingList = MappingList; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var binarySearch = __webpack_require__(8); + var ArraySet = __webpack_require__(5).ArraySet; + var base64VLQ = __webpack_require__(2); + var quickSort = __webpack_require__(9).quickSort; + + function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); + } + + SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); + } + + /** + * The version of the source mapping spec that we are consuming. + */ + SourceMapConsumer.prototype._version = 3; + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } + }); + + SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + + SourceMapConsumer.GREATEST_LOWER_BOUND = 1; + SourceMapConsumer.LEAST_UPPER_BOUND = 2; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + + exports.SourceMapConsumer = SourceMapConsumer; + + /** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; + } + + BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + + /** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ + BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; + }; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ + BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + + /** + * The version of the source mapping spec that we are consuming. + */ + BasicSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } + }); + + /** + * Provide the JIT with a nice shape / hidden class. + */ + function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + + exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + + /** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ + function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); + } + + IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + + /** + * The version of the source mapping spec that we are consuming. + */ + IndexedSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } + }); + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + + exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + exports.GREATEST_LOWER_BOUND = 1; + exports.LEAST_UPPER_BOUND = 2; + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } + } + + /** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; + }; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + // It turns out that some (most?) JavaScript engines don't self-host + // `Array.prototype.sort`. This makes sense because C++ will likely remain + // faster than JS when doing raw CPU-intensive sorting. However, when using a + // custom comparator function, calling back and forth between the VM's C++ and + // JIT'd JS is rather slow *and* loses JIT type information, resulting in + // worse generated code for the comparator function than would be optimal. In + // fact, when sorting with a comparator, these costs outweigh the benefits of + // sorting in C++. By using our own JS-implemented Quick Sort (below), we get + // a ~3500ms mean speed-up in `bench/bench.html`. + + /** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ + function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; + } + + /** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ + function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); + } + + /** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ + function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } + } + + /** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); + }; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + var util = __webpack_require__(4); + + // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other + // operating systems these days (capturing the result). + var REGEX_NEWLINE = /(\r?\n)/; + + // Newline character code for charCodeAt() comparisons + var NEWLINE_CODE = 10; + + // Private symbol for identifying `SourceNode`s when multiple versions of + // the source-map library are loaded. This MUST NOT CHANGE across + // versions! + var isSourceNode = "$$$isSourceNode$$$"; + + /** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + }; + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + + /** + * Returns the string representation of this source node along with a source + * map. + */ + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + + exports.SourceNode = SourceNode; + + +/***/ }) +/******/ ]) +}); +; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vd2VicGFjay91bml2ZXJzYWxNb2R1bGVEZWZpbml0aW9uIiwid2VicGFjazovLy93ZWJwYWNrL2Jvb3RzdHJhcCAxNjI0YzcyOTliODg3ZjdiZGY2NCIsIndlYnBhY2s6Ly8vLi9zb3VyY2UtbWFwLmpzIiwid2VicGFjazovLy8uL2xpYi9zb3VyY2UtbWFwLWdlbmVyYXRvci5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmFzZTY0LXZscS5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmFzZTY0LmpzIiwid2VicGFjazovLy8uL2xpYi91dGlsLmpzIiwid2VicGFjazovLy8uL2xpYi9hcnJheS1zZXQuanMiLCJ3ZWJwYWNrOi8vLy4vbGliL21hcHBpbmctbGlzdC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvc291cmNlLW1hcC1jb25zdW1lci5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmluYXJ5LXNlYXJjaC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvcXVpY2stc29ydC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvc291cmNlLW5vZGUuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsQ0FBQztBQUNELE87QUNWQTtBQUNBOztBQUVBO0FBQ0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ICAgbmV4dCArPSBiYXNlNjRWTFEuZW5jb2RlKHNvdXJjZUlkeCAtIHByZXZpb3VzU291cmNlKTtcbiAgICAgICAgcHJldmlvdXNTb3VyY2UgPSBzb3VyY2VJZHg7XG5cbiAgICAgICAgLy8gbGluZXMgYXJlIHN0b3JlZCAwLWJhc2VkIGluIFNvdXJjZU1hcCBzcGVjIHZlcnNpb24gM1xuICAgICAgICBuZXh0ICs9IGJhc2U2NFZMUS5lbmNvZGUobWFwcGluZy5vcmlnaW5hbExpbmUgLSAxXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC0gcHJldmlvdXNPcmlnaW5hbExpbmUpO1xuICAgICAgICBwcmV2aW91c09yaWdpbmFsTGluZSA9IG1hcHBpbmcub3JpZ2luYWxMaW5lIC0gMTtcblxuICAgICAgICBuZXh0ICs9IGJhc2U2NFZMUS5lbmNvZGUobWFwcGluZy5vcmlnaW5hbENvbHVtblxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAtIHByZXZpb3VzT3JpZ2luYWxDb2x1bW4pO1xuICAgICAgICBwcmV2aW91c09yaWdpbmFsQ29sdW1uID0gbWFwcGluZy5vcmlnaW5hbENvbHVtbjtcblxuICAgICAgICBpZiAobWFwcGluZy5uYW1lICE9IG51bGwpIHtcbiAgICAgICAgICBuYW1lSWR4ID0gdGhpcy5fbmFtZXMuaW5kZXhPZihtYXBwaW5nLm5hbWUpO1xuICAgICAgICAgIG5leHQgKz0gYmFzZTY0VkxRLmVuY29kZShuYW1lSWR4IC0gcHJldmlvdXNOYW1lKTtcbiAgICAgICAgICBwcmV2aW91c05hbWUgPSBuYW1lSWR4O1xuICAgICAgICB9XG4gICAgICB9XG5cbiAgICAgIHJlc3VsdCArPSBuZXh0O1xuICAgIH1cblxuICAgIHJldHVybiByZXN1bHQ7XG4gIH07XG5cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuX2dlbmVyYXRlU291cmNlc0NvbnRlbnQgPVxuICB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XG4gICAgICAgICAgICBpbmRleCA9IHRlbXAucmVzdDtcbiAgICAgICAgICAgIHNlZ21lbnQucHVzaCh2YWx1ZSk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKHNlZ21lbnQubGVuZ3RoID09PSAyKSB7XG4gICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ0ZvdW5kIGEgc291cmNlLCBidXQgbm8gbGluZSBhbmQgY29sdW1uJyk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKHNlZ21lbnQubGVuZ3RoID09PSAzKSB7XG4gICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ0ZvdW5kIGEgc291cmNlIGFuZCBsaW5lLCBidXQgbm8gY29sdW1uJyk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgY2FjaGVkU2VnbWVudHNbc3RyXSA9IHNlZ21lbnQ7XG4gICAgICAgIH1cblxuICAgICAgICAvLyBHZW5lcmF0ZWQgY29sdW1uLlxuICAgICAgICBtYXBwaW5nLmdlbmVyYXRlZENvbHVtbiA9IHByZXZpb3VzR2VuZXJhdGVkQ29sdW1uICsgc2VnbWVudFswXTtcbiAgICAgICAgcHJldmlvdXNHZW5lcmF0ZWRDb2x1bW4gPSBtYXBwaW5nLmdlbmVyYXRlZENvbHVtbjtcblxuICAgICAgICBpZiAoc2VnbWVudC5sZW5ndGggPiAxKSB7XG4gICAgICAgICAgLy8gT3JpZ2luYWwgc291cmNlLlxuICAgICAgICAgIG1hcHBpbmcuc291cmNlID0gcHJldmlvdXNTb3VyY2UgKyBzZWdtZW50WzFdO1xuICAgICAgICAgIHByZXZpb3VzU291cmNlICs9IHNlZ21lbnRbMV07XG5cbiAgICAgICAgICAvLyBPcmlnaW5hbCBsaW5lLlxuICAgICAgICAgIG1hcHBpbmcub3JpZ2luYWxMaW5lID0gcHJldmlvdXNPcmlnaW5hbExpbmUgKyBzZWdtZW50WzJdO1xuICAgICAgICAgIHByZXZpb3VzT3JpZ2luYWx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Nlcy5mb3JFYWNoKGZ1bmN0aW9uIChzb3VyY2VGaWxlKSB7XG4gICAgICB2YXIgY29udGVudCA9IGFTb3VyY2VNYXBDb25zdW1lci5zb3VyY2VDb250ZW50Rm9yKHNvdXJjZUZpbGUpO1xuICAgICAgaWYgKGNvbnRlbnQgIT0gbnVsbCkge1xuICAgICAgICBpZiAoYVJlbGF0aXZlUGF0aCAhPSBudWxsKSB7XG4gICAgICAgICAgc291cmNlRmlsZSA9IHV0aWwuam9pbihhUmVsYXRpdmVQYXRoLCBzb3VyY2VGaWxlKTtcbiAgICAgICAgfVxuICAgICAgICBub2RlLnNldFNvdXJjZUNvbnRlbnQoc291cmNlRmlsZSwgY29udGVudCk7XG4gICAgICB9XG4gICAgfSk7XG5cbiAgICByZXR1cm4gbm9kZTtcblxuICAgIGZ1bmN0aW9uIGFkZE1hcHBpbmdXaXRoQ29kZShtYXBwaW5nLCBjb2RlKSB7XG4gICAgICBpZiAobWFwcGluZyA9PT0gbnVsbCB8fCBtYXBwaW5nLnNvdXJjZSA9PT0gdW5kZWZpbmVkKSB7XG4gICAgICAgIG5vZGUuYWRkKGNvZGUpO1xuICAgICAgfSBlbHNlIHtcbiAgICAgICAgdmFyIHNvdXJjZSA9IGFSZWxhdGl2ZVBhdGhcbiAgICAgICAgICA/IHV0aWwuam9pbihhUmVsYXRpdmVQYXRoLCBtYXBwaW5nLnNvdXJjZSlcbiAgICAgICAgICA6IG1hcHBpbmcuc291cmNlO1xuICAgICAgICBub2RlLmFkZChuZXcgU291cmNlTm9kZShtYXBwaW5nLm9yaWdpbmFsTGluZSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgbWFwcGluZy5vcmlnaW5hbENvbHVtbixcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgc291cmNlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb2RlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBtYXBwaW5nLm5hbWUpKTtcbi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zb3VyY2VNYXBwaW5nQWN0aXZlID0gZmFsc2U7XG4gICAgfVxuICAgIGZvciAodmFyIGlkeCA9IDAsIGxlbmd0aCA9IGNodW5rLmxlbmd0aDsgaWR4IDwgbGVuZ3RoOyBpZHgrKykge1xuICAgICAgaWYgKGNodW5rLmNoYXJDb2RlQXQoaWR4KSA9PT0gTkVXTElORV9DT0RFKSB7XG4gICAgICAgIGdlbmVyYXRlZC5saW5lKys7XG4gICAgICAgIGdlbmVyYXRlZC5jb2x1bW4gPSAwO1xuICAgICAgICAvLyBNYXBwaW5ncyBlbmQgYXQgZW9sXG4gICAgICAgIGlmIChpZHggKyAxID09PSBsZW5ndGgpIHtcbiAgICAgICAgICBsYXN0T3JpZ2luYWxTb3VyY2UgPSBudWxsO1xuICAgICAgICAgIHNvdXJjZU1hcHBpbmdBY3RpdmUgPSBmYWxzZTtcbiAgICAgICAgfSBlbHNlIGlmIChzb3VyY2VNYXBwaW5nQWN0aXZlKSB7XG4gICAgICAgICAgbWFwLmFkZE1hcHBpbmcoe1xuICAgICAgICAgICAgc291cmNlOiBvcmlnaW5hbC5zb3VyY2UsXG4gICAgICAgICAgICBvcmlnaW5hbDoge1xuICAgICAgICAgICAgICBsaW5lOiBvcmlnaW5hbC5saW5lLFxuICAgICAgICAgICAgICBjb2x1bW46IG9yaWdpbmFsLmNvbHVtblxuICAgICAgICAgICAgfSxcbiAgICAgICAgICAgIGdlbmVyYXRlZDoge1xuICAgICAgICAgICAgICBsaW5lOiBnZW5lcmF0ZWQubGluZSxcbiAgICAgICAgICAgICAgY29sdW1uOiBnZW5lcmF0ZWQuY29sdW1uXG4gICAgICAgICAgICB9LFxuICAgICAgICAgICAgbmFtZTogb3JpZ2luYWwubmFtZVxuICAgICAgICAgIH0pO1xuICAgICAgICB9XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBnZW5lcmF0ZWQuY29sdW1uKys7XG4gICAgICB9XG4gICAgfVxuICB9KTtcbiAgdGhpcy53YWxrU291cmNlQ29udGVudHMoZnVuY3Rpb24gKHNvdXJjZUZpbGUsIHNvdXJjZUNvbnRlbnQpIHtcbiAgICBtYXAuc2V0U291cmNlQ29udGVudChzb3VyY2VGaWxlLCBzb3VyY2VDb250ZW50KTtcbiAgfSk7XG5cbiAgcmV0dXJuIHsgY29kZTogZ2VuZXJhdGVkLmNvZGUsIG1hcDogbWFwIH07XG59O1xuXG5leHBvcnRzLlNvdXJjZU5vZGUgPSBTb3VyY2VOb2RlO1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvc291cmNlLW5vZGUuanNcbi8vIG1vZHVsZSBpZCA9IDEwXG4vLyBtb2R1bGUgY2h1bmtzID0gMCJdLCJzb3VyY2VSb290IjoiIn0= \ No newline at end of file diff --git a/node_modules/source-map/dist/source-map.js b/node_modules/source-map/dist/source-map.js new file mode 100644 index 0000000..b4eb087 --- /dev/null +++ b/node_modules/source-map/dist/source-map.js @@ -0,0 +1,3233 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["sourceMap"] = factory(); + else + root["sourceMap"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + /* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ + exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; + exports.SourceNode = __webpack_require__(10).SourceNode; + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var base64VLQ = __webpack_require__(2); + var util = __webpack_require__(4); + var ArraySet = __webpack_require__(5).ArraySet; + var MappingList = __webpack_require__(6).MappingList; + + /** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ + function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; + } + + SourceMapGenerator.prototype._version = 3; + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + + /** + * Set the source content for a source file. + */ + SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + + SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + + /** + * Externalize the source map. + */ + SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + + /** + * Render the source map being generated to a string. + */ + SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + + exports.SourceMapGenerator = SourceMapGenerator; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + var base64 = __webpack_require__(3); + + // A single base 64 digit can contain 6 bits of data. For the base 64 variable + // length quantities we use in the source map spec, the first bit is the sign, + // the next four bits are the actual value, and the 6th bit is the + // continuation bit. The continuation bit tells us whether there are more + // digits in this value following this digit. + // + // Continuation + // | Sign + // | | + // V V + // 101011 + + var VLQ_BASE_SHIFT = 5; + + // binary: 100000 + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + + // binary: 011111 + var VLQ_BASE_MASK = VLQ_BASE - 1; + + // binary: 100000 + var VLQ_CONTINUATION_BIT = VLQ_BASE; + + /** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ + function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; + } + + /** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; + } + + /** + * Returns the base 64 VLQ encoded value. + */ + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; + }; + + /** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ + exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; + }; + + +/***/ }), +/* 3 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + + /** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ + exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); + }; + + /** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ + exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; + }; + + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); + }; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); + } + exports.relative = relative; + + var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); + }()); + + function identity (s) { + return s; + } + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; + } + exports.toSetString = supportsNullProto ? identity : toSetString; + + function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; + } + exports.fromSetString = supportsNullProto ? identity : fromSetString; + + function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; + } + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; + } + + /** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ + function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + + /** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ + function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); + } + exports.parseSourceMapInput = parseSourceMapInput; + + /** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ + function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); + } + exports.computeSourceURL = computeSourceURL; + + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var has = Object.prototype.hasOwnProperty; + var hasNativeMap = typeof Map !== "undefined"; + + /** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ + function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; + }; + + /** + * Add the given string to this set. + * + * @param String aStr + */ + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } + }; + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } + }; + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); + }; + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + + exports.ArraySet = ArraySet; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + + /** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ + function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; + } + + /** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ + function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + }; + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + }; + + exports.MappingList = MappingList; + + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var binarySearch = __webpack_require__(8); + var ArraySet = __webpack_require__(5).ArraySet; + var base64VLQ = __webpack_require__(2); + var quickSort = __webpack_require__(9).quickSort; + + function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); + } + + SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); + } + + /** + * The version of the source mapping spec that we are consuming. + */ + SourceMapConsumer.prototype._version = 3; + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } + }); + + SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + + SourceMapConsumer.GREATEST_LOWER_BOUND = 1; + SourceMapConsumer.LEAST_UPPER_BOUND = 2; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + + exports.SourceMapConsumer = SourceMapConsumer; + + /** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; + } + + BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + + /** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ + BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; + }; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ + BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + + /** + * The version of the source mapping spec that we are consuming. + */ + BasicSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } + }); + + /** + * Provide the JIT with a nice shape / hidden class. + */ + function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + + exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + + /** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ + function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); + } + + IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + + /** + * The version of the source mapping spec that we are consuming. + */ + IndexedSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } + }); + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ + IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ + IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + + exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + exports.GREATEST_LOWER_BOUND = 1; + exports.LEAST_UPPER_BOUND = 2; + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } + } + + /** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; + }; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + // It turns out that some (most?) JavaScript engines don't self-host + // `Array.prototype.sort`. This makes sense because C++ will likely remain + // faster than JS when doing raw CPU-intensive sorting. However, when using a + // custom comparator function, calling back and forth between the VM's C++ and + // JIT'd JS is rather slow *and* loses JIT type information, resulting in + // worse generated code for the comparator function than would be optimal. In + // fact, when sorting with a comparator, these costs outweigh the benefits of + // sorting in C++. By using our own JS-implemented Quick Sort (below), we get + // a ~3500ms mean speed-up in `bench/bench.html`. + + /** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ + function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; + } + + /** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ + function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); + } + + /** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ + function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } + } + + /** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); + }; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + var util = __webpack_require__(4); + + // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other + // operating systems these days (capturing the result). + var REGEX_NEWLINE = /(\r?\n)/; + + // Newline character code for charCodeAt() comparisons + var NEWLINE_CODE = 10; + + // Private symbol for identifying `SourceNode`s when multiple versions of + // the source-map library are loaded. This MUST NOT CHANGE across + // versions! + var isSourceNode = "$$$isSourceNode$$$"; + + /** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + }; + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + + /** + * Returns the string representation of this source node along with a source + * map. + */ + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + + exports.SourceNode = SourceNode; + + +/***/ }) +/******/ ]) +}); +; \ No newline at end of file diff --git a/node_modules/source-map/dist/source-map.min.js b/node_modules/source-map/dist/source-map.min.js new file mode 100644 index 0000000..c7c72da --- /dev/null +++ b/node_modules/source-map/dist/source-map.min.js @@ -0,0 +1,2 @@ +!function(e,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define([],n):"object"==typeof exports?exports.sourceMap=n():e.sourceMap=n()}(this,function(){return function(e){function n(t){if(r[t])return r[t].exports;var o=r[t]={exports:{},id:t,loaded:!1};return e[t].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}var r={};return n.m=e,n.c=r,n.p="",n(0)}([function(e,n,r){n.SourceMapGenerator=r(1).SourceMapGenerator,n.SourceMapConsumer=r(7).SourceMapConsumer,n.SourceNode=r(10).SourceNode},function(e,n,r){function t(e){e||(e={}),this._file=i.getArg(e,"file",null),this._sourceRoot=i.getArg(e,"sourceRoot",null),this._skipValidation=i.getArg(e,"skipValidation",!1),this._sources=new s,this._names=new s,this._mappings=new a,this._sourcesContents=null}var o=r(2),i=r(4),s=r(5).ArraySet,a=r(6).MappingList;t.prototype._version=3,t.fromSourceMap=function(e){var n=e.sourceRoot,r=new t({file:e.file,sourceRoot:n});return e.eachMapping(function(e){var t={generated:{line:e.generatedLine,column:e.generatedColumn}};null!=e.source&&(t.source=e.source,null!=n&&(t.source=i.relative(n,t.source)),t.original={line:e.originalLine,column:e.originalColumn},null!=e.name&&(t.name=e.name)),r.addMapping(t)}),e.sources.forEach(function(t){var o=t;null!==n&&(o=i.relative(n,t)),r._sources.has(o)||r._sources.add(o);var s=e.sourceContentFor(t);null!=s&&r.setSourceContent(t,s)}),r},t.prototype.addMapping=function(e){var n=i.getArg(e,"generated"),r=i.getArg(e,"original",null),t=i.getArg(e,"source",null),o=i.getArg(e,"name",null);this._skipValidation||this._validateMapping(n,r,t,o),null!=t&&(t=String(t),this._sources.has(t)||this._sources.add(t)),null!=o&&(o=String(o),this._names.has(o)||this._names.add(o)),this._mappings.add({generatedLine:n.line,generatedColumn:n.column,originalLine:null!=r&&r.line,originalColumn:null!=r&&r.column,source:t,name:o})},t.prototype.setSourceContent=function(e,n){var r=e;null!=this._sourceRoot&&(r=i.relative(this._sourceRoot,r)),null!=n?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[i.toSetString(r)]=n):this._sourcesContents&&(delete this._sourcesContents[i.toSetString(r)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))},t.prototype.applySourceMap=function(e,n,r){var t=n;if(null==n){if(null==e.file)throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');t=e.file}var o=this._sourceRoot;null!=o&&(t=i.relative(o,t));var a=new s,u=new s;this._mappings.unsortedForEach(function(n){if(n.source===t&&null!=n.originalLine){var s=e.originalPositionFor({line:n.originalLine,column:n.originalColumn});null!=s.source&&(n.source=s.source,null!=r&&(n.source=i.join(r,n.source)),null!=o&&(n.source=i.relative(o,n.source)),n.originalLine=s.line,n.originalColumn=s.column,null!=s.name&&(n.name=s.name))}var l=n.source;null==l||a.has(l)||a.add(l);var c=n.name;null==c||u.has(c)||u.add(c)},this),this._sources=a,this._names=u,e.sources.forEach(function(n){var t=e.sourceContentFor(n);null!=t&&(null!=r&&(n=i.join(r,n)),null!=o&&(n=i.relative(o,n)),this.setSourceContent(n,t))},this)},t.prototype._validateMapping=function(e,n,r,t){if(n&&"number"!=typeof n.line&&"number"!=typeof n.column)throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if((!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0)||n||r||t)&&!(e&&"line"in e&&"column"in e&&n&&"line"in n&&"column"in n&&e.line>0&&e.column>=0&&n.line>0&&n.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:n,name:t}))},t.prototype._serializeMappings=function(){for(var e,n,r,t,s=0,a=1,u=0,l=0,c=0,g=0,p="",h=this._mappings.toArray(),f=0,d=h.length;f0){if(!i.compareByGeneratedPositionsInflated(n,h[f-1]))continue;e+=","}e+=o.encode(n.generatedColumn-s),s=n.generatedColumn,null!=n.source&&(t=this._sources.indexOf(n.source),e+=o.encode(t-g),g=t,e+=o.encode(n.originalLine-1-l),l=n.originalLine-1,e+=o.encode(n.originalColumn-u),u=n.originalColumn,null!=n.name&&(r=this._names.indexOf(n.name),e+=o.encode(r-c),c=r)),p+=e}return p},t.prototype._generateSourcesContent=function(e,n){return e.map(function(e){if(!this._sourcesContents)return null;null!=n&&(e=i.relative(n,e));var r=i.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,r)?this._sourcesContents[r]:null},this)},t.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},t.prototype.toString=function(){return JSON.stringify(this.toJSON())},n.SourceMapGenerator=t},function(e,n,r){function t(e){return e<0?(-e<<1)+1:(e<<1)+0}function o(e){var n=1===(1&e),r=e>>1;return n?-r:r}var i=r(3),s=5,a=1<>>=s,o>0&&(n|=l),r+=i.encode(n);while(o>0);return r},n.decode=function(e,n,r){var t,a,c=e.length,g=0,p=0;do{if(n>=c)throw new Error("Expected more digits in base 64 VLQ value.");if(a=i.decode(e.charCodeAt(n++)),a===-1)throw new Error("Invalid base64 digit: "+e.charAt(n-1));t=!!(a&l),a&=u,g+=a<=0;c--)s=u[c],"."===s?u.splice(c,1):".."===s?l++:l>0&&(""===s?(u.splice(c+1,l),l=0):(u.splice(c,2),l--));return r=u.join("/"),""===r&&(r=a?"/":"."),i?(i.path=r,o(i)):r}function s(e,n){""===e&&(e="."),""===n&&(n=".");var r=t(n),s=t(e);if(s&&(e=s.path||"/"),r&&!r.scheme)return s&&(r.scheme=s.scheme),o(r);if(r||n.match(y))return n;if(s&&!s.host&&!s.path)return s.host=n,o(s);var a="/"===n.charAt(0)?n:i(e.replace(/\/+$/,"")+"/"+n);return s?(s.path=a,o(s)):a}function a(e,n){""===e&&(e="."),e=e.replace(/\/$/,"");for(var r=0;0!==n.indexOf(e+"/");){var t=e.lastIndexOf("/");if(t<0)return n;if(e=e.slice(0,t),e.match(/^([^\/]+:\/)?\/*$/))return n;++r}return Array(r+1).join("../")+n.substr(e.length+1)}function u(e){return e}function l(e){return g(e)?"$"+e:e}function c(e){return g(e)?e.slice(1):e}function g(e){if(!e)return!1;var n=e.length;if(n<9)return!1;if(95!==e.charCodeAt(n-1)||95!==e.charCodeAt(n-2)||111!==e.charCodeAt(n-3)||116!==e.charCodeAt(n-4)||111!==e.charCodeAt(n-5)||114!==e.charCodeAt(n-6)||112!==e.charCodeAt(n-7)||95!==e.charCodeAt(n-8)||95!==e.charCodeAt(n-9))return!1;for(var r=n-10;r>=0;r--)if(36!==e.charCodeAt(r))return!1;return!0}function p(e,n,r){var t=f(e.source,n.source);return 0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t||r?t:(t=e.generatedColumn-n.generatedColumn,0!==t?t:(t=e.generatedLine-n.generatedLine,0!==t?t:f(e.name,n.name)))))}function h(e,n,r){var t=e.generatedLine-n.generatedLine;return 0!==t?t:(t=e.generatedColumn-n.generatedColumn,0!==t||r?t:(t=f(e.source,n.source),0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t?t:f(e.name,n.name)))))}function f(e,n){return e===n?0:null===e?1:null===n?-1:e>n?1:-1}function d(e,n){var r=e.generatedLine-n.generatedLine;return 0!==r?r:(r=e.generatedColumn-n.generatedColumn,0!==r?r:(r=f(e.source,n.source),0!==r?r:(r=e.originalLine-n.originalLine,0!==r?r:(r=e.originalColumn-n.originalColumn,0!==r?r:f(e.name,n.name)))))}function m(e){return JSON.parse(e.replace(/^\)]}'[^\n]*\n/,""))}function _(e,n,r){if(n=n||"",e&&("/"!==e[e.length-1]&&"/"!==n[0]&&(e+="/"),n=e+n),r){var a=t(r);if(!a)throw new Error("sourceMapURL could not be parsed");if(a.path){var u=a.path.lastIndexOf("/");u>=0&&(a.path=a.path.substring(0,u+1))}n=s(o(a),n)}return i(n)}n.getArg=r;var v=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,y=/^data:.+\,.+$/;n.urlParse=t,n.urlGenerate=o,n.normalize=i,n.join=s,n.isAbsolute=function(e){return"/"===e.charAt(0)||v.test(e)},n.relative=a;var C=function(){var e=Object.create(null);return!("__proto__"in e)}();n.toSetString=C?u:l,n.fromSetString=C?u:c,n.compareByOriginalPositions=p,n.compareByGeneratedPositionsDeflated=h,n.compareByGeneratedPositionsInflated=d,n.parseSourceMapInput=m,n.computeSourceURL=_},function(e,n,r){function t(){this._array=[],this._set=s?new Map:Object.create(null)}var o=r(4),i=Object.prototype.hasOwnProperty,s="undefined"!=typeof Map;t.fromArray=function(e,n){for(var r=new t,o=0,i=e.length;o=0)return n}else{var r=o.toSetString(e);if(i.call(this._set,r))return this._set[r]}throw new Error('"'+e+'" is not in the set.')},t.prototype.at=function(e){if(e>=0&&er||t==r&&s>=o||i.compareByGeneratedPositionsInflated(e,n)<=0}function o(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var i=r(4);o.prototype.unsortedForEach=function(e,n){this._array.forEach(e,n)},o.prototype.add=function(e){t(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},o.prototype.toArray=function(){return this._sorted||(this._array.sort(i.compareByGeneratedPositionsInflated),this._sorted=!0),this._array},n.MappingList=o},function(e,n,r){function t(e,n){var r=e;return"string"==typeof e&&(r=a.parseSourceMapInput(e)),null!=r.sections?new s(r,n):new o(r,n)}function o(e,n){var r=e;"string"==typeof e&&(r=a.parseSourceMapInput(e));var t=a.getArg(r,"version"),o=a.getArg(r,"sources"),i=a.getArg(r,"names",[]),s=a.getArg(r,"sourceRoot",null),u=a.getArg(r,"sourcesContent",null),c=a.getArg(r,"mappings"),g=a.getArg(r,"file",null);if(t!=this._version)throw new Error("Unsupported version: "+t);s&&(s=a.normalize(s)),o=o.map(String).map(a.normalize).map(function(e){return s&&a.isAbsolute(s)&&a.isAbsolute(e)?a.relative(s,e):e}),this._names=l.fromArray(i.map(String),!0),this._sources=l.fromArray(o,!0),this._absoluteSources=this._sources.toArray().map(function(e){return a.computeSourceURL(s,e,n)}),this.sourceRoot=s,this.sourcesContent=u,this._mappings=c,this._sourceMapURL=n,this.file=g}function i(){this.generatedLine=0,this.generatedColumn=0,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}function s(e,n){var r=e;"string"==typeof e&&(r=a.parseSourceMapInput(e));var o=a.getArg(r,"version"),i=a.getArg(r,"sections");if(o!=this._version)throw new Error("Unsupported version: "+o);this._sources=new l,this._names=new l;var s={line:-1,column:0};this._sections=i.map(function(e){if(e.url)throw new Error("Support for url field in sections not implemented.");var r=a.getArg(e,"offset"),o=a.getArg(r,"line"),i=a.getArg(r,"column");if(o=0){var i=this._originalMappings[o];if(void 0===e.column)for(var s=i.originalLine;i&&i.originalLine===s;)t.push({line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o];else for(var l=i.originalColumn;i&&i.originalLine===n&&i.originalColumn==l;)t.push({line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o]}return t},n.SourceMapConsumer=t,o.prototype=Object.create(t.prototype),o.prototype.consumer=t,o.prototype._findSourceIndex=function(e){var n=e;if(null!=this.sourceRoot&&(n=a.relative(this.sourceRoot,n)),this._sources.has(n))return this._sources.indexOf(n);var r;for(r=0;r1&&(r.source=d+o[1],d+=o[1],r.originalLine=h+o[2],h=r.originalLine,r.originalLine+=1,r.originalColumn=f+o[3],f=r.originalColumn,o.length>4&&(r.name=m+o[4],m+=o[4])),A.push(r),"number"==typeof r.originalLine&&S.push(r)}g(A,a.compareByGeneratedPositionsDeflated),this.__generatedMappings=A,g(S,a.compareByOriginalPositions),this.__originalMappings=S},o.prototype._findMapping=function(e,n,r,t,o,i){if(e[r]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[r]);if(e[t]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[t]);return u.search(e,n,o,i)},o.prototype.computeColumnSpans=function(){for(var e=0;e=0){var o=this._generatedMappings[r];if(o.generatedLine===n.generatedLine){var i=a.getArg(o,"source",null);null!==i&&(i=this._sources.at(i),i=a.computeSourceURL(this.sourceRoot,i,this._sourceMapURL));var s=a.getArg(o,"name",null);return null!==s&&(s=this._names.at(s)),{source:i,line:a.getArg(o,"originalLine",null),column:a.getArg(o,"originalColumn",null),name:s}}}return{source:null,line:null,column:null,name:null}},o.prototype.hasContentsOfAllSources=function(){return!!this.sourcesContent&&(this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return null==e}))},o.prototype.sourceContentFor=function(e,n){if(!this.sourcesContent)return null;var r=this._findSourceIndex(e);if(r>=0)return this.sourcesContent[r];var t=e;null!=this.sourceRoot&&(t=a.relative(this.sourceRoot,t));var o;if(null!=this.sourceRoot&&(o=a.urlParse(this.sourceRoot))){var i=t.replace(/^file:\/\//,"");if("file"==o.scheme&&this._sources.has(i))return this.sourcesContent[this._sources.indexOf(i)];if((!o.path||"/"==o.path)&&this._sources.has("/"+t))return this.sourcesContent[this._sources.indexOf("/"+t)]}if(n)return null;throw new Error('"'+t+'" is not in the SourceMap.')},o.prototype.generatedPositionFor=function(e){var n=a.getArg(e,"source");if(n=this._findSourceIndex(n),n<0)return{line:null,column:null,lastColumn:null};var r={source:n,originalLine:a.getArg(e,"line"),originalColumn:a.getArg(e,"column")},o=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",a.compareByOriginalPositions,a.getArg(e,"bias",t.GREATEST_LOWER_BOUND));if(o>=0){var i=this._originalMappings[o];if(i.source===r.source)return{line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},n.BasicSourceMapConsumer=o,s.prototype=Object.create(t.prototype),s.prototype.constructor=t,s.prototype._version=3,Object.defineProperty(s.prototype,"sources",{get:function(){for(var e=[],n=0;n0?t-u>1?r(u,t,o,i,s,a):a==n.LEAST_UPPER_BOUND?t1?r(e,u,o,i,s,a):a==n.LEAST_UPPER_BOUND?u:e<0?-1:e}n.GREATEST_LOWER_BOUND=1,n.LEAST_UPPER_BOUND=2,n.search=function(e,t,o,i){if(0===t.length)return-1;var s=r(-1,t.length,e,t,o,i||n.GREATEST_LOWER_BOUND);if(s<0)return-1;for(;s-1>=0&&0===o(t[s],t[s-1],!0);)--s;return s}},function(e,n){function r(e,n,r){var t=e[n];e[n]=e[r],e[r]=t}function t(e,n){return Math.round(e+Math.random()*(n-e))}function o(e,n,i,s){if(i=0;n--)this.prepend(e[n]);else{if(!e[u]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);this.children.unshift(e)}return this},t.prototype.walk=function(e){for(var n,r=0,t=this.children.length;r0){for(n=[],r=0;r 0 && aGenerated.column >= 0\n\t && !aOriginal && !aSource && !aName) {\n\t // Case 1.\n\t return;\n\t }\n\t else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n\t && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n\t && aGenerated.line > 0 && aGenerated.column >= 0\n\t && aOriginal.line > 0 && aOriginal.column >= 0\n\t && aSource) {\n\t // Cases 2 and 3.\n\t return;\n\t }\n\t else {\n\t throw new Error('Invalid mapping: ' + JSON.stringify({\n\t generated: aGenerated,\n\t source: aSource,\n\t original: aOriginal,\n\t name: aName\n\t }));\n\t }\n\t };\n\t\n\t/**\n\t * Serialize the accumulated mappings in to the stream of base 64 VLQs\n\t * specified by the source map format.\n\t */\n\tSourceMapGenerator.prototype._serializeMappings =\n\t function SourceMapGenerator_serializeMappings() {\n\t var previousGeneratedColumn = 0;\n\t var previousGeneratedLine = 1;\n\t var previousOriginalColumn = 0;\n\t var previousOriginalLine = 0;\n\t var previousName = 0;\n\t var previousSource = 0;\n\t var result = '';\n\t var next;\n\t var mapping;\n\t var nameIdx;\n\t var sourceIdx;\n\t\n\t var mappings = this._mappings.toArray();\n\t for (var i = 0, len = mappings.length; i < len; i++) {\n\t mapping = mappings[i];\n\t next = ''\n\t\n\t if (mapping.generatedLine !== previousGeneratedLine) {\n\t previousGeneratedColumn = 0;\n\t while (mapping.generatedLine !== previousGeneratedLine) {\n\t next += ';';\n\t previousGeneratedLine++;\n\t }\n\t }\n\t else {\n\t if (i > 0) {\n\t if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n\t continue;\n\t }\n\t next += ',';\n\t }\n\t }\n\t\n\t next += base64VLQ.encode(mapping.generatedColumn\n\t - previousGeneratedColumn);\n\t previousGeneratedColumn = mapping.generatedColumn;\n\t\n\t if (mapping.source != null) {\n\t sourceIdx = this._sources.indexOf(mapping.source);\n\t next += base64VLQ.encode(sourceIdx - previousSource);\n\t previousSource = sourceIdx;\n\t\n\t // lines are stored 0-based in SourceMap spec version 3\n\t next += base64VLQ.encode(mapping.originalLine - 1\n\t - previousOriginalLine);\n\t previousOriginalLine = mapping.originalLine - 1;\n\t\n\t next += base64VLQ.encode(mapping.originalColumn\n\t - previousOriginalColumn);\n\t previousOriginalColumn = mapping.originalColumn;\n\t\n\t if (mapping.name != null) {\n\t nameIdx = this._names.indexOf(mapping.name);\n\t next += base64VLQ.encode(nameIdx - previousName);\n\t previousName = nameIdx;\n\t }\n\t }\n\t\n\t result += next;\n\t }\n\t\n\t return result;\n\t };\n\t\n\tSourceMapGenerator.prototype._generateSourcesContent =\n\t function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n\t return aSources.map(function (source) {\n\t if (!this._sourcesContents) {\n\t return null;\n\t }\n\t if (aSourceRoot != null) {\n\t source = util.relative(aSourceRoot, source);\n\t }\n\t var key = util.toSetString(source);\n\t return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n\t ? this._sourcesContents[key]\n\t : null;\n\t }, this);\n\t };\n\t\n\t/**\n\t * Externalize the source map.\n\t */\n\tSourceMapGenerator.prototype.toJSON =\n\t function SourceMapGenerator_toJSON() {\n\t var map = {\n\t version: this._version,\n\t sources: this._sources.toArray(),\n\t names: this._names.toArray(),\n\t mappings: this._serializeMappings()\n\t };\n\t if (this._file != null) {\n\t map.file = this._file;\n\t }\n\t if (this._sourceRoot != null) {\n\t map.sourceRoot = this._sourceRoot;\n\t }\n\t if (this._sourcesContents) {\n\t map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n\t }\n\t\n\t return map;\n\t };\n\t\n\t/**\n\t * Render the source map being generated to a string.\n\t */\n\tSourceMapGenerator.prototype.toString =\n\t function SourceMapGenerator_toString() {\n\t return JSON.stringify(this.toJSON());\n\t };\n\t\n\texports.SourceMapGenerator = SourceMapGenerator;\n\n\n/***/ }),\n/* 2 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t *\n\t * Based on the Base 64 VLQ implementation in Closure Compiler:\n\t * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n\t *\n\t * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n\t * Redistribution and use in source and binary forms, with or without\n\t * modification, are permitted provided that the following conditions are\n\t * met:\n\t *\n\t * * Redistributions of source code must retain the above copyright\n\t * notice, this list of conditions and the following disclaimer.\n\t * * Redistributions in binary form must reproduce the above\n\t * copyright notice, this list of conditions and the following\n\t * disclaimer in the documentation and/or other materials provided\n\t * with the distribution.\n\t * * Neither the name of Google Inc. nor the names of its\n\t * contributors may be used to endorse or promote products derived\n\t * from this software without specific prior written permission.\n\t *\n\t * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\t * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\t * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\t * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\t * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\t * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\t * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\t * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\t * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\t * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\t * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\t */\n\t\n\tvar base64 = __webpack_require__(3);\n\t\n\t// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n\t// length quantities we use in the source map spec, the first bit is the sign,\n\t// the next four bits are the actual value, and the 6th bit is the\n\t// continuation bit. The continuation bit tells us whether there are more\n\t// digits in this value following this digit.\n\t//\n\t// Continuation\n\t// | Sign\n\t// | |\n\t// V V\n\t// 101011\n\t\n\tvar VLQ_BASE_SHIFT = 5;\n\t\n\t// binary: 100000\n\tvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\t\n\t// binary: 011111\n\tvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\t\n\t// binary: 100000\n\tvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\t\n\t/**\n\t * Converts from a two-complement value to a value where the sign bit is\n\t * placed in the least significant bit. For example, as decimals:\n\t * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n\t * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n\t */\n\tfunction toVLQSigned(aValue) {\n\t return aValue < 0\n\t ? ((-aValue) << 1) + 1\n\t : (aValue << 1) + 0;\n\t}\n\t\n\t/**\n\t * Converts to a two-complement value from a value where the sign bit is\n\t * placed in the least significant bit. For example, as decimals:\n\t * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n\t * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n\t */\n\tfunction fromVLQSigned(aValue) {\n\t var isNegative = (aValue & 1) === 1;\n\t var shifted = aValue >> 1;\n\t return isNegative\n\t ? -shifted\n\t : shifted;\n\t}\n\t\n\t/**\n\t * Returns the base 64 VLQ encoded value.\n\t */\n\texports.encode = function base64VLQ_encode(aValue) {\n\t var encoded = \"\";\n\t var digit;\n\t\n\t var vlq = toVLQSigned(aValue);\n\t\n\t do {\n\t digit = vlq & VLQ_BASE_MASK;\n\t vlq >>>= VLQ_BASE_SHIFT;\n\t if (vlq > 0) {\n\t // There are still more digits in this value, so we must make sure the\n\t // continuation bit is marked.\n\t digit |= VLQ_CONTINUATION_BIT;\n\t }\n\t encoded += base64.encode(digit);\n\t } while (vlq > 0);\n\t\n\t return encoded;\n\t};\n\t\n\t/**\n\t * Decodes the next base 64 VLQ value from the given string and returns the\n\t * value and the rest of the string via the out parameter.\n\t */\n\texports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n\t var strLen = aStr.length;\n\t var result = 0;\n\t var shift = 0;\n\t var continuation, digit;\n\t\n\t do {\n\t if (aIndex >= strLen) {\n\t throw new Error(\"Expected more digits in base 64 VLQ value.\");\n\t }\n\t\n\t digit = base64.decode(aStr.charCodeAt(aIndex++));\n\t if (digit === -1) {\n\t throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n\t }\n\t\n\t continuation = !!(digit & VLQ_CONTINUATION_BIT);\n\t digit &= VLQ_BASE_MASK;\n\t result = result + (digit << shift);\n\t shift += VLQ_BASE_SHIFT;\n\t } while (continuation);\n\t\n\t aOutParam.value = fromVLQSigned(result);\n\t aOutParam.rest = aIndex;\n\t};\n\n\n/***/ }),\n/* 3 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\t\n\t/**\n\t * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n\t */\n\texports.encode = function (number) {\n\t if (0 <= number && number < intToCharMap.length) {\n\t return intToCharMap[number];\n\t }\n\t throw new TypeError(\"Must be between 0 and 63: \" + number);\n\t};\n\t\n\t/**\n\t * Decode a single base 64 character code digit to an integer. Returns -1 on\n\t * failure.\n\t */\n\texports.decode = function (charCode) {\n\t var bigA = 65; // 'A'\n\t var bigZ = 90; // 'Z'\n\t\n\t var littleA = 97; // 'a'\n\t var littleZ = 122; // 'z'\n\t\n\t var zero = 48; // '0'\n\t var nine = 57; // '9'\n\t\n\t var plus = 43; // '+'\n\t var slash = 47; // '/'\n\t\n\t var littleOffset = 26;\n\t var numberOffset = 52;\n\t\n\t // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n\t if (bigA <= charCode && charCode <= bigZ) {\n\t return (charCode - bigA);\n\t }\n\t\n\t // 26 - 51: abcdefghijklmnopqrstuvwxyz\n\t if (littleA <= charCode && charCode <= littleZ) {\n\t return (charCode - littleA + littleOffset);\n\t }\n\t\n\t // 52 - 61: 0123456789\n\t if (zero <= charCode && charCode <= nine) {\n\t return (charCode - zero + numberOffset);\n\t }\n\t\n\t // 62: +\n\t if (charCode == plus) {\n\t return 62;\n\t }\n\t\n\t // 63: /\n\t if (charCode == slash) {\n\t return 63;\n\t }\n\t\n\t // Invalid base64 digit.\n\t return -1;\n\t};\n\n\n/***/ }),\n/* 4 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\t/**\n\t * This is a helper function for getting values from parameter/options\n\t * objects.\n\t *\n\t * @param args The object we are extracting values from\n\t * @param name The name of the property we are getting.\n\t * @param defaultValue An optional value to return if the property is missing\n\t * from the object. If this is not specified and the property is missing, an\n\t * error will be thrown.\n\t */\n\tfunction getArg(aArgs, aName, aDefaultValue) {\n\t if (aName in aArgs) {\n\t return aArgs[aName];\n\t } else if (arguments.length === 3) {\n\t return aDefaultValue;\n\t } else {\n\t throw new Error('\"' + aName + '\" is a required argument.');\n\t }\n\t}\n\texports.getArg = getArg;\n\t\n\tvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.-]*)(?::(\\d+))?(.*)$/;\n\tvar dataUrlRegexp = /^data:.+\\,.+$/;\n\t\n\tfunction urlParse(aUrl) {\n\t var match = aUrl.match(urlRegexp);\n\t if (!match) {\n\t return null;\n\t }\n\t return {\n\t scheme: match[1],\n\t auth: match[2],\n\t host: match[3],\n\t port: match[4],\n\t path: match[5]\n\t };\n\t}\n\texports.urlParse = urlParse;\n\t\n\tfunction urlGenerate(aParsedUrl) {\n\t var url = '';\n\t if (aParsedUrl.scheme) {\n\t url += aParsedUrl.scheme + ':';\n\t }\n\t url += '//';\n\t if (aParsedUrl.auth) {\n\t url += aParsedUrl.auth + '@';\n\t }\n\t if (aParsedUrl.host) {\n\t url += aParsedUrl.host;\n\t }\n\t if (aParsedUrl.port) {\n\t url += \":\" + aParsedUrl.port\n\t }\n\t if (aParsedUrl.path) {\n\t url += aParsedUrl.path;\n\t }\n\t return url;\n\t}\n\texports.urlGenerate = urlGenerate;\n\t\n\t/**\n\t * Normalizes a path, or the path portion of a URL:\n\t *\n\t * - Replaces consecutive slashes with one slash.\n\t * - Removes unnecessary '.' parts.\n\t * - Removes unnecessary '/..' parts.\n\t *\n\t * Based on code in the Node.js 'path' core module.\n\t *\n\t * @param aPath The path or url to normalize.\n\t */\n\tfunction normalize(aPath) {\n\t var path = aPath;\n\t var url = urlParse(aPath);\n\t if (url) {\n\t if (!url.path) {\n\t return aPath;\n\t }\n\t path = url.path;\n\t }\n\t var isAbsolute = exports.isAbsolute(path);\n\t\n\t var parts = path.split(/\\/+/);\n\t for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n\t part = parts[i];\n\t if (part === '.') {\n\t parts.splice(i, 1);\n\t } else if (part === '..') {\n\t up++;\n\t } else if (up > 0) {\n\t if (part === '') {\n\t // The first part is blank if the path is absolute. Trying to go\n\t // above the root is a no-op. Therefore we can remove all '..' parts\n\t // directly after the root.\n\t parts.splice(i + 1, up);\n\t up = 0;\n\t } else {\n\t parts.splice(i, 2);\n\t up--;\n\t }\n\t }\n\t }\n\t path = parts.join('/');\n\t\n\t if (path === '') {\n\t path = isAbsolute ? '/' : '.';\n\t }\n\t\n\t if (url) {\n\t url.path = path;\n\t return urlGenerate(url);\n\t }\n\t return path;\n\t}\n\texports.normalize = normalize;\n\t\n\t/**\n\t * Joins two paths/URLs.\n\t *\n\t * @param aRoot The root path or URL.\n\t * @param aPath The path or URL to be joined with the root.\n\t *\n\t * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n\t * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n\t * first.\n\t * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n\t * is updated with the result and aRoot is returned. Otherwise the result\n\t * is returned.\n\t * - If aPath is absolute, the result is aPath.\n\t * - Otherwise the two paths are joined with a slash.\n\t * - Joining for example 'http://' and 'www.example.com' is also supported.\n\t */\n\tfunction join(aRoot, aPath) {\n\t if (aRoot === \"\") {\n\t aRoot = \".\";\n\t }\n\t if (aPath === \"\") {\n\t aPath = \".\";\n\t }\n\t var aPathUrl = urlParse(aPath);\n\t var aRootUrl = urlParse(aRoot);\n\t if (aRootUrl) {\n\t aRoot = aRootUrl.path || '/';\n\t }\n\t\n\t // `join(foo, '//www.example.org')`\n\t if (aPathUrl && !aPathUrl.scheme) {\n\t if (aRootUrl) {\n\t aPathUrl.scheme = aRootUrl.scheme;\n\t }\n\t return urlGenerate(aPathUrl);\n\t }\n\t\n\t if (aPathUrl || aPath.match(dataUrlRegexp)) {\n\t return aPath;\n\t }\n\t\n\t // `join('http://', 'www.example.com')`\n\t if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n\t aRootUrl.host = aPath;\n\t return urlGenerate(aRootUrl);\n\t }\n\t\n\t var joined = aPath.charAt(0) === '/'\n\t ? aPath\n\t : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\t\n\t if (aRootUrl) {\n\t aRootUrl.path = joined;\n\t return urlGenerate(aRootUrl);\n\t }\n\t return joined;\n\t}\n\texports.join = join;\n\t\n\texports.isAbsolute = function (aPath) {\n\t return aPath.charAt(0) === '/' || urlRegexp.test(aPath);\n\t};\n\t\n\t/**\n\t * Make a path relative to a URL or another path.\n\t *\n\t * @param aRoot The root path or URL.\n\t * @param aPath The path or URL to be made relative to aRoot.\n\t */\n\tfunction relative(aRoot, aPath) {\n\t if (aRoot === \"\") {\n\t aRoot = \".\";\n\t }\n\t\n\t aRoot = aRoot.replace(/\\/$/, '');\n\t\n\t // It is possible for the path to be above the root. In this case, simply\n\t // checking whether the root is a prefix of the path won't work. Instead, we\n\t // need to remove components from the root one by one, until either we find\n\t // a prefix that fits, or we run out of components to remove.\n\t var level = 0;\n\t while (aPath.indexOf(aRoot + '/') !== 0) {\n\t var index = aRoot.lastIndexOf(\"/\");\n\t if (index < 0) {\n\t return aPath;\n\t }\n\t\n\t // If the only part of the root that is left is the scheme (i.e. http://,\n\t // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n\t // have exhausted all components, so the path is not relative to the root.\n\t aRoot = aRoot.slice(0, index);\n\t if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n\t return aPath;\n\t }\n\t\n\t ++level;\n\t }\n\t\n\t // Make sure we add a \"../\" for each component we removed from the root.\n\t return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n\t}\n\texports.relative = relative;\n\t\n\tvar supportsNullProto = (function () {\n\t var obj = Object.create(null);\n\t return !('__proto__' in obj);\n\t}());\n\t\n\tfunction identity (s) {\n\t return s;\n\t}\n\t\n\t/**\n\t * Because behavior goes wacky when you set `__proto__` on objects, we\n\t * have to prefix all the strings in our set with an arbitrary character.\n\t *\n\t * See https://github.com/mozilla/source-map/pull/31 and\n\t * https://github.com/mozilla/source-map/issues/30\n\t *\n\t * @param String aStr\n\t */\n\tfunction toSetString(aStr) {\n\t if (isProtoString(aStr)) {\n\t return '$' + aStr;\n\t }\n\t\n\t return aStr;\n\t}\n\texports.toSetString = supportsNullProto ? identity : toSetString;\n\t\n\tfunction fromSetString(aStr) {\n\t if (isProtoString(aStr)) {\n\t return aStr.slice(1);\n\t }\n\t\n\t return aStr;\n\t}\n\texports.fromSetString = supportsNullProto ? identity : fromSetString;\n\t\n\tfunction isProtoString(s) {\n\t if (!s) {\n\t return false;\n\t }\n\t\n\t var length = s.length;\n\t\n\t if (length < 9 /* \"__proto__\".length */) {\n\t return false;\n\t }\n\t\n\t if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 2) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n\t s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n\t s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n\t s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n\t s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n\t s.charCodeAt(length - 8) !== 95 /* '_' */ ||\n\t s.charCodeAt(length - 9) !== 95 /* '_' */) {\n\t return false;\n\t }\n\t\n\t for (var i = length - 10; i >= 0; i--) {\n\t if (s.charCodeAt(i) !== 36 /* '$' */) {\n\t return false;\n\t }\n\t }\n\t\n\t return true;\n\t}\n\t\n\t/**\n\t * Comparator between two mappings where the original positions are compared.\n\t *\n\t * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n\t * mappings with the same original source/line/column, but different generated\n\t * line and column the same. Useful when searching for a mapping with a\n\t * stubbed out mapping.\n\t */\n\tfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n\t var cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0 || onlyCompareOriginal) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByOriginalPositions = compareByOriginalPositions;\n\t\n\t/**\n\t * Comparator between two mappings with deflated source and name indices where\n\t * the generated positions are compared.\n\t *\n\t * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n\t * mappings with the same generated line and column, but different\n\t * source/name/original line and column the same. Useful when searching for a\n\t * mapping with a stubbed out mapping.\n\t */\n\tfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n\t var cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0 || onlyCompareGenerated) {\n\t return cmp;\n\t }\n\t\n\t cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\t\n\tfunction strcmp(aStr1, aStr2) {\n\t if (aStr1 === aStr2) {\n\t return 0;\n\t }\n\t\n\t if (aStr1 === null) {\n\t return 1; // aStr2 !== null\n\t }\n\t\n\t if (aStr2 === null) {\n\t return -1; // aStr1 !== null\n\t }\n\t\n\t if (aStr1 > aStr2) {\n\t return 1;\n\t }\n\t\n\t return -1;\n\t}\n\t\n\t/**\n\t * Comparator between two mappings with inflated source and name strings where\n\t * the generated positions are compared.\n\t */\n\tfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n\t var cmp = mappingA.generatedLine - mappingB.generatedLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = strcmp(mappingA.source, mappingB.source);\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalLine - mappingB.originalLine;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t cmp = mappingA.originalColumn - mappingB.originalColumn;\n\t if (cmp !== 0) {\n\t return cmp;\n\t }\n\t\n\t return strcmp(mappingA.name, mappingB.name);\n\t}\n\texports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n\t\n\t/**\n\t * Strip any JSON XSSI avoidance prefix from the string (as documented\n\t * in the source maps specification), and then parse the string as\n\t * JSON.\n\t */\n\tfunction parseSourceMapInput(str) {\n\t return JSON.parse(str.replace(/^\\)]}'[^\\n]*\\n/, ''));\n\t}\n\texports.parseSourceMapInput = parseSourceMapInput;\n\t\n\t/**\n\t * Compute the URL of a source given the the source root, the source's\n\t * URL, and the source map's URL.\n\t */\n\tfunction computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {\n\t sourceURL = sourceURL || '';\n\t\n\t if (sourceRoot) {\n\t // This follows what Chrome does.\n\t if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {\n\t sourceRoot += '/';\n\t }\n\t // The spec says:\n\t // Line 4: An optional source root, useful for relocating source\n\t // files on a server or removing repeated values in the\n\t // “sources” entry. This value is prepended to the individual\n\t // entries in the “source” field.\n\t sourceURL = sourceRoot + sourceURL;\n\t }\n\t\n\t // Historically, SourceMapConsumer did not take the sourceMapURL as\n\t // a parameter. This mode is still somewhat supported, which is why\n\t // this code block is conditional. However, it's preferable to pass\n\t // the source map URL to SourceMapConsumer, so that this function\n\t // can implement the source URL resolution algorithm as outlined in\n\t // the spec. This block is basically the equivalent of:\n\t // new URL(sourceURL, sourceMapURL).toString()\n\t // ... except it avoids using URL, which wasn't available in the\n\t // older releases of node still supported by this library.\n\t //\n\t // The spec says:\n\t // If the sources are not absolute URLs after prepending of the\n\t // “sourceRoot”, the sources are resolved relative to the\n\t // SourceMap (like resolving script src in a html document).\n\t if (sourceMapURL) {\n\t var parsed = urlParse(sourceMapURL);\n\t if (!parsed) {\n\t throw new Error(\"sourceMapURL could not be parsed\");\n\t }\n\t if (parsed.path) {\n\t // Strip the last path component, but keep the \"/\".\n\t var index = parsed.path.lastIndexOf('/');\n\t if (index >= 0) {\n\t parsed.path = parsed.path.substring(0, index + 1);\n\t }\n\t }\n\t sourceURL = join(urlGenerate(parsed), sourceURL);\n\t }\n\t\n\t return normalize(sourceURL);\n\t}\n\texports.computeSourceURL = computeSourceURL;\n\n\n/***/ }),\n/* 5 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\tvar has = Object.prototype.hasOwnProperty;\n\tvar hasNativeMap = typeof Map !== \"undefined\";\n\t\n\t/**\n\t * A data structure which is a combination of an array and a set. Adding a new\n\t * member is O(1), testing for membership is O(1), and finding the index of an\n\t * element is O(1). Removing elements from the set is not supported. Only\n\t * strings are supported for membership.\n\t */\n\tfunction ArraySet() {\n\t this._array = [];\n\t this._set = hasNativeMap ? new Map() : Object.create(null);\n\t}\n\t\n\t/**\n\t * Static method for creating ArraySet instances from an existing array.\n\t */\n\tArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n\t var set = new ArraySet();\n\t for (var i = 0, len = aArray.length; i < len; i++) {\n\t set.add(aArray[i], aAllowDuplicates);\n\t }\n\t return set;\n\t};\n\t\n\t/**\n\t * Return how many unique items are in this ArraySet. If duplicates have been\n\t * added, than those do not count towards the size.\n\t *\n\t * @returns Number\n\t */\n\tArraySet.prototype.size = function ArraySet_size() {\n\t return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n\t};\n\t\n\t/**\n\t * Add the given string to this set.\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n\t var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n\t var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n\t var idx = this._array.length;\n\t if (!isDuplicate || aAllowDuplicates) {\n\t this._array.push(aStr);\n\t }\n\t if (!isDuplicate) {\n\t if (hasNativeMap) {\n\t this._set.set(aStr, idx);\n\t } else {\n\t this._set[sStr] = idx;\n\t }\n\t }\n\t};\n\t\n\t/**\n\t * Is the given string a member of this set?\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.has = function ArraySet_has(aStr) {\n\t if (hasNativeMap) {\n\t return this._set.has(aStr);\n\t } else {\n\t var sStr = util.toSetString(aStr);\n\t return has.call(this._set, sStr);\n\t }\n\t};\n\t\n\t/**\n\t * What is the index of the given string in the array?\n\t *\n\t * @param String aStr\n\t */\n\tArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n\t if (hasNativeMap) {\n\t var idx = this._set.get(aStr);\n\t if (idx >= 0) {\n\t return idx;\n\t }\n\t } else {\n\t var sStr = util.toSetString(aStr);\n\t if (has.call(this._set, sStr)) {\n\t return this._set[sStr];\n\t }\n\t }\n\t\n\t throw new Error('\"' + aStr + '\" is not in the set.');\n\t};\n\t\n\t/**\n\t * What is the element at the given index?\n\t *\n\t * @param Number aIdx\n\t */\n\tArraySet.prototype.at = function ArraySet_at(aIdx) {\n\t if (aIdx >= 0 && aIdx < this._array.length) {\n\t return this._array[aIdx];\n\t }\n\t throw new Error('No element indexed by ' + aIdx);\n\t};\n\t\n\t/**\n\t * Returns the array representation of this set (which has the proper indices\n\t * indicated by indexOf). Note that this is a copy of the internal array used\n\t * for storing the members so that no one can mess with internal state.\n\t */\n\tArraySet.prototype.toArray = function ArraySet_toArray() {\n\t return this._array.slice();\n\t};\n\t\n\texports.ArraySet = ArraySet;\n\n\n/***/ }),\n/* 6 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2014 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\t\n\t/**\n\t * Determine whether mappingB is after mappingA with respect to generated\n\t * position.\n\t */\n\tfunction generatedPositionAfter(mappingA, mappingB) {\n\t // Optimized for most common case\n\t var lineA = mappingA.generatedLine;\n\t var lineB = mappingB.generatedLine;\n\t var columnA = mappingA.generatedColumn;\n\t var columnB = mappingB.generatedColumn;\n\t return lineB > lineA || lineB == lineA && columnB >= columnA ||\n\t util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n\t}\n\t\n\t/**\n\t * A data structure to provide a sorted view of accumulated mappings in a\n\t * performance conscious manner. It trades a neglibable overhead in general\n\t * case for a large speedup in case of mappings being added in order.\n\t */\n\tfunction MappingList() {\n\t this._array = [];\n\t this._sorted = true;\n\t // Serves as infimum\n\t this._last = {generatedLine: -1, generatedColumn: 0};\n\t}\n\t\n\t/**\n\t * Iterate through internal items. This method takes the same arguments that\n\t * `Array.prototype.forEach` takes.\n\t *\n\t * NOTE: The order of the mappings is NOT guaranteed.\n\t */\n\tMappingList.prototype.unsortedForEach =\n\t function MappingList_forEach(aCallback, aThisArg) {\n\t this._array.forEach(aCallback, aThisArg);\n\t };\n\t\n\t/**\n\t * Add the given source mapping.\n\t *\n\t * @param Object aMapping\n\t */\n\tMappingList.prototype.add = function MappingList_add(aMapping) {\n\t if (generatedPositionAfter(this._last, aMapping)) {\n\t this._last = aMapping;\n\t this._array.push(aMapping);\n\t } else {\n\t this._sorted = false;\n\t this._array.push(aMapping);\n\t }\n\t};\n\t\n\t/**\n\t * Returns the flat, sorted array of mappings. The mappings are sorted by\n\t * generated position.\n\t *\n\t * WARNING: This method returns internal data without copying, for\n\t * performance. The return value must NOT be mutated, and should be treated as\n\t * an immutable borrow. If you want to take ownership, you must make your own\n\t * copy.\n\t */\n\tMappingList.prototype.toArray = function MappingList_toArray() {\n\t if (!this._sorted) {\n\t this._array.sort(util.compareByGeneratedPositionsInflated);\n\t this._sorted = true;\n\t }\n\t return this._array;\n\t};\n\t\n\texports.MappingList = MappingList;\n\n\n/***/ }),\n/* 7 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar util = __webpack_require__(4);\n\tvar binarySearch = __webpack_require__(8);\n\tvar ArraySet = __webpack_require__(5).ArraySet;\n\tvar base64VLQ = __webpack_require__(2);\n\tvar quickSort = __webpack_require__(9).quickSort;\n\t\n\tfunction SourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t return sourceMap.sections != null\n\t ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)\n\t : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);\n\t}\n\t\n\tSourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {\n\t return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);\n\t}\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tSourceMapConsumer.prototype._version = 3;\n\t\n\t// `__generatedMappings` and `__originalMappings` are arrays that hold the\n\t// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n\t// are lazily instantiated, accessed via the `_generatedMappings` and\n\t// `_originalMappings` getters respectively, and we only parse the mappings\n\t// and create these arrays once queried for a source location. We jump through\n\t// these hoops because there can be many thousands of mappings, and parsing\n\t// them is expensive, so we only want to do it if we must.\n\t//\n\t// Each object in the arrays is of the form:\n\t//\n\t// {\n\t// generatedLine: The line number in the generated code,\n\t// generatedColumn: The column number in the generated code,\n\t// source: The path to the original source file that generated this\n\t// chunk of code,\n\t// originalLine: The line number in the original source that\n\t// corresponds to this chunk of generated code,\n\t// originalColumn: The column number in the original source that\n\t// corresponds to this chunk of generated code,\n\t// name: The name of the original symbol which generated this chunk of\n\t// code.\n\t// }\n\t//\n\t// All properties except for `generatedLine` and `generatedColumn` can be\n\t// `null`.\n\t//\n\t// `_generatedMappings` is ordered by the generated positions.\n\t//\n\t// `_originalMappings` is ordered by the original positions.\n\t\n\tSourceMapConsumer.prototype.__generatedMappings = null;\n\tObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n\t configurable: true,\n\t enumerable: true,\n\t get: function () {\n\t if (!this.__generatedMappings) {\n\t this._parseMappings(this._mappings, this.sourceRoot);\n\t }\n\t\n\t return this.__generatedMappings;\n\t }\n\t});\n\t\n\tSourceMapConsumer.prototype.__originalMappings = null;\n\tObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n\t configurable: true,\n\t enumerable: true,\n\t get: function () {\n\t if (!this.__originalMappings) {\n\t this._parseMappings(this._mappings, this.sourceRoot);\n\t }\n\t\n\t return this.__originalMappings;\n\t }\n\t});\n\t\n\tSourceMapConsumer.prototype._charIsMappingSeparator =\n\t function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n\t var c = aStr.charAt(index);\n\t return c === \";\" || c === \",\";\n\t };\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tSourceMapConsumer.prototype._parseMappings =\n\t function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t throw new Error(\"Subclasses must implement _parseMappings\");\n\t };\n\t\n\tSourceMapConsumer.GENERATED_ORDER = 1;\n\tSourceMapConsumer.ORIGINAL_ORDER = 2;\n\t\n\tSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\n\tSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\t\n\t/**\n\t * Iterate over each mapping between an original source/line/column and a\n\t * generated line/column in this source map.\n\t *\n\t * @param Function aCallback\n\t * The function that is called with each mapping.\n\t * @param Object aContext\n\t * Optional. If specified, this object will be the value of `this` every\n\t * time that `aCallback` is called.\n\t * @param aOrder\n\t * Either `SourceMapConsumer.GENERATED_ORDER` or\n\t * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n\t * iterate over the mappings sorted by the generated file's line/column\n\t * order or the original's source/line/column order, respectively. Defaults to\n\t * `SourceMapConsumer.GENERATED_ORDER`.\n\t */\n\tSourceMapConsumer.prototype.eachMapping =\n\t function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n\t var context = aContext || null;\n\t var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\t\n\t var mappings;\n\t switch (order) {\n\t case SourceMapConsumer.GENERATED_ORDER:\n\t mappings = this._generatedMappings;\n\t break;\n\t case SourceMapConsumer.ORIGINAL_ORDER:\n\t mappings = this._originalMappings;\n\t break;\n\t default:\n\t throw new Error(\"Unknown order of iteration.\");\n\t }\n\t\n\t var sourceRoot = this.sourceRoot;\n\t mappings.map(function (mapping) {\n\t var source = mapping.source === null ? null : this._sources.at(mapping.source);\n\t source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);\n\t return {\n\t source: source,\n\t generatedLine: mapping.generatedLine,\n\t generatedColumn: mapping.generatedColumn,\n\t originalLine: mapping.originalLine,\n\t originalColumn: mapping.originalColumn,\n\t name: mapping.name === null ? null : this._names.at(mapping.name)\n\t };\n\t }, this).forEach(aCallback, context);\n\t };\n\t\n\t/**\n\t * Returns all generated line and column information for the original source,\n\t * line, and column provided. If no column is provided, returns all mappings\n\t * corresponding to a either the line we are searching for or the next\n\t * closest line that has any mappings. Otherwise, returns all mappings\n\t * corresponding to the given line and either the column we are searching for\n\t * or the next closest column that has any offsets.\n\t *\n\t * The only argument is an object with the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number is 1-based.\n\t * - column: Optional. the column number in the original source.\n\t * The column number is 0-based.\n\t *\n\t * and an array of objects is returned, each with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tSourceMapConsumer.prototype.allGeneratedPositionsFor =\n\t function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n\t var line = util.getArg(aArgs, 'line');\n\t\n\t // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n\t // returns the index of the closest mapping less than the needle. By\n\t // setting needle.originalColumn to 0, we thus find the last mapping for\n\t // the given line, provided such a mapping exists.\n\t var needle = {\n\t source: util.getArg(aArgs, 'source'),\n\t originalLine: line,\n\t originalColumn: util.getArg(aArgs, 'column', 0)\n\t };\n\t\n\t needle.source = this._findSourceIndex(needle.source);\n\t if (needle.source < 0) {\n\t return [];\n\t }\n\t\n\t var mappings = [];\n\t\n\t var index = this._findMapping(needle,\n\t this._originalMappings,\n\t \"originalLine\",\n\t \"originalColumn\",\n\t util.compareByOriginalPositions,\n\t binarySearch.LEAST_UPPER_BOUND);\n\t if (index >= 0) {\n\t var mapping = this._originalMappings[index];\n\t\n\t if (aArgs.column === undefined) {\n\t var originalLine = mapping.originalLine;\n\t\n\t // Iterate until either we run out of mappings, or we run into\n\t // a mapping for a different line than the one we found. Since\n\t // mappings are sorted, this is guaranteed to find all mappings for\n\t // the line we found.\n\t while (mapping && mapping.originalLine === originalLine) {\n\t mappings.push({\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t });\n\t\n\t mapping = this._originalMappings[++index];\n\t }\n\t } else {\n\t var originalColumn = mapping.originalColumn;\n\t\n\t // Iterate until either we run out of mappings, or we run into\n\t // a mapping for a different line than the one we were searching for.\n\t // Since mappings are sorted, this is guaranteed to find all mappings for\n\t // the line we are searching for.\n\t while (mapping &&\n\t mapping.originalLine === line &&\n\t mapping.originalColumn == originalColumn) {\n\t mappings.push({\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t });\n\t\n\t mapping = this._originalMappings[++index];\n\t }\n\t }\n\t }\n\t\n\t return mappings;\n\t };\n\t\n\texports.SourceMapConsumer = SourceMapConsumer;\n\t\n\t/**\n\t * A BasicSourceMapConsumer instance represents a parsed source map which we can\n\t * query for information about the original file positions by giving it a file\n\t * position in the generated source.\n\t *\n\t * The first parameter is the raw source map (either as a JSON string, or\n\t * already parsed to an object). According to the spec, source maps have the\n\t * following attributes:\n\t *\n\t * - version: Which version of the source map spec this map is following.\n\t * - sources: An array of URLs to the original source files.\n\t * - names: An array of identifiers which can be referrenced by individual mappings.\n\t * - sourceRoot: Optional. The URL root from which all sources are relative.\n\t * - sourcesContent: Optional. An array of contents of the original source files.\n\t * - mappings: A string of base64 VLQs which contain the actual mappings.\n\t * - file: Optional. The generated file this source map is associated with.\n\t *\n\t * Here is an example source map, taken from the source map spec[0]:\n\t *\n\t * {\n\t * version : 3,\n\t * file: \"out.js\",\n\t * sourceRoot : \"\",\n\t * sources: [\"foo.js\", \"bar.js\"],\n\t * names: [\"src\", \"maps\", \"are\", \"fun\"],\n\t * mappings: \"AA,AB;;ABCDE;\"\n\t * }\n\t *\n\t * The second parameter, if given, is a string whose value is the URL\n\t * at which the source map was found. This URL is used to compute the\n\t * sources array.\n\t *\n\t * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n\t */\n\tfunction BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t var version = util.getArg(sourceMap, 'version');\n\t var sources = util.getArg(sourceMap, 'sources');\n\t // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n\t // requires the array) to play nice here.\n\t var names = util.getArg(sourceMap, 'names', []);\n\t var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n\t var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n\t var mappings = util.getArg(sourceMap, 'mappings');\n\t var file = util.getArg(sourceMap, 'file', null);\n\t\n\t // Once again, Sass deviates from the spec and supplies the version as a\n\t // string rather than a number, so we use loose equality checking here.\n\t if (version != this._version) {\n\t throw new Error('Unsupported version: ' + version);\n\t }\n\t\n\t if (sourceRoot) {\n\t sourceRoot = util.normalize(sourceRoot);\n\t }\n\t\n\t sources = sources\n\t .map(String)\n\t // Some source maps produce relative source paths like \"./foo.js\" instead of\n\t // \"foo.js\". Normalize these first so that future comparisons will succeed.\n\t // See bugzil.la/1090768.\n\t .map(util.normalize)\n\t // Always ensure that absolute sources are internally stored relative to\n\t // the source root, if the source root is absolute. Not doing this would\n\t // be particularly problematic when the source root is a prefix of the\n\t // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n\t .map(function (source) {\n\t return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n\t ? util.relative(sourceRoot, source)\n\t : source;\n\t });\n\t\n\t // Pass `true` below to allow duplicate names and sources. While source maps\n\t // are intended to be compressed and deduplicated, the TypeScript compiler\n\t // sometimes generates source maps with duplicates in them. See Github issue\n\t // #72 and bugzil.la/889492.\n\t this._names = ArraySet.fromArray(names.map(String), true);\n\t this._sources = ArraySet.fromArray(sources, true);\n\t\n\t this._absoluteSources = this._sources.toArray().map(function (s) {\n\t return util.computeSourceURL(sourceRoot, s, aSourceMapURL);\n\t });\n\t\n\t this.sourceRoot = sourceRoot;\n\t this.sourcesContent = sourcesContent;\n\t this._mappings = mappings;\n\t this._sourceMapURL = aSourceMapURL;\n\t this.file = file;\n\t}\n\t\n\tBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\n\tBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\t\n\t/**\n\t * Utility function to find the index of a source. Returns -1 if not\n\t * found.\n\t */\n\tBasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {\n\t var relativeSource = aSource;\n\t if (this.sourceRoot != null) {\n\t relativeSource = util.relative(this.sourceRoot, relativeSource);\n\t }\n\t\n\t if (this._sources.has(relativeSource)) {\n\t return this._sources.indexOf(relativeSource);\n\t }\n\t\n\t // Maybe aSource is an absolute URL as returned by |sources|. In\n\t // this case we can't simply undo the transform.\n\t var i;\n\t for (i = 0; i < this._absoluteSources.length; ++i) {\n\t if (this._absoluteSources[i] == aSource) {\n\t return i;\n\t }\n\t }\n\t\n\t return -1;\n\t};\n\t\n\t/**\n\t * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n\t *\n\t * @param SourceMapGenerator aSourceMap\n\t * The source map that will be consumed.\n\t * @param String aSourceMapURL\n\t * The URL at which the source map can be found (optional)\n\t * @returns BasicSourceMapConsumer\n\t */\n\tBasicSourceMapConsumer.fromSourceMap =\n\t function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {\n\t var smc = Object.create(BasicSourceMapConsumer.prototype);\n\t\n\t var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n\t var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n\t smc.sourceRoot = aSourceMap._sourceRoot;\n\t smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n\t smc.sourceRoot);\n\t smc.file = aSourceMap._file;\n\t smc._sourceMapURL = aSourceMapURL;\n\t smc._absoluteSources = smc._sources.toArray().map(function (s) {\n\t return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);\n\t });\n\t\n\t // Because we are modifying the entries (by converting string sources and\n\t // names to indices into the sources and names ArraySets), we have to make\n\t // a copy of the entry or else bad things happen. Shared mutable state\n\t // strikes again! See github issue #191.\n\t\n\t var generatedMappings = aSourceMap._mappings.toArray().slice();\n\t var destGeneratedMappings = smc.__generatedMappings = [];\n\t var destOriginalMappings = smc.__originalMappings = [];\n\t\n\t for (var i = 0, length = generatedMappings.length; i < length; i++) {\n\t var srcMapping = generatedMappings[i];\n\t var destMapping = new Mapping;\n\t destMapping.generatedLine = srcMapping.generatedLine;\n\t destMapping.generatedColumn = srcMapping.generatedColumn;\n\t\n\t if (srcMapping.source) {\n\t destMapping.source = sources.indexOf(srcMapping.source);\n\t destMapping.originalLine = srcMapping.originalLine;\n\t destMapping.originalColumn = srcMapping.originalColumn;\n\t\n\t if (srcMapping.name) {\n\t destMapping.name = names.indexOf(srcMapping.name);\n\t }\n\t\n\t destOriginalMappings.push(destMapping);\n\t }\n\t\n\t destGeneratedMappings.push(destMapping);\n\t }\n\t\n\t quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\t\n\t return smc;\n\t };\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tBasicSourceMapConsumer.prototype._version = 3;\n\t\n\t/**\n\t * The list of original sources.\n\t */\n\tObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n\t get: function () {\n\t return this._absoluteSources.slice();\n\t }\n\t});\n\t\n\t/**\n\t * Provide the JIT with a nice shape / hidden class.\n\t */\n\tfunction Mapping() {\n\t this.generatedLine = 0;\n\t this.generatedColumn = 0;\n\t this.source = null;\n\t this.originalLine = null;\n\t this.originalColumn = null;\n\t this.name = null;\n\t}\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tBasicSourceMapConsumer.prototype._parseMappings =\n\t function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t var generatedLine = 1;\n\t var previousGeneratedColumn = 0;\n\t var previousOriginalLine = 0;\n\t var previousOriginalColumn = 0;\n\t var previousSource = 0;\n\t var previousName = 0;\n\t var length = aStr.length;\n\t var index = 0;\n\t var cachedSegments = {};\n\t var temp = {};\n\t var originalMappings = [];\n\t var generatedMappings = [];\n\t var mapping, str, segment, end, value;\n\t\n\t while (index < length) {\n\t if (aStr.charAt(index) === ';') {\n\t generatedLine++;\n\t index++;\n\t previousGeneratedColumn = 0;\n\t }\n\t else if (aStr.charAt(index) === ',') {\n\t index++;\n\t }\n\t else {\n\t mapping = new Mapping();\n\t mapping.generatedLine = generatedLine;\n\t\n\t // Because each offset is encoded relative to the previous one,\n\t // many segments often have the same encoding. We can exploit this\n\t // fact by caching the parsed variable length fields of each segment,\n\t // allowing us to avoid a second parse if we encounter the same\n\t // segment again.\n\t for (end = index; end < length; end++) {\n\t if (this._charIsMappingSeparator(aStr, end)) {\n\t break;\n\t }\n\t }\n\t str = aStr.slice(index, end);\n\t\n\t segment = cachedSegments[str];\n\t if (segment) {\n\t index += str.length;\n\t } else {\n\t segment = [];\n\t while (index < end) {\n\t base64VLQ.decode(aStr, index, temp);\n\t value = temp.value;\n\t index = temp.rest;\n\t segment.push(value);\n\t }\n\t\n\t if (segment.length === 2) {\n\t throw new Error('Found a source, but no line and column');\n\t }\n\t\n\t if (segment.length === 3) {\n\t throw new Error('Found a source and line, but no column');\n\t }\n\t\n\t cachedSegments[str] = segment;\n\t }\n\t\n\t // Generated column.\n\t mapping.generatedColumn = previousGeneratedColumn + segment[0];\n\t previousGeneratedColumn = mapping.generatedColumn;\n\t\n\t if (segment.length > 1) {\n\t // Original source.\n\t mapping.source = previousSource + segment[1];\n\t previousSource += segment[1];\n\t\n\t // Original line.\n\t mapping.originalLine = previousOriginalLine + segment[2];\n\t previousOriginalLine = mapping.originalLine;\n\t // Lines are stored 0-based\n\t mapping.originalLine += 1;\n\t\n\t // Original column.\n\t mapping.originalColumn = previousOriginalColumn + segment[3];\n\t previousOriginalColumn = mapping.originalColumn;\n\t\n\t if (segment.length > 4) {\n\t // Original name.\n\t mapping.name = previousName + segment[4];\n\t previousName += segment[4];\n\t }\n\t }\n\t\n\t generatedMappings.push(mapping);\n\t if (typeof mapping.originalLine === 'number') {\n\t originalMappings.push(mapping);\n\t }\n\t }\n\t }\n\t\n\t quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);\n\t this.__generatedMappings = generatedMappings;\n\t\n\t quickSort(originalMappings, util.compareByOriginalPositions);\n\t this.__originalMappings = originalMappings;\n\t };\n\t\n\t/**\n\t * Find the mapping that best matches the hypothetical \"needle\" mapping that\n\t * we are searching for in the given \"haystack\" of mappings.\n\t */\n\tBasicSourceMapConsumer.prototype._findMapping =\n\t function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n\t aColumnName, aComparator, aBias) {\n\t // To return the position we are searching for, we must first find the\n\t // mapping for the given position and then return the opposite position it\n\t // points to. Because the mappings are sorted, we can use binary search to\n\t // find the best mapping.\n\t\n\t if (aNeedle[aLineName] <= 0) {\n\t throw new TypeError('Line must be greater than or equal to 1, got '\n\t + aNeedle[aLineName]);\n\t }\n\t if (aNeedle[aColumnName] < 0) {\n\t throw new TypeError('Column must be greater than or equal to 0, got '\n\t + aNeedle[aColumnName]);\n\t }\n\t\n\t return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n\t };\n\t\n\t/**\n\t * Compute the last column for each generated mapping. The last column is\n\t * inclusive.\n\t */\n\tBasicSourceMapConsumer.prototype.computeColumnSpans =\n\t function SourceMapConsumer_computeColumnSpans() {\n\t for (var index = 0; index < this._generatedMappings.length; ++index) {\n\t var mapping = this._generatedMappings[index];\n\t\n\t // Mappings do not contain a field for the last generated columnt. We\n\t // can come up with an optimistic estimate, however, by assuming that\n\t // mappings are contiguous (i.e. given two consecutive mappings, the\n\t // first mapping ends where the second one starts).\n\t if (index + 1 < this._generatedMappings.length) {\n\t var nextMapping = this._generatedMappings[index + 1];\n\t\n\t if (mapping.generatedLine === nextMapping.generatedLine) {\n\t mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n\t continue;\n\t }\n\t }\n\t\n\t // The last mapping for each line spans the entire line.\n\t mapping.lastGeneratedColumn = Infinity;\n\t }\n\t };\n\t\n\t/**\n\t * Returns the original source, line, and column information for the generated\n\t * source's line and column positions provided. The only argument is an object\n\t * with the following properties:\n\t *\n\t * - line: The line number in the generated source. The line number\n\t * is 1-based.\n\t * - column: The column number in the generated source. The column\n\t * number is 0-based.\n\t * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n\t * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - source: The original source file, or null.\n\t * - line: The line number in the original source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the original source, or null. The\n\t * column number is 0-based.\n\t * - name: The original identifier, or null.\n\t */\n\tBasicSourceMapConsumer.prototype.originalPositionFor =\n\t function SourceMapConsumer_originalPositionFor(aArgs) {\n\t var needle = {\n\t generatedLine: util.getArg(aArgs, 'line'),\n\t generatedColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t var index = this._findMapping(\n\t needle,\n\t this._generatedMappings,\n\t \"generatedLine\",\n\t \"generatedColumn\",\n\t util.compareByGeneratedPositionsDeflated,\n\t util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n\t );\n\t\n\t if (index >= 0) {\n\t var mapping = this._generatedMappings[index];\n\t\n\t if (mapping.generatedLine === needle.generatedLine) {\n\t var source = util.getArg(mapping, 'source', null);\n\t if (source !== null) {\n\t source = this._sources.at(source);\n\t source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);\n\t }\n\t var name = util.getArg(mapping, 'name', null);\n\t if (name !== null) {\n\t name = this._names.at(name);\n\t }\n\t return {\n\t source: source,\n\t line: util.getArg(mapping, 'originalLine', null),\n\t column: util.getArg(mapping, 'originalColumn', null),\n\t name: name\n\t };\n\t }\n\t }\n\t\n\t return {\n\t source: null,\n\t line: null,\n\t column: null,\n\t name: null\n\t };\n\t };\n\t\n\t/**\n\t * Return true if we have the source content for every source in the source\n\t * map, false otherwise.\n\t */\n\tBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n\t function BasicSourceMapConsumer_hasContentsOfAllSources() {\n\t if (!this.sourcesContent) {\n\t return false;\n\t }\n\t return this.sourcesContent.length >= this._sources.size() &&\n\t !this.sourcesContent.some(function (sc) { return sc == null; });\n\t };\n\t\n\t/**\n\t * Returns the original source content. The only argument is the url of the\n\t * original source file. Returns null if no original source content is\n\t * available.\n\t */\n\tBasicSourceMapConsumer.prototype.sourceContentFor =\n\t function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n\t if (!this.sourcesContent) {\n\t return null;\n\t }\n\t\n\t var index = this._findSourceIndex(aSource);\n\t if (index >= 0) {\n\t return this.sourcesContent[index];\n\t }\n\t\n\t var relativeSource = aSource;\n\t if (this.sourceRoot != null) {\n\t relativeSource = util.relative(this.sourceRoot, relativeSource);\n\t }\n\t\n\t var url;\n\t if (this.sourceRoot != null\n\t && (url = util.urlParse(this.sourceRoot))) {\n\t // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n\t // many users. We can help them out when they expect file:// URIs to\n\t // behave like it would if they were running a local HTTP server. See\n\t // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n\t var fileUriAbsPath = relativeSource.replace(/^file:\\/\\//, \"\");\n\t if (url.scheme == \"file\"\n\t && this._sources.has(fileUriAbsPath)) {\n\t return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n\t }\n\t\n\t if ((!url.path || url.path == \"/\")\n\t && this._sources.has(\"/\" + relativeSource)) {\n\t return this.sourcesContent[this._sources.indexOf(\"/\" + relativeSource)];\n\t }\n\t }\n\t\n\t // This function is used recursively from\n\t // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n\t // don't want to throw if we can't find the source - we just want to\n\t // return null, so we provide a flag to exit gracefully.\n\t if (nullOnMissing) {\n\t return null;\n\t }\n\t else {\n\t throw new Error('\"' + relativeSource + '\" is not in the SourceMap.');\n\t }\n\t };\n\t\n\t/**\n\t * Returns the generated line and column information for the original source,\n\t * line, and column positions provided. The only argument is an object with\n\t * the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number\n\t * is 1-based.\n\t * - column: The column number in the original source. The column\n\t * number is 0-based.\n\t * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n\t * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tBasicSourceMapConsumer.prototype.generatedPositionFor =\n\t function SourceMapConsumer_generatedPositionFor(aArgs) {\n\t var source = util.getArg(aArgs, 'source');\n\t source = this._findSourceIndex(source);\n\t if (source < 0) {\n\t return {\n\t line: null,\n\t column: null,\n\t lastColumn: null\n\t };\n\t }\n\t\n\t var needle = {\n\t source: source,\n\t originalLine: util.getArg(aArgs, 'line'),\n\t originalColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t var index = this._findMapping(\n\t needle,\n\t this._originalMappings,\n\t \"originalLine\",\n\t \"originalColumn\",\n\t util.compareByOriginalPositions,\n\t util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n\t );\n\t\n\t if (index >= 0) {\n\t var mapping = this._originalMappings[index];\n\t\n\t if (mapping.source === needle.source) {\n\t return {\n\t line: util.getArg(mapping, 'generatedLine', null),\n\t column: util.getArg(mapping, 'generatedColumn', null),\n\t lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n\t };\n\t }\n\t }\n\t\n\t return {\n\t line: null,\n\t column: null,\n\t lastColumn: null\n\t };\n\t };\n\t\n\texports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\t\n\t/**\n\t * An IndexedSourceMapConsumer instance represents a parsed source map which\n\t * we can query for information. It differs from BasicSourceMapConsumer in\n\t * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n\t * input.\n\t *\n\t * The first parameter is a raw source map (either as a JSON string, or already\n\t * parsed to an object). According to the spec for indexed source maps, they\n\t * have the following attributes:\n\t *\n\t * - version: Which version of the source map spec this map is following.\n\t * - file: Optional. The generated file this source map is associated with.\n\t * - sections: A list of section definitions.\n\t *\n\t * Each value under the \"sections\" field has two fields:\n\t * - offset: The offset into the original specified at which this section\n\t * begins to apply, defined as an object with a \"line\" and \"column\"\n\t * field.\n\t * - map: A source map definition. This source map could also be indexed,\n\t * but doesn't have to be.\n\t *\n\t * Instead of the \"map\" field, it's also possible to have a \"url\" field\n\t * specifying a URL to retrieve a source map from, but that's currently\n\t * unsupported.\n\t *\n\t * Here's an example source map, taken from the source map spec[0], but\n\t * modified to omit a section which uses the \"url\" field.\n\t *\n\t * {\n\t * version : 3,\n\t * file: \"app.js\",\n\t * sections: [{\n\t * offset: {line:100, column:10},\n\t * map: {\n\t * version : 3,\n\t * file: \"section.js\",\n\t * sources: [\"foo.js\", \"bar.js\"],\n\t * names: [\"src\", \"maps\", \"are\", \"fun\"],\n\t * mappings: \"AAAA,E;;ABCDE;\"\n\t * }\n\t * }],\n\t * }\n\t *\n\t * The second parameter, if given, is a string whose value is the URL\n\t * at which the source map was found. This URL is used to compute the\n\t * sources array.\n\t *\n\t * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n\t */\n\tfunction IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {\n\t var sourceMap = aSourceMap;\n\t if (typeof aSourceMap === 'string') {\n\t sourceMap = util.parseSourceMapInput(aSourceMap);\n\t }\n\t\n\t var version = util.getArg(sourceMap, 'version');\n\t var sections = util.getArg(sourceMap, 'sections');\n\t\n\t if (version != this._version) {\n\t throw new Error('Unsupported version: ' + version);\n\t }\n\t\n\t this._sources = new ArraySet();\n\t this._names = new ArraySet();\n\t\n\t var lastOffset = {\n\t line: -1,\n\t column: 0\n\t };\n\t this._sections = sections.map(function (s) {\n\t if (s.url) {\n\t // The url field will require support for asynchronicity.\n\t // See https://github.com/mozilla/source-map/issues/16\n\t throw new Error('Support for url field in sections not implemented.');\n\t }\n\t var offset = util.getArg(s, 'offset');\n\t var offsetLine = util.getArg(offset, 'line');\n\t var offsetColumn = util.getArg(offset, 'column');\n\t\n\t if (offsetLine < lastOffset.line ||\n\t (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n\t throw new Error('Section offsets must be ordered and non-overlapping.');\n\t }\n\t lastOffset = offset;\n\t\n\t return {\n\t generatedOffset: {\n\t // The offset fields are 0-based, but we use 1-based indices when\n\t // encoding/decoding from VLQ.\n\t generatedLine: offsetLine + 1,\n\t generatedColumn: offsetColumn + 1\n\t },\n\t consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)\n\t }\n\t });\n\t}\n\t\n\tIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\n\tIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\t\n\t/**\n\t * The version of the source mapping spec that we are consuming.\n\t */\n\tIndexedSourceMapConsumer.prototype._version = 3;\n\t\n\t/**\n\t * The list of original sources.\n\t */\n\tObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n\t get: function () {\n\t var sources = [];\n\t for (var i = 0; i < this._sections.length; i++) {\n\t for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n\t sources.push(this._sections[i].consumer.sources[j]);\n\t }\n\t }\n\t return sources;\n\t }\n\t});\n\t\n\t/**\n\t * Returns the original source, line, and column information for the generated\n\t * source's line and column positions provided. The only argument is an object\n\t * with the following properties:\n\t *\n\t * - line: The line number in the generated source. The line number\n\t * is 1-based.\n\t * - column: The column number in the generated source. The column\n\t * number is 0-based.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - source: The original source file, or null.\n\t * - line: The line number in the original source, or null. The\n\t * line number is 1-based.\n\t * - column: The column number in the original source, or null. The\n\t * column number is 0-based.\n\t * - name: The original identifier, or null.\n\t */\n\tIndexedSourceMapConsumer.prototype.originalPositionFor =\n\t function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n\t var needle = {\n\t generatedLine: util.getArg(aArgs, 'line'),\n\t generatedColumn: util.getArg(aArgs, 'column')\n\t };\n\t\n\t // Find the section containing the generated position we're trying to map\n\t // to an original position.\n\t var sectionIndex = binarySearch.search(needle, this._sections,\n\t function(needle, section) {\n\t var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n\t if (cmp) {\n\t return cmp;\n\t }\n\t\n\t return (needle.generatedColumn -\n\t section.generatedOffset.generatedColumn);\n\t });\n\t var section = this._sections[sectionIndex];\n\t\n\t if (!section) {\n\t return {\n\t source: null,\n\t line: null,\n\t column: null,\n\t name: null\n\t };\n\t }\n\t\n\t return section.consumer.originalPositionFor({\n\t line: needle.generatedLine -\n\t (section.generatedOffset.generatedLine - 1),\n\t column: needle.generatedColumn -\n\t (section.generatedOffset.generatedLine === needle.generatedLine\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0),\n\t bias: aArgs.bias\n\t });\n\t };\n\t\n\t/**\n\t * Return true if we have the source content for every source in the source\n\t * map, false otherwise.\n\t */\n\tIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n\t function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n\t return this._sections.every(function (s) {\n\t return s.consumer.hasContentsOfAllSources();\n\t });\n\t };\n\t\n\t/**\n\t * Returns the original source content. The only argument is the url of the\n\t * original source file. Returns null if no original source content is\n\t * available.\n\t */\n\tIndexedSourceMapConsumer.prototype.sourceContentFor =\n\t function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t\n\t var content = section.consumer.sourceContentFor(aSource, true);\n\t if (content) {\n\t return content;\n\t }\n\t }\n\t if (nullOnMissing) {\n\t return null;\n\t }\n\t else {\n\t throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n\t }\n\t };\n\t\n\t/**\n\t * Returns the generated line and column information for the original source,\n\t * line, and column positions provided. The only argument is an object with\n\t * the following properties:\n\t *\n\t * - source: The filename of the original source.\n\t * - line: The line number in the original source. The line number\n\t * is 1-based.\n\t * - column: The column number in the original source. The column\n\t * number is 0-based.\n\t *\n\t * and an object is returned with the following properties:\n\t *\n\t * - line: The line number in the generated source, or null. The\n\t * line number is 1-based. \n\t * - column: The column number in the generated source, or null.\n\t * The column number is 0-based.\n\t */\n\tIndexedSourceMapConsumer.prototype.generatedPositionFor =\n\t function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t\n\t // Only consider this section if the requested source is in the list of\n\t // sources of the consumer.\n\t if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {\n\t continue;\n\t }\n\t var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n\t if (generatedPosition) {\n\t var ret = {\n\t line: generatedPosition.line +\n\t (section.generatedOffset.generatedLine - 1),\n\t column: generatedPosition.column +\n\t (section.generatedOffset.generatedLine === generatedPosition.line\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0)\n\t };\n\t return ret;\n\t }\n\t }\n\t\n\t return {\n\t line: null,\n\t column: null\n\t };\n\t };\n\t\n\t/**\n\t * Parse the mappings in a string in to a data structure which we can easily\n\t * query (the ordered arrays in the `this.__generatedMappings` and\n\t * `this.__originalMappings` properties).\n\t */\n\tIndexedSourceMapConsumer.prototype._parseMappings =\n\t function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n\t this.__generatedMappings = [];\n\t this.__originalMappings = [];\n\t for (var i = 0; i < this._sections.length; i++) {\n\t var section = this._sections[i];\n\t var sectionMappings = section.consumer._generatedMappings;\n\t for (var j = 0; j < sectionMappings.length; j++) {\n\t var mapping = sectionMappings[j];\n\t\n\t var source = section.consumer._sources.at(mapping.source);\n\t source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);\n\t this._sources.add(source);\n\t source = this._sources.indexOf(source);\n\t\n\t var name = null;\n\t if (mapping.name) {\n\t name = section.consumer._names.at(mapping.name);\n\t this._names.add(name);\n\t name = this._names.indexOf(name);\n\t }\n\t\n\t // The mappings coming from the consumer for the section have\n\t // generated positions relative to the start of the section, so we\n\t // need to offset them to be relative to the start of the concatenated\n\t // generated file.\n\t var adjustedMapping = {\n\t source: source,\n\t generatedLine: mapping.generatedLine +\n\t (section.generatedOffset.generatedLine - 1),\n\t generatedColumn: mapping.generatedColumn +\n\t (section.generatedOffset.generatedLine === mapping.generatedLine\n\t ? section.generatedOffset.generatedColumn - 1\n\t : 0),\n\t originalLine: mapping.originalLine,\n\t originalColumn: mapping.originalColumn,\n\t name: name\n\t };\n\t\n\t this.__generatedMappings.push(adjustedMapping);\n\t if (typeof adjustedMapping.originalLine === 'number') {\n\t this.__originalMappings.push(adjustedMapping);\n\t }\n\t }\n\t }\n\t\n\t quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n\t quickSort(this.__originalMappings, util.compareByOriginalPositions);\n\t };\n\t\n\texports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n\n\n/***/ }),\n/* 8 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\texports.GREATEST_LOWER_BOUND = 1;\n\texports.LEAST_UPPER_BOUND = 2;\n\t\n\t/**\n\t * Recursive implementation of binary search.\n\t *\n\t * @param aLow Indices here and lower do not contain the needle.\n\t * @param aHigh Indices here and higher do not contain the needle.\n\t * @param aNeedle The element being searched for.\n\t * @param aHaystack The non-empty array being searched.\n\t * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n\t * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n\t * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t */\n\tfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n\t // This function terminates when one of the following is true:\n\t //\n\t // 1. We find the exact element we are looking for.\n\t //\n\t // 2. We did not find the exact element, but we can return the index of\n\t // the next-closest element.\n\t //\n\t // 3. We did not find the exact element, and there is no next-closest\n\t // element than the one we are searching for, so we return -1.\n\t var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n\t var cmp = aCompare(aNeedle, aHaystack[mid], true);\n\t if (cmp === 0) {\n\t // Found the element we are looking for.\n\t return mid;\n\t }\n\t else if (cmp > 0) {\n\t // Our needle is greater than aHaystack[mid].\n\t if (aHigh - mid > 1) {\n\t // The element is in the upper half.\n\t return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n\t }\n\t\n\t // The exact needle element was not found in this haystack. Determine if\n\t // we are in termination case (3) or (2) and return the appropriate thing.\n\t if (aBias == exports.LEAST_UPPER_BOUND) {\n\t return aHigh < aHaystack.length ? aHigh : -1;\n\t } else {\n\t return mid;\n\t }\n\t }\n\t else {\n\t // Our needle is less than aHaystack[mid].\n\t if (mid - aLow > 1) {\n\t // The element is in the lower half.\n\t return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n\t }\n\t\n\t // we are in termination case (3) or (2) and return the appropriate thing.\n\t if (aBias == exports.LEAST_UPPER_BOUND) {\n\t return mid;\n\t } else {\n\t return aLow < 0 ? -1 : aLow;\n\t }\n\t }\n\t}\n\t\n\t/**\n\t * This is an implementation of binary search which will always try and return\n\t * the index of the closest element if there is no exact hit. This is because\n\t * mappings between original and generated line/col pairs are single points,\n\t * and there is an implicit region between each of them, so a miss just means\n\t * that you aren't on the very start of a region.\n\t *\n\t * @param aNeedle The element you are looking for.\n\t * @param aHaystack The array that is being searched.\n\t * @param aCompare A function which takes the needle and an element in the\n\t * array and returns -1, 0, or 1 depending on whether the needle is less\n\t * than, equal to, or greater than the element, respectively.\n\t * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n\t * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n\t * closest element that is smaller than or greater than the one we are\n\t * searching for, respectively, if the exact element cannot be found.\n\t * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n\t */\n\texports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n\t if (aHaystack.length === 0) {\n\t return -1;\n\t }\n\t\n\t var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n\t aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n\t if (index < 0) {\n\t return -1;\n\t }\n\t\n\t // We have found either the exact element, or the next-closest element than\n\t // the one we are searching for. However, there may be more than one such\n\t // element. Make sure we always return the smallest of these.\n\t while (index - 1 >= 0) {\n\t if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n\t break;\n\t }\n\t --index;\n\t }\n\t\n\t return index;\n\t};\n\n\n/***/ }),\n/* 9 */\n/***/ (function(module, exports) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\t// It turns out that some (most?) JavaScript engines don't self-host\n\t// `Array.prototype.sort`. This makes sense because C++ will likely remain\n\t// faster than JS when doing raw CPU-intensive sorting. However, when using a\n\t// custom comparator function, calling back and forth between the VM's C++ and\n\t// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n\t// worse generated code for the comparator function than would be optimal. In\n\t// fact, when sorting with a comparator, these costs outweigh the benefits of\n\t// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n\t// a ~3500ms mean speed-up in `bench/bench.html`.\n\t\n\t/**\n\t * Swap the elements indexed by `x` and `y` in the array `ary`.\n\t *\n\t * @param {Array} ary\n\t * The array.\n\t * @param {Number} x\n\t * The index of the first item.\n\t * @param {Number} y\n\t * The index of the second item.\n\t */\n\tfunction swap(ary, x, y) {\n\t var temp = ary[x];\n\t ary[x] = ary[y];\n\t ary[y] = temp;\n\t}\n\t\n\t/**\n\t * Returns a random integer within the range `low .. high` inclusive.\n\t *\n\t * @param {Number} low\n\t * The lower bound on the range.\n\t * @param {Number} high\n\t * The upper bound on the range.\n\t */\n\tfunction randomIntInRange(low, high) {\n\t return Math.round(low + (Math.random() * (high - low)));\n\t}\n\t\n\t/**\n\t * The Quick Sort algorithm.\n\t *\n\t * @param {Array} ary\n\t * An array to sort.\n\t * @param {function} comparator\n\t * Function to use to compare two items.\n\t * @param {Number} p\n\t * Start index of the array\n\t * @param {Number} r\n\t * End index of the array\n\t */\n\tfunction doQuickSort(ary, comparator, p, r) {\n\t // If our lower bound is less than our upper bound, we (1) partition the\n\t // array into two pieces and (2) recurse on each half. If it is not, this is\n\t // the empty array and our base case.\n\t\n\t if (p < r) {\n\t // (1) Partitioning.\n\t //\n\t // The partitioning chooses a pivot between `p` and `r` and moves all\n\t // elements that are less than or equal to the pivot to the before it, and\n\t // all the elements that are greater than it after it. The effect is that\n\t // once partition is done, the pivot is in the exact place it will be when\n\t // the array is put in sorted order, and it will not need to be moved\n\t // again. This runs in O(n) time.\n\t\n\t // Always choose a random pivot so that an input array which is reverse\n\t // sorted does not cause O(n^2) running time.\n\t var pivotIndex = randomIntInRange(p, r);\n\t var i = p - 1;\n\t\n\t swap(ary, pivotIndex, r);\n\t var pivot = ary[r];\n\t\n\t // Immediately after `j` is incremented in this loop, the following hold\n\t // true:\n\t //\n\t // * Every element in `ary[p .. i]` is less than or equal to the pivot.\n\t //\n\t // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n\t for (var j = p; j < r; j++) {\n\t if (comparator(ary[j], pivot) <= 0) {\n\t i += 1;\n\t swap(ary, i, j);\n\t }\n\t }\n\t\n\t swap(ary, i + 1, j);\n\t var q = i + 1;\n\t\n\t // (2) Recurse on each half.\n\t\n\t doQuickSort(ary, comparator, p, q - 1);\n\t doQuickSort(ary, comparator, q + 1, r);\n\t }\n\t}\n\t\n\t/**\n\t * Sort the given array in-place with the given comparator function.\n\t *\n\t * @param {Array} ary\n\t * An array to sort.\n\t * @param {function} comparator\n\t * Function to use to compare two items.\n\t */\n\texports.quickSort = function (ary, comparator) {\n\t doQuickSort(ary, comparator, 0, ary.length - 1);\n\t};\n\n\n/***/ }),\n/* 10 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\t/* -*- Mode: js; js-indent-level: 2; -*- */\n\t/*\n\t * Copyright 2011 Mozilla Foundation and contributors\n\t * Licensed under the New BSD license. See LICENSE or:\n\t * http://opensource.org/licenses/BSD-3-Clause\n\t */\n\t\n\tvar SourceMapGenerator = __webpack_require__(1).SourceMapGenerator;\n\tvar util = __webpack_require__(4);\n\t\n\t// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n\t// operating systems these days (capturing the result).\n\tvar REGEX_NEWLINE = /(\\r?\\n)/;\n\t\n\t// Newline character code for charCodeAt() comparisons\n\tvar NEWLINE_CODE = 10;\n\t\n\t// Private symbol for identifying `SourceNode`s when multiple versions of\n\t// the source-map library are loaded. This MUST NOT CHANGE across\n\t// versions!\n\tvar isSourceNode = \"$$$isSourceNode$$$\";\n\t\n\t/**\n\t * SourceNodes provide a way to abstract over interpolating/concatenating\n\t * snippets of generated JavaScript source code while maintaining the line and\n\t * column information associated with the original source code.\n\t *\n\t * @param aLine The original line number.\n\t * @param aColumn The original column number.\n\t * @param aSource The original source's filename.\n\t * @param aChunks Optional. An array of strings which are snippets of\n\t * generated JS, or other SourceNodes.\n\t * @param aName The original identifier.\n\t */\n\tfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n\t this.children = [];\n\t this.sourceContents = {};\n\t this.line = aLine == null ? null : aLine;\n\t this.column = aColumn == null ? null : aColumn;\n\t this.source = aSource == null ? null : aSource;\n\t this.name = aName == null ? null : aName;\n\t this[isSourceNode] = true;\n\t if (aChunks != null) this.add(aChunks);\n\t}\n\t\n\t/**\n\t * Creates a SourceNode from generated code and a SourceMapConsumer.\n\t *\n\t * @param aGeneratedCode The generated code\n\t * @param aSourceMapConsumer The SourceMap for the generated code\n\t * @param aRelativePath Optional. The path that relative sources in the\n\t * SourceMapConsumer should be relative to.\n\t */\n\tSourceNode.fromStringWithSourceMap =\n\t function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n\t // The SourceNode we want to fill with the generated code\n\t // and the SourceMap\n\t var node = new SourceNode();\n\t\n\t // All even indices of this array are one line of the generated code,\n\t // while all odd indices are the newlines between two adjacent lines\n\t // (since `REGEX_NEWLINE` captures its match).\n\t // Processed fragments are accessed by calling `shiftNextLine`.\n\t var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n\t var remainingLinesIndex = 0;\n\t var shiftNextLine = function() {\n\t var lineContents = getNextLine();\n\t // The last line of a file might not have a newline.\n\t var newLine = getNextLine() || \"\";\n\t return lineContents + newLine;\n\t\n\t function getNextLine() {\n\t return remainingLinesIndex < remainingLines.length ?\n\t remainingLines[remainingLinesIndex++] : undefined;\n\t }\n\t };\n\t\n\t // We need to remember the position of \"remainingLines\"\n\t var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\t\n\t // The generate SourceNodes we need a code range.\n\t // To extract it current and last mapping is used.\n\t // Here we store the last mapping.\n\t var lastMapping = null;\n\t\n\t aSourceMapConsumer.eachMapping(function (mapping) {\n\t if (lastMapping !== null) {\n\t // We add the code from \"lastMapping\" to \"mapping\":\n\t // First check if there is a new line in between.\n\t if (lastGeneratedLine < mapping.generatedLine) {\n\t // Associate first line with \"lastMapping\"\n\t addMappingWithCode(lastMapping, shiftNextLine());\n\t lastGeneratedLine++;\n\t lastGeneratedColumn = 0;\n\t // The remaining code is added without mapping\n\t } else {\n\t // There is no new line in between.\n\t // Associate the code between \"lastGeneratedColumn\" and\n\t // \"mapping.generatedColumn\" with \"lastMapping\"\n\t var nextLine = remainingLines[remainingLinesIndex] || '';\n\t var code = nextLine.substr(0, mapping.generatedColumn -\n\t lastGeneratedColumn);\n\t remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n\t lastGeneratedColumn);\n\t lastGeneratedColumn = mapping.generatedColumn;\n\t addMappingWithCode(lastMapping, code);\n\t // No more remaining code, continue\n\t lastMapping = mapping;\n\t return;\n\t }\n\t }\n\t // We add the generated code until the first mapping\n\t // to the SourceNode without any mapping.\n\t // Each line is added as separate string.\n\t while (lastGeneratedLine < mapping.generatedLine) {\n\t node.add(shiftNextLine());\n\t lastGeneratedLine++;\n\t }\n\t if (lastGeneratedColumn < mapping.generatedColumn) {\n\t var nextLine = remainingLines[remainingLinesIndex] || '';\n\t node.add(nextLine.substr(0, mapping.generatedColumn));\n\t remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n\t lastGeneratedColumn = mapping.generatedColumn;\n\t }\n\t lastMapping = mapping;\n\t }, this);\n\t // We have processed all mappings.\n\t if (remainingLinesIndex < remainingLines.length) {\n\t if (lastMapping) {\n\t // Associate the remaining code in the current line with \"lastMapping\"\n\t addMappingWithCode(lastMapping, shiftNextLine());\n\t }\n\t // and add the remaining lines without any mapping\n\t node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n\t }\n\t\n\t // Copy sourcesContent into SourceNode\n\t aSourceMapConsumer.sources.forEach(function (sourceFile) {\n\t var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n\t if (content != null) {\n\t if (aRelativePath != null) {\n\t sourceFile = util.join(aRelativePath, sourceFile);\n\t }\n\t node.setSourceContent(sourceFile, content);\n\t }\n\t });\n\t\n\t return node;\n\t\n\t function addMappingWithCode(mapping, code) {\n\t if (mapping === null || mapping.source === undefined) {\n\t node.add(code);\n\t } else {\n\t var source = aRelativePath\n\t ? util.join(aRelativePath, mapping.source)\n\t : mapping.source;\n\t node.add(new SourceNode(mapping.originalLine,\n\t mapping.originalColumn,\n\t source,\n\t code,\n\t mapping.name));\n\t }\n\t }\n\t };\n\t\n\t/**\n\t * Add a chunk of generated JS to this source node.\n\t *\n\t * @param aChunk A string snippet of generated JS code, another instance of\n\t * SourceNode, or an array where each member is one of those things.\n\t */\n\tSourceNode.prototype.add = function SourceNode_add(aChunk) {\n\t if (Array.isArray(aChunk)) {\n\t aChunk.forEach(function (chunk) {\n\t this.add(chunk);\n\t }, this);\n\t }\n\t else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n\t if (aChunk) {\n\t this.children.push(aChunk);\n\t }\n\t }\n\t else {\n\t throw new TypeError(\n\t \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n\t );\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Add a chunk of generated JS to the beginning of this source node.\n\t *\n\t * @param aChunk A string snippet of generated JS code, another instance of\n\t * SourceNode, or an array where each member is one of those things.\n\t */\n\tSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n\t if (Array.isArray(aChunk)) {\n\t for (var i = aChunk.length-1; i >= 0; i--) {\n\t this.prepend(aChunk[i]);\n\t }\n\t }\n\t else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n\t this.children.unshift(aChunk);\n\t }\n\t else {\n\t throw new TypeError(\n\t \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n\t );\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Walk over the tree of JS snippets in this node and its children. The\n\t * walking function is called once for each snippet of JS and is passed that\n\t * snippet and the its original associated source's line/column location.\n\t *\n\t * @param aFn The traversal function.\n\t */\n\tSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n\t var chunk;\n\t for (var i = 0, len = this.children.length; i < len; i++) {\n\t chunk = this.children[i];\n\t if (chunk[isSourceNode]) {\n\t chunk.walk(aFn);\n\t }\n\t else {\n\t if (chunk !== '') {\n\t aFn(chunk, { source: this.source,\n\t line: this.line,\n\t column: this.column,\n\t name: this.name });\n\t }\n\t }\n\t }\n\t};\n\t\n\t/**\n\t * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n\t * each of `this.children`.\n\t *\n\t * @param aSep The separator.\n\t */\n\tSourceNode.prototype.join = function SourceNode_join(aSep) {\n\t var newChildren;\n\t var i;\n\t var len = this.children.length;\n\t if (len > 0) {\n\t newChildren = [];\n\t for (i = 0; i < len-1; i++) {\n\t newChildren.push(this.children[i]);\n\t newChildren.push(aSep);\n\t }\n\t newChildren.push(this.children[i]);\n\t this.children = newChildren;\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Call String.prototype.replace on the very right-most source snippet. Useful\n\t * for trimming whitespace from the end of a source node, etc.\n\t *\n\t * @param aPattern The pattern to replace.\n\t * @param aReplacement The thing to replace the pattern with.\n\t */\n\tSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n\t var lastChild = this.children[this.children.length - 1];\n\t if (lastChild[isSourceNode]) {\n\t lastChild.replaceRight(aPattern, aReplacement);\n\t }\n\t else if (typeof lastChild === 'string') {\n\t this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n\t }\n\t else {\n\t this.children.push(''.replace(aPattern, aReplacement));\n\t }\n\t return this;\n\t};\n\t\n\t/**\n\t * Set the source content for a source file. This will be added to the SourceMapGenerator\n\t * in the sourcesContent field.\n\t *\n\t * @param aSourceFile The filename of the source file\n\t * @param aSourceContent The content of the source file\n\t */\n\tSourceNode.prototype.setSourceContent =\n\t function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n\t this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n\t };\n\t\n\t/**\n\t * Walk over the tree of SourceNodes. The walking function is called for each\n\t * source file content and is passed the filename and source content.\n\t *\n\t * @param aFn The traversal function.\n\t */\n\tSourceNode.prototype.walkSourceContents =\n\t function SourceNode_walkSourceContents(aFn) {\n\t for (var i = 0, len = this.children.length; i < len; i++) {\n\t if (this.children[i][isSourceNode]) {\n\t this.children[i].walkSourceContents(aFn);\n\t }\n\t }\n\t\n\t var sources = Object.keys(this.sourceContents);\n\t for (var i = 0, len = sources.length; i < len; i++) {\n\t aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n\t }\n\t };\n\t\n\t/**\n\t * Return the string representation of this source node. Walks over the tree\n\t * and concatenates all the various snippets together to one string.\n\t */\n\tSourceNode.prototype.toString = function SourceNode_toString() {\n\t var str = \"\";\n\t this.walk(function (chunk) {\n\t str += chunk;\n\t });\n\t return str;\n\t};\n\t\n\t/**\n\t * Returns the string representation of this source node along with a source\n\t * map.\n\t */\n\tSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n\t var generated = {\n\t code: \"\",\n\t line: 1,\n\t column: 0\n\t };\n\t var map = new SourceMapGenerator(aArgs);\n\t var sourceMappingActive = false;\n\t var lastOriginalSource = null;\n\t var lastOriginalLine = null;\n\t var lastOriginalColumn = null;\n\t var lastOriginalName = null;\n\t this.walk(function (chunk, original) {\n\t generated.code += chunk;\n\t if (original.source !== null\n\t && original.line !== null\n\t && original.column !== null) {\n\t if(lastOriginalSource !== original.source\n\t || lastOriginalLine !== original.line\n\t || lastOriginalColumn !== original.column\n\t || lastOriginalName !== original.name) {\n\t map.addMapping({\n\t source: original.source,\n\t original: {\n\t line: original.line,\n\t column: original.column\n\t },\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t },\n\t name: original.name\n\t });\n\t }\n\t lastOriginalSource = original.source;\n\t lastOriginalLine = original.line;\n\t lastOriginalColumn = original.column;\n\t lastOriginalName = original.name;\n\t sourceMappingActive = true;\n\t } else if (sourceMappingActive) {\n\t map.addMapping({\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t }\n\t });\n\t lastOriginalSource = null;\n\t sourceMappingActive = false;\n\t }\n\t for (var idx = 0, length = chunk.length; idx < length; idx++) {\n\t if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n\t generated.line++;\n\t generated.column = 0;\n\t // Mappings end at eol\n\t if (idx + 1 === length) {\n\t lastOriginalSource = null;\n\t sourceMappingActive = false;\n\t } else if (sourceMappingActive) {\n\t map.addMapping({\n\t source: original.source,\n\t original: {\n\t line: original.line,\n\t column: original.column\n\t },\n\t generated: {\n\t line: generated.line,\n\t column: generated.column\n\t },\n\t name: original.name\n\t });\n\t }\n\t } else {\n\t generated.column++;\n\t }\n\t }\n\t });\n\t this.walkSourceContents(function (sourceFile, sourceContent) {\n\t map.setSourceContent(sourceFile, sourceContent);\n\t });\n\t\n\t return { code: generated.code, map: map };\n\t};\n\t\n\texports.SourceNode = SourceNode;\n\n\n/***/ })\n/******/ ])\n});\n;\n\n\n// WEBPACK FOOTER //\n// source-map.min.js"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 0fd5815da764db5fb9fe","/*\n * Copyright 2009-2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE.txt or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\nexports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;\nexports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;\nexports.SourceNode = require('./lib/source-node').SourceNode;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./source-map.js\n// module id = 0\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar base64VLQ = require('./base64-vlq');\nvar util = require('./util');\nvar ArraySet = require('./array-set').ArraySet;\nvar MappingList = require('./mapping-list').MappingList;\n\n/**\n * An instance of the SourceMapGenerator represents a source map which is\n * being built incrementally. You may pass an object with the following\n * properties:\n *\n * - file: The filename of the generated source.\n * - sourceRoot: A root for all relative URLs in this source map.\n */\nfunction SourceMapGenerator(aArgs) {\n if (!aArgs) {\n aArgs = {};\n }\n this._file = util.getArg(aArgs, 'file', null);\n this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);\n this._skipValidation = util.getArg(aArgs, 'skipValidation', false);\n this._sources = new ArraySet();\n this._names = new ArraySet();\n this._mappings = new MappingList();\n this._sourcesContents = null;\n}\n\nSourceMapGenerator.prototype._version = 3;\n\n/**\n * Creates a new SourceMapGenerator based on a SourceMapConsumer\n *\n * @param aSourceMapConsumer The SourceMap.\n */\nSourceMapGenerator.fromSourceMap =\n function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {\n var sourceRoot = aSourceMapConsumer.sourceRoot;\n var generator = new SourceMapGenerator({\n file: aSourceMapConsumer.file,\n sourceRoot: sourceRoot\n });\n aSourceMapConsumer.eachMapping(function (mapping) {\n var newMapping = {\n generated: {\n line: mapping.generatedLine,\n column: mapping.generatedColumn\n }\n };\n\n if (mapping.source != null) {\n newMapping.source = mapping.source;\n if (sourceRoot != null) {\n newMapping.source = util.relative(sourceRoot, newMapping.source);\n }\n\n newMapping.original = {\n line: mapping.originalLine,\n column: mapping.originalColumn\n };\n\n if (mapping.name != null) {\n newMapping.name = mapping.name;\n }\n }\n\n generator.addMapping(newMapping);\n });\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var sourceRelative = sourceFile;\n if (sourceRoot !== null) {\n sourceRelative = util.relative(sourceRoot, sourceFile);\n }\n\n if (!generator._sources.has(sourceRelative)) {\n generator._sources.add(sourceRelative);\n }\n\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n generator.setSourceContent(sourceFile, content);\n }\n });\n return generator;\n };\n\n/**\n * Add a single mapping from original source line and column to the generated\n * source's line and column for this source map being created. The mapping\n * object should have the following properties:\n *\n * - generated: An object with the generated line and column positions.\n * - original: An object with the original line and column positions.\n * - source: The original source file (relative to the sourceRoot).\n * - name: An optional original token name for this mapping.\n */\nSourceMapGenerator.prototype.addMapping =\n function SourceMapGenerator_addMapping(aArgs) {\n var generated = util.getArg(aArgs, 'generated');\n var original = util.getArg(aArgs, 'original', null);\n var source = util.getArg(aArgs, 'source', null);\n var name = util.getArg(aArgs, 'name', null);\n\n if (!this._skipValidation) {\n this._validateMapping(generated, original, source, name);\n }\n\n if (source != null) {\n source = String(source);\n if (!this._sources.has(source)) {\n this._sources.add(source);\n }\n }\n\n if (name != null) {\n name = String(name);\n if (!this._names.has(name)) {\n this._names.add(name);\n }\n }\n\n this._mappings.add({\n generatedLine: generated.line,\n generatedColumn: generated.column,\n originalLine: original != null && original.line,\n originalColumn: original != null && original.column,\n source: source,\n name: name\n });\n };\n\n/**\n * Set the source content for a source file.\n */\nSourceMapGenerator.prototype.setSourceContent =\n function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {\n var source = aSourceFile;\n if (this._sourceRoot != null) {\n source = util.relative(this._sourceRoot, source);\n }\n\n if (aSourceContent != null) {\n // Add the source content to the _sourcesContents map.\n // Create a new _sourcesContents map if the property is null.\n if (!this._sourcesContents) {\n this._sourcesContents = Object.create(null);\n }\n this._sourcesContents[util.toSetString(source)] = aSourceContent;\n } else if (this._sourcesContents) {\n // Remove the source file from the _sourcesContents map.\n // If the _sourcesContents map is empty, set the property to null.\n delete this._sourcesContents[util.toSetString(source)];\n if (Object.keys(this._sourcesContents).length === 0) {\n this._sourcesContents = null;\n }\n }\n };\n\n/**\n * Applies the mappings of a sub-source-map for a specific source file to the\n * source map being generated. Each mapping to the supplied source file is\n * rewritten using the supplied source map. Note: The resolution for the\n * resulting mappings is the minimium of this map and the supplied map.\n *\n * @param aSourceMapConsumer The source map to be applied.\n * @param aSourceFile Optional. The filename of the source file.\n * If omitted, SourceMapConsumer's file property will be used.\n * @param aSourceMapPath Optional. The dirname of the path to the source map\n * to be applied. If relative, it is relative to the SourceMapConsumer.\n * This parameter is needed when the two source maps aren't in the same\n * directory, and the source map to be applied contains relative source\n * paths. If so, those relative source paths need to be rewritten\n * relative to the SourceMapGenerator.\n */\nSourceMapGenerator.prototype.applySourceMap =\n function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {\n var sourceFile = aSourceFile;\n // If aSourceFile is omitted, we will use the file property of the SourceMap\n if (aSourceFile == null) {\n if (aSourceMapConsumer.file == null) {\n throw new Error(\n 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +\n 'or the source map\\'s \"file\" property. Both were omitted.'\n );\n }\n sourceFile = aSourceMapConsumer.file;\n }\n var sourceRoot = this._sourceRoot;\n // Make \"sourceFile\" relative if an absolute Url is passed.\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n // Applying the SourceMap can add and remove items from the sources and\n // the names array.\n var newSources = new ArraySet();\n var newNames = new ArraySet();\n\n // Find mappings for the \"sourceFile\"\n this._mappings.unsortedForEach(function (mapping) {\n if (mapping.source === sourceFile && mapping.originalLine != null) {\n // Check if it can be mapped by the source map, then update the mapping.\n var original = aSourceMapConsumer.originalPositionFor({\n line: mapping.originalLine,\n column: mapping.originalColumn\n });\n if (original.source != null) {\n // Copy mapping\n mapping.source = original.source;\n if (aSourceMapPath != null) {\n mapping.source = util.join(aSourceMapPath, mapping.source)\n }\n if (sourceRoot != null) {\n mapping.source = util.relative(sourceRoot, mapping.source);\n }\n mapping.originalLine = original.line;\n mapping.originalColumn = original.column;\n if (original.name != null) {\n mapping.name = original.name;\n }\n }\n }\n\n var source = mapping.source;\n if (source != null && !newSources.has(source)) {\n newSources.add(source);\n }\n\n var name = mapping.name;\n if (name != null && !newNames.has(name)) {\n newNames.add(name);\n }\n\n }, this);\n this._sources = newSources;\n this._names = newNames;\n\n // Copy sourcesContents of applied map.\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aSourceMapPath != null) {\n sourceFile = util.join(aSourceMapPath, sourceFile);\n }\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n this.setSourceContent(sourceFile, content);\n }\n }, this);\n };\n\n/**\n * A mapping can have one of the three levels of data:\n *\n * 1. Just the generated position.\n * 2. The Generated position, original position, and original source.\n * 3. Generated and original position, original source, as well as a name\n * token.\n *\n * To maintain consistency, we validate that any new mapping being added falls\n * in to one of these categories.\n */\nSourceMapGenerator.prototype._validateMapping =\n function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,\n aName) {\n // When aOriginal is truthy but has empty values for .line and .column,\n // it is most likely a programmer error. In this case we throw a very\n // specific error message to try to guide them the right way.\n // For example: https://github.com/Polymer/polymer-bundler/pull/519\n if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {\n throw new Error(\n 'original.line and original.column are not numbers -- you probably meant to omit ' +\n 'the original mapping entirely and only map the generated position. If so, pass ' +\n 'null for the original mapping instead of an object with empty or null values.'\n );\n }\n\n if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aGenerated.line > 0 && aGenerated.column >= 0\n && !aOriginal && !aSource && !aName) {\n // Case 1.\n return;\n }\n else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n && aGenerated.line > 0 && aGenerated.column >= 0\n && aOriginal.line > 0 && aOriginal.column >= 0\n && aSource) {\n // Cases 2 and 3.\n return;\n }\n else {\n throw new Error('Invalid mapping: ' + JSON.stringify({\n generated: aGenerated,\n source: aSource,\n original: aOriginal,\n name: aName\n }));\n }\n };\n\n/**\n * Serialize the accumulated mappings in to the stream of base 64 VLQs\n * specified by the source map format.\n */\nSourceMapGenerator.prototype._serializeMappings =\n function SourceMapGenerator_serializeMappings() {\n var previousGeneratedColumn = 0;\n var previousGeneratedLine = 1;\n var previousOriginalColumn = 0;\n var previousOriginalLine = 0;\n var previousName = 0;\n var previousSource = 0;\n var result = '';\n var next;\n var mapping;\n var nameIdx;\n var sourceIdx;\n\n var mappings = this._mappings.toArray();\n for (var i = 0, len = mappings.length; i < len; i++) {\n mapping = mappings[i];\n next = ''\n\n if (mapping.generatedLine !== previousGeneratedLine) {\n previousGeneratedColumn = 0;\n while (mapping.generatedLine !== previousGeneratedLine) {\n next += ';';\n previousGeneratedLine++;\n }\n }\n else {\n if (i > 0) {\n if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n continue;\n }\n next += ',';\n }\n }\n\n next += base64VLQ.encode(mapping.generatedColumn\n - previousGeneratedColumn);\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (mapping.source != null) {\n sourceIdx = this._sources.indexOf(mapping.source);\n next += base64VLQ.encode(sourceIdx - previousSource);\n previousSource = sourceIdx;\n\n // lines are stored 0-based in SourceMap spec version 3\n next += base64VLQ.encode(mapping.originalLine - 1\n - previousOriginalLine);\n previousOriginalLine = mapping.originalLine - 1;\n\n next += base64VLQ.encode(mapping.originalColumn\n - previousOriginalColumn);\n previousOriginalColumn = mapping.originalColumn;\n\n if (mapping.name != null) {\n nameIdx = this._names.indexOf(mapping.name);\n next += base64VLQ.encode(nameIdx - previousName);\n previousName = nameIdx;\n }\n }\n\n result += next;\n }\n\n return result;\n };\n\nSourceMapGenerator.prototype._generateSourcesContent =\n function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n return aSources.map(function (source) {\n if (!this._sourcesContents) {\n return null;\n }\n if (aSourceRoot != null) {\n source = util.relative(aSourceRoot, source);\n }\n var key = util.toSetString(source);\n return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n ? this._sourcesContents[key]\n : null;\n }, this);\n };\n\n/**\n * Externalize the source map.\n */\nSourceMapGenerator.prototype.toJSON =\n function SourceMapGenerator_toJSON() {\n var map = {\n version: this._version,\n sources: this._sources.toArray(),\n names: this._names.toArray(),\n mappings: this._serializeMappings()\n };\n if (this._file != null) {\n map.file = this._file;\n }\n if (this._sourceRoot != null) {\n map.sourceRoot = this._sourceRoot;\n }\n if (this._sourcesContents) {\n map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n }\n\n return map;\n };\n\n/**\n * Render the source map being generated to a string.\n */\nSourceMapGenerator.prototype.toString =\n function SourceMapGenerator_toString() {\n return JSON.stringify(this.toJSON());\n };\n\nexports.SourceMapGenerator = SourceMapGenerator;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-map-generator.js\n// module id = 1\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n *\n * Based on the Base 64 VLQ implementation in Closure Compiler:\n * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n *\n * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nvar base64 = require('./base64');\n\n// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n// length quantities we use in the source map spec, the first bit is the sign,\n// the next four bits are the actual value, and the 6th bit is the\n// continuation bit. The continuation bit tells us whether there are more\n// digits in this value following this digit.\n//\n// Continuation\n// | Sign\n// | |\n// V V\n// 101011\n\nvar VLQ_BASE_SHIFT = 5;\n\n// binary: 100000\nvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\n// binary: 011111\nvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\n// binary: 100000\nvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\n/**\n * Converts from a two-complement value to a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n */\nfunction toVLQSigned(aValue) {\n return aValue < 0\n ? ((-aValue) << 1) + 1\n : (aValue << 1) + 0;\n}\n\n/**\n * Converts to a two-complement value from a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n */\nfunction fromVLQSigned(aValue) {\n var isNegative = (aValue & 1) === 1;\n var shifted = aValue >> 1;\n return isNegative\n ? -shifted\n : shifted;\n}\n\n/**\n * Returns the base 64 VLQ encoded value.\n */\nexports.encode = function base64VLQ_encode(aValue) {\n var encoded = \"\";\n var digit;\n\n var vlq = toVLQSigned(aValue);\n\n do {\n digit = vlq & VLQ_BASE_MASK;\n vlq >>>= VLQ_BASE_SHIFT;\n if (vlq > 0) {\n // There are still more digits in this value, so we must make sure the\n // continuation bit is marked.\n digit |= VLQ_CONTINUATION_BIT;\n }\n encoded += base64.encode(digit);\n } while (vlq > 0);\n\n return encoded;\n};\n\n/**\n * Decodes the next base 64 VLQ value from the given string and returns the\n * value and the rest of the string via the out parameter.\n */\nexports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n var strLen = aStr.length;\n var result = 0;\n var shift = 0;\n var continuation, digit;\n\n do {\n if (aIndex >= strLen) {\n throw new Error(\"Expected more digits in base 64 VLQ value.\");\n }\n\n digit = base64.decode(aStr.charCodeAt(aIndex++));\n if (digit === -1) {\n throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n }\n\n continuation = !!(digit & VLQ_CONTINUATION_BIT);\n digit &= VLQ_BASE_MASK;\n result = result + (digit << shift);\n shift += VLQ_BASE_SHIFT;\n } while (continuation);\n\n aOutParam.value = fromVLQSigned(result);\n aOutParam.rest = aIndex;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/base64-vlq.js\n// module id = 2\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\n/**\n * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n */\nexports.encode = function (number) {\n if (0 <= number && number < intToCharMap.length) {\n return intToCharMap[number];\n }\n throw new TypeError(\"Must be between 0 and 63: \" + number);\n};\n\n/**\n * Decode a single base 64 character code digit to an integer. Returns -1 on\n * failure.\n */\nexports.decode = function (charCode) {\n var bigA = 65; // 'A'\n var bigZ = 90; // 'Z'\n\n var littleA = 97; // 'a'\n var littleZ = 122; // 'z'\n\n var zero = 48; // '0'\n var nine = 57; // '9'\n\n var plus = 43; // '+'\n var slash = 47; // '/'\n\n var littleOffset = 26;\n var numberOffset = 52;\n\n // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n if (bigA <= charCode && charCode <= bigZ) {\n return (charCode - bigA);\n }\n\n // 26 - 51: abcdefghijklmnopqrstuvwxyz\n if (littleA <= charCode && charCode <= littleZ) {\n return (charCode - littleA + littleOffset);\n }\n\n // 52 - 61: 0123456789\n if (zero <= charCode && charCode <= nine) {\n return (charCode - zero + numberOffset);\n }\n\n // 62: +\n if (charCode == plus) {\n return 62;\n }\n\n // 63: /\n if (charCode == slash) {\n return 63;\n }\n\n // Invalid base64 digit.\n return -1;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/base64.js\n// module id = 3\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n/**\n * This is a helper function for getting values from parameter/options\n * objects.\n *\n * @param args The object we are extracting values from\n * @param name The name of the property we are getting.\n * @param defaultValue An optional value to return if the property is missing\n * from the object. If this is not specified and the property is missing, an\n * error will be thrown.\n */\nfunction getArg(aArgs, aName, aDefaultValue) {\n if (aName in aArgs) {\n return aArgs[aName];\n } else if (arguments.length === 3) {\n return aDefaultValue;\n } else {\n throw new Error('\"' + aName + '\" is a required argument.');\n }\n}\nexports.getArg = getArg;\n\nvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.-]*)(?::(\\d+))?(.*)$/;\nvar dataUrlRegexp = /^data:.+\\,.+$/;\n\nfunction urlParse(aUrl) {\n var match = aUrl.match(urlRegexp);\n if (!match) {\n return null;\n }\n return {\n scheme: match[1],\n auth: match[2],\n host: match[3],\n port: match[4],\n path: match[5]\n };\n}\nexports.urlParse = urlParse;\n\nfunction urlGenerate(aParsedUrl) {\n var url = '';\n if (aParsedUrl.scheme) {\n url += aParsedUrl.scheme + ':';\n }\n url += '//';\n if (aParsedUrl.auth) {\n url += aParsedUrl.auth + '@';\n }\n if (aParsedUrl.host) {\n url += aParsedUrl.host;\n }\n if (aParsedUrl.port) {\n url += \":\" + aParsedUrl.port\n }\n if (aParsedUrl.path) {\n url += aParsedUrl.path;\n }\n return url;\n}\nexports.urlGenerate = urlGenerate;\n\n/**\n * Normalizes a path, or the path portion of a URL:\n *\n * - Replaces consecutive slashes with one slash.\n * - Removes unnecessary '.' parts.\n * - Removes unnecessary '/..' parts.\n *\n * Based on code in the Node.js 'path' core module.\n *\n * @param aPath The path or url to normalize.\n */\nfunction normalize(aPath) {\n var path = aPath;\n var url = urlParse(aPath);\n if (url) {\n if (!url.path) {\n return aPath;\n }\n path = url.path;\n }\n var isAbsolute = exports.isAbsolute(path);\n\n var parts = path.split(/\\/+/);\n for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n part = parts[i];\n if (part === '.') {\n parts.splice(i, 1);\n } else if (part === '..') {\n up++;\n } else if (up > 0) {\n if (part === '') {\n // The first part is blank if the path is absolute. Trying to go\n // above the root is a no-op. Therefore we can remove all '..' parts\n // directly after the root.\n parts.splice(i + 1, up);\n up = 0;\n } else {\n parts.splice(i, 2);\n up--;\n }\n }\n }\n path = parts.join('/');\n\n if (path === '') {\n path = isAbsolute ? '/' : '.';\n }\n\n if (url) {\n url.path = path;\n return urlGenerate(url);\n }\n return path;\n}\nexports.normalize = normalize;\n\n/**\n * Joins two paths/URLs.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be joined with the root.\n *\n * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n * first.\n * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n * is updated with the result and aRoot is returned. Otherwise the result\n * is returned.\n * - If aPath is absolute, the result is aPath.\n * - Otherwise the two paths are joined with a slash.\n * - Joining for example 'http://' and 'www.example.com' is also supported.\n */\nfunction join(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n if (aPath === \"\") {\n aPath = \".\";\n }\n var aPathUrl = urlParse(aPath);\n var aRootUrl = urlParse(aRoot);\n if (aRootUrl) {\n aRoot = aRootUrl.path || '/';\n }\n\n // `join(foo, '//www.example.org')`\n if (aPathUrl && !aPathUrl.scheme) {\n if (aRootUrl) {\n aPathUrl.scheme = aRootUrl.scheme;\n }\n return urlGenerate(aPathUrl);\n }\n\n if (aPathUrl || aPath.match(dataUrlRegexp)) {\n return aPath;\n }\n\n // `join('http://', 'www.example.com')`\n if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n aRootUrl.host = aPath;\n return urlGenerate(aRootUrl);\n }\n\n var joined = aPath.charAt(0) === '/'\n ? aPath\n : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\n if (aRootUrl) {\n aRootUrl.path = joined;\n return urlGenerate(aRootUrl);\n }\n return joined;\n}\nexports.join = join;\n\nexports.isAbsolute = function (aPath) {\n return aPath.charAt(0) === '/' || urlRegexp.test(aPath);\n};\n\n/**\n * Make a path relative to a URL or another path.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be made relative to aRoot.\n */\nfunction relative(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n\n aRoot = aRoot.replace(/\\/$/, '');\n\n // It is possible for the path to be above the root. In this case, simply\n // checking whether the root is a prefix of the path won't work. Instead, we\n // need to remove components from the root one by one, until either we find\n // a prefix that fits, or we run out of components to remove.\n var level = 0;\n while (aPath.indexOf(aRoot + '/') !== 0) {\n var index = aRoot.lastIndexOf(\"/\");\n if (index < 0) {\n return aPath;\n }\n\n // If the only part of the root that is left is the scheme (i.e. http://,\n // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n // have exhausted all components, so the path is not relative to the root.\n aRoot = aRoot.slice(0, index);\n if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n return aPath;\n }\n\n ++level;\n }\n\n // Make sure we add a \"../\" for each component we removed from the root.\n return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n}\nexports.relative = relative;\n\nvar supportsNullProto = (function () {\n var obj = Object.create(null);\n return !('__proto__' in obj);\n}());\n\nfunction identity (s) {\n return s;\n}\n\n/**\n * Because behavior goes wacky when you set `__proto__` on objects, we\n * have to prefix all the strings in our set with an arbitrary character.\n *\n * See https://github.com/mozilla/source-map/pull/31 and\n * https://github.com/mozilla/source-map/issues/30\n *\n * @param String aStr\n */\nfunction toSetString(aStr) {\n if (isProtoString(aStr)) {\n return '$' + aStr;\n }\n\n return aStr;\n}\nexports.toSetString = supportsNullProto ? identity : toSetString;\n\nfunction fromSetString(aStr) {\n if (isProtoString(aStr)) {\n return aStr.slice(1);\n }\n\n return aStr;\n}\nexports.fromSetString = supportsNullProto ? identity : fromSetString;\n\nfunction isProtoString(s) {\n if (!s) {\n return false;\n }\n\n var length = s.length;\n\n if (length < 9 /* \"__proto__\".length */) {\n return false;\n }\n\n if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||\n s.charCodeAt(length - 2) !== 95 /* '_' */ ||\n s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n s.charCodeAt(length - 8) !== 95 /* '_' */ ||\n s.charCodeAt(length - 9) !== 95 /* '_' */) {\n return false;\n }\n\n for (var i = length - 10; i >= 0; i--) {\n if (s.charCodeAt(i) !== 36 /* '$' */) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Comparator between two mappings where the original positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same original source/line/column, but different generated\n * line and column the same. Useful when searching for a mapping with a\n * stubbed out mapping.\n */\nfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n var cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0 || onlyCompareOriginal) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByOriginalPositions = compareByOriginalPositions;\n\n/**\n * Comparator between two mappings with deflated source and name indices where\n * the generated positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same generated line and column, but different\n * source/name/original line and column the same. Useful when searching for a\n * mapping with a stubbed out mapping.\n */\nfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0 || onlyCompareGenerated) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\nfunction strcmp(aStr1, aStr2) {\n if (aStr1 === aStr2) {\n return 0;\n }\n\n if (aStr1 === null) {\n return 1; // aStr2 !== null\n }\n\n if (aStr2 === null) {\n return -1; // aStr1 !== null\n }\n\n if (aStr1 > aStr2) {\n return 1;\n }\n\n return -1;\n}\n\n/**\n * Comparator between two mappings with inflated source and name strings where\n * the generated positions are compared.\n */\nfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n\n/**\n * Strip any JSON XSSI avoidance prefix from the string (as documented\n * in the source maps specification), and then parse the string as\n * JSON.\n */\nfunction parseSourceMapInput(str) {\n return JSON.parse(str.replace(/^\\)]}'[^\\n]*\\n/, ''));\n}\nexports.parseSourceMapInput = parseSourceMapInput;\n\n/**\n * Compute the URL of a source given the the source root, the source's\n * URL, and the source map's URL.\n */\nfunction computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {\n sourceURL = sourceURL || '';\n\n if (sourceRoot) {\n // This follows what Chrome does.\n if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {\n sourceRoot += '/';\n }\n // The spec says:\n // Line 4: An optional source root, useful for relocating source\n // files on a server or removing repeated values in the\n // “sources” entry. This value is prepended to the individual\n // entries in the “source” field.\n sourceURL = sourceRoot + sourceURL;\n }\n\n // Historically, SourceMapConsumer did not take the sourceMapURL as\n // a parameter. This mode is still somewhat supported, which is why\n // this code block is conditional. However, it's preferable to pass\n // the source map URL to SourceMapConsumer, so that this function\n // can implement the source URL resolution algorithm as outlined in\n // the spec. This block is basically the equivalent of:\n // new URL(sourceURL, sourceMapURL).toString()\n // ... except it avoids using URL, which wasn't available in the\n // older releases of node still supported by this library.\n //\n // The spec says:\n // If the sources are not absolute URLs after prepending of the\n // “sourceRoot”, the sources are resolved relative to the\n // SourceMap (like resolving script src in a html document).\n if (sourceMapURL) {\n var parsed = urlParse(sourceMapURL);\n if (!parsed) {\n throw new Error(\"sourceMapURL could not be parsed\");\n }\n if (parsed.path) {\n // Strip the last path component, but keep the \"/\".\n var index = parsed.path.lastIndexOf('/');\n if (index >= 0) {\n parsed.path = parsed.path.substring(0, index + 1);\n }\n }\n sourceURL = join(urlGenerate(parsed), sourceURL);\n }\n\n return normalize(sourceURL);\n}\nexports.computeSourceURL = computeSourceURL;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/util.js\n// module id = 4\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar has = Object.prototype.hasOwnProperty;\nvar hasNativeMap = typeof Map !== \"undefined\";\n\n/**\n * A data structure which is a combination of an array and a set. Adding a new\n * member is O(1), testing for membership is O(1), and finding the index of an\n * element is O(1). Removing elements from the set is not supported. Only\n * strings are supported for membership.\n */\nfunction ArraySet() {\n this._array = [];\n this._set = hasNativeMap ? new Map() : Object.create(null);\n}\n\n/**\n * Static method for creating ArraySet instances from an existing array.\n */\nArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n var set = new ArraySet();\n for (var i = 0, len = aArray.length; i < len; i++) {\n set.add(aArray[i], aAllowDuplicates);\n }\n return set;\n};\n\n/**\n * Return how many unique items are in this ArraySet. If duplicates have been\n * added, than those do not count towards the size.\n *\n * @returns Number\n */\nArraySet.prototype.size = function ArraySet_size() {\n return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n};\n\n/**\n * Add the given string to this set.\n *\n * @param String aStr\n */\nArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n var idx = this._array.length;\n if (!isDuplicate || aAllowDuplicates) {\n this._array.push(aStr);\n }\n if (!isDuplicate) {\n if (hasNativeMap) {\n this._set.set(aStr, idx);\n } else {\n this._set[sStr] = idx;\n }\n }\n};\n\n/**\n * Is the given string a member of this set?\n *\n * @param String aStr\n */\nArraySet.prototype.has = function ArraySet_has(aStr) {\n if (hasNativeMap) {\n return this._set.has(aStr);\n } else {\n var sStr = util.toSetString(aStr);\n return has.call(this._set, sStr);\n }\n};\n\n/**\n * What is the index of the given string in the array?\n *\n * @param String aStr\n */\nArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n if (hasNativeMap) {\n var idx = this._set.get(aStr);\n if (idx >= 0) {\n return idx;\n }\n } else {\n var sStr = util.toSetString(aStr);\n if (has.call(this._set, sStr)) {\n return this._set[sStr];\n }\n }\n\n throw new Error('\"' + aStr + '\" is not in the set.');\n};\n\n/**\n * What is the element at the given index?\n *\n * @param Number aIdx\n */\nArraySet.prototype.at = function ArraySet_at(aIdx) {\n if (aIdx >= 0 && aIdx < this._array.length) {\n return this._array[aIdx];\n }\n throw new Error('No element indexed by ' + aIdx);\n};\n\n/**\n * Returns the array representation of this set (which has the proper indices\n * indicated by indexOf). Note that this is a copy of the internal array used\n * for storing the members so that no one can mess with internal state.\n */\nArraySet.prototype.toArray = function ArraySet_toArray() {\n return this._array.slice();\n};\n\nexports.ArraySet = ArraySet;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/array-set.js\n// module id = 5\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2014 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\n\n/**\n * Determine whether mappingB is after mappingA with respect to generated\n * position.\n */\nfunction generatedPositionAfter(mappingA, mappingB) {\n // Optimized for most common case\n var lineA = mappingA.generatedLine;\n var lineB = mappingB.generatedLine;\n var columnA = mappingA.generatedColumn;\n var columnB = mappingB.generatedColumn;\n return lineB > lineA || lineB == lineA && columnB >= columnA ||\n util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n}\n\n/**\n * A data structure to provide a sorted view of accumulated mappings in a\n * performance conscious manner. It trades a neglibable overhead in general\n * case for a large speedup in case of mappings being added in order.\n */\nfunction MappingList() {\n this._array = [];\n this._sorted = true;\n // Serves as infimum\n this._last = {generatedLine: -1, generatedColumn: 0};\n}\n\n/**\n * Iterate through internal items. This method takes the same arguments that\n * `Array.prototype.forEach` takes.\n *\n * NOTE: The order of the mappings is NOT guaranteed.\n */\nMappingList.prototype.unsortedForEach =\n function MappingList_forEach(aCallback, aThisArg) {\n this._array.forEach(aCallback, aThisArg);\n };\n\n/**\n * Add the given source mapping.\n *\n * @param Object aMapping\n */\nMappingList.prototype.add = function MappingList_add(aMapping) {\n if (generatedPositionAfter(this._last, aMapping)) {\n this._last = aMapping;\n this._array.push(aMapping);\n } else {\n this._sorted = false;\n this._array.push(aMapping);\n }\n};\n\n/**\n * Returns the flat, sorted array of mappings. The mappings are sorted by\n * generated position.\n *\n * WARNING: This method returns internal data without copying, for\n * performance. The return value must NOT be mutated, and should be treated as\n * an immutable borrow. If you want to take ownership, you must make your own\n * copy.\n */\nMappingList.prototype.toArray = function MappingList_toArray() {\n if (!this._sorted) {\n this._array.sort(util.compareByGeneratedPositionsInflated);\n this._sorted = true;\n }\n return this._array;\n};\n\nexports.MappingList = MappingList;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/mapping-list.js\n// module id = 6\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar binarySearch = require('./binary-search');\nvar ArraySet = require('./array-set').ArraySet;\nvar base64VLQ = require('./base64-vlq');\nvar quickSort = require('./quick-sort').quickSort;\n\nfunction SourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n return sourceMap.sections != null\n ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)\n : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);\n}\n\nSourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {\n return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);\n}\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nSourceMapConsumer.prototype._version = 3;\n\n// `__generatedMappings` and `__originalMappings` are arrays that hold the\n// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n// are lazily instantiated, accessed via the `_generatedMappings` and\n// `_originalMappings` getters respectively, and we only parse the mappings\n// and create these arrays once queried for a source location. We jump through\n// these hoops because there can be many thousands of mappings, and parsing\n// them is expensive, so we only want to do it if we must.\n//\n// Each object in the arrays is of the form:\n//\n// {\n// generatedLine: The line number in the generated code,\n// generatedColumn: The column number in the generated code,\n// source: The path to the original source file that generated this\n// chunk of code,\n// originalLine: The line number in the original source that\n// corresponds to this chunk of generated code,\n// originalColumn: The column number in the original source that\n// corresponds to this chunk of generated code,\n// name: The name of the original symbol which generated this chunk of\n// code.\n// }\n//\n// All properties except for `generatedLine` and `generatedColumn` can be\n// `null`.\n//\n// `_generatedMappings` is ordered by the generated positions.\n//\n// `_originalMappings` is ordered by the original positions.\n\nSourceMapConsumer.prototype.__generatedMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__generatedMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__generatedMappings;\n }\n});\n\nSourceMapConsumer.prototype.__originalMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__originalMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__originalMappings;\n }\n});\n\nSourceMapConsumer.prototype._charIsMappingSeparator =\n function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n var c = aStr.charAt(index);\n return c === \";\" || c === \",\";\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n throw new Error(\"Subclasses must implement _parseMappings\");\n };\n\nSourceMapConsumer.GENERATED_ORDER = 1;\nSourceMapConsumer.ORIGINAL_ORDER = 2;\n\nSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\nSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\n/**\n * Iterate over each mapping between an original source/line/column and a\n * generated line/column in this source map.\n *\n * @param Function aCallback\n * The function that is called with each mapping.\n * @param Object aContext\n * Optional. If specified, this object will be the value of `this` every\n * time that `aCallback` is called.\n * @param aOrder\n * Either `SourceMapConsumer.GENERATED_ORDER` or\n * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n * iterate over the mappings sorted by the generated file's line/column\n * order or the original's source/line/column order, respectively. Defaults to\n * `SourceMapConsumer.GENERATED_ORDER`.\n */\nSourceMapConsumer.prototype.eachMapping =\n function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n var context = aContext || null;\n var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\n var mappings;\n switch (order) {\n case SourceMapConsumer.GENERATED_ORDER:\n mappings = this._generatedMappings;\n break;\n case SourceMapConsumer.ORIGINAL_ORDER:\n mappings = this._originalMappings;\n break;\n default:\n throw new Error(\"Unknown order of iteration.\");\n }\n\n var sourceRoot = this.sourceRoot;\n mappings.map(function (mapping) {\n var source = mapping.source === null ? null : this._sources.at(mapping.source);\n source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);\n return {\n source: source,\n generatedLine: mapping.generatedLine,\n generatedColumn: mapping.generatedColumn,\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: mapping.name === null ? null : this._names.at(mapping.name)\n };\n }, this).forEach(aCallback, context);\n };\n\n/**\n * Returns all generated line and column information for the original source,\n * line, and column provided. If no column is provided, returns all mappings\n * corresponding to a either the line we are searching for or the next\n * closest line that has any mappings. Otherwise, returns all mappings\n * corresponding to the given line and either the column we are searching for\n * or the next closest column that has any offsets.\n *\n * The only argument is an object with the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number is 1-based.\n * - column: Optional. the column number in the original source.\n * The column number is 0-based.\n *\n * and an array of objects is returned, each with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nSourceMapConsumer.prototype.allGeneratedPositionsFor =\n function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n var line = util.getArg(aArgs, 'line');\n\n // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n // returns the index of the closest mapping less than the needle. By\n // setting needle.originalColumn to 0, we thus find the last mapping for\n // the given line, provided such a mapping exists.\n var needle = {\n source: util.getArg(aArgs, 'source'),\n originalLine: line,\n originalColumn: util.getArg(aArgs, 'column', 0)\n };\n\n needle.source = this._findSourceIndex(needle.source);\n if (needle.source < 0) {\n return [];\n }\n\n var mappings = [];\n\n var index = this._findMapping(needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n binarySearch.LEAST_UPPER_BOUND);\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (aArgs.column === undefined) {\n var originalLine = mapping.originalLine;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we found. Since\n // mappings are sorted, this is guaranteed to find all mappings for\n // the line we found.\n while (mapping && mapping.originalLine === originalLine) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n } else {\n var originalColumn = mapping.originalColumn;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we were searching for.\n // Since mappings are sorted, this is guaranteed to find all mappings for\n // the line we are searching for.\n while (mapping &&\n mapping.originalLine === line &&\n mapping.originalColumn == originalColumn) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n }\n }\n\n return mappings;\n };\n\nexports.SourceMapConsumer = SourceMapConsumer;\n\n/**\n * A BasicSourceMapConsumer instance represents a parsed source map which we can\n * query for information about the original file positions by giving it a file\n * position in the generated source.\n *\n * The first parameter is the raw source map (either as a JSON string, or\n * already parsed to an object). According to the spec, source maps have the\n * following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - sources: An array of URLs to the original source files.\n * - names: An array of identifiers which can be referrenced by individual mappings.\n * - sourceRoot: Optional. The URL root from which all sources are relative.\n * - sourcesContent: Optional. An array of contents of the original source files.\n * - mappings: A string of base64 VLQs which contain the actual mappings.\n * - file: Optional. The generated file this source map is associated with.\n *\n * Here is an example source map, taken from the source map spec[0]:\n *\n * {\n * version : 3,\n * file: \"out.js\",\n * sourceRoot : \"\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AA,AB;;ABCDE;\"\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n */\nfunction BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sources = util.getArg(sourceMap, 'sources');\n // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n // requires the array) to play nice here.\n var names = util.getArg(sourceMap, 'names', []);\n var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n var mappings = util.getArg(sourceMap, 'mappings');\n var file = util.getArg(sourceMap, 'file', null);\n\n // Once again, Sass deviates from the spec and supplies the version as a\n // string rather than a number, so we use loose equality checking here.\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n if (sourceRoot) {\n sourceRoot = util.normalize(sourceRoot);\n }\n\n sources = sources\n .map(String)\n // Some source maps produce relative source paths like \"./foo.js\" instead of\n // \"foo.js\". Normalize these first so that future comparisons will succeed.\n // See bugzil.la/1090768.\n .map(util.normalize)\n // Always ensure that absolute sources are internally stored relative to\n // the source root, if the source root is absolute. Not doing this would\n // be particularly problematic when the source root is a prefix of the\n // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n .map(function (source) {\n return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n ? util.relative(sourceRoot, source)\n : source;\n });\n\n // Pass `true` below to allow duplicate names and sources. While source maps\n // are intended to be compressed and deduplicated, the TypeScript compiler\n // sometimes generates source maps with duplicates in them. See Github issue\n // #72 and bugzil.la/889492.\n this._names = ArraySet.fromArray(names.map(String), true);\n this._sources = ArraySet.fromArray(sources, true);\n\n this._absoluteSources = this._sources.toArray().map(function (s) {\n return util.computeSourceURL(sourceRoot, s, aSourceMapURL);\n });\n\n this.sourceRoot = sourceRoot;\n this.sourcesContent = sourcesContent;\n this._mappings = mappings;\n this._sourceMapURL = aSourceMapURL;\n this.file = file;\n}\n\nBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\n/**\n * Utility function to find the index of a source. Returns -1 if not\n * found.\n */\nBasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n if (this._sources.has(relativeSource)) {\n return this._sources.indexOf(relativeSource);\n }\n\n // Maybe aSource is an absolute URL as returned by |sources|. In\n // this case we can't simply undo the transform.\n var i;\n for (i = 0; i < this._absoluteSources.length; ++i) {\n if (this._absoluteSources[i] == aSource) {\n return i;\n }\n }\n\n return -1;\n};\n\n/**\n * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n *\n * @param SourceMapGenerator aSourceMap\n * The source map that will be consumed.\n * @param String aSourceMapURL\n * The URL at which the source map can be found (optional)\n * @returns BasicSourceMapConsumer\n */\nBasicSourceMapConsumer.fromSourceMap =\n function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {\n var smc = Object.create(BasicSourceMapConsumer.prototype);\n\n var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n smc.sourceRoot = aSourceMap._sourceRoot;\n smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n smc.sourceRoot);\n smc.file = aSourceMap._file;\n smc._sourceMapURL = aSourceMapURL;\n smc._absoluteSources = smc._sources.toArray().map(function (s) {\n return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);\n });\n\n // Because we are modifying the entries (by converting string sources and\n // names to indices into the sources and names ArraySets), we have to make\n // a copy of the entry or else bad things happen. Shared mutable state\n // strikes again! See github issue #191.\n\n var generatedMappings = aSourceMap._mappings.toArray().slice();\n var destGeneratedMappings = smc.__generatedMappings = [];\n var destOriginalMappings = smc.__originalMappings = [];\n\n for (var i = 0, length = generatedMappings.length; i < length; i++) {\n var srcMapping = generatedMappings[i];\n var destMapping = new Mapping;\n destMapping.generatedLine = srcMapping.generatedLine;\n destMapping.generatedColumn = srcMapping.generatedColumn;\n\n if (srcMapping.source) {\n destMapping.source = sources.indexOf(srcMapping.source);\n destMapping.originalLine = srcMapping.originalLine;\n destMapping.originalColumn = srcMapping.originalColumn;\n\n if (srcMapping.name) {\n destMapping.name = names.indexOf(srcMapping.name);\n }\n\n destOriginalMappings.push(destMapping);\n }\n\n destGeneratedMappings.push(destMapping);\n }\n\n quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\n return smc;\n };\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nBasicSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n get: function () {\n return this._absoluteSources.slice();\n }\n});\n\n/**\n * Provide the JIT with a nice shape / hidden class.\n */\nfunction Mapping() {\n this.generatedLine = 0;\n this.generatedColumn = 0;\n this.source = null;\n this.originalLine = null;\n this.originalColumn = null;\n this.name = null;\n}\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nBasicSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n var generatedLine = 1;\n var previousGeneratedColumn = 0;\n var previousOriginalLine = 0;\n var previousOriginalColumn = 0;\n var previousSource = 0;\n var previousName = 0;\n var length = aStr.length;\n var index = 0;\n var cachedSegments = {};\n var temp = {};\n var originalMappings = [];\n var generatedMappings = [];\n var mapping, str, segment, end, value;\n\n while (index < length) {\n if (aStr.charAt(index) === ';') {\n generatedLine++;\n index++;\n previousGeneratedColumn = 0;\n }\n else if (aStr.charAt(index) === ',') {\n index++;\n }\n else {\n mapping = new Mapping();\n mapping.generatedLine = generatedLine;\n\n // Because each offset is encoded relative to the previous one,\n // many segments often have the same encoding. We can exploit this\n // fact by caching the parsed variable length fields of each segment,\n // allowing us to avoid a second parse if we encounter the same\n // segment again.\n for (end = index; end < length; end++) {\n if (this._charIsMappingSeparator(aStr, end)) {\n break;\n }\n }\n str = aStr.slice(index, end);\n\n segment = cachedSegments[str];\n if (segment) {\n index += str.length;\n } else {\n segment = [];\n while (index < end) {\n base64VLQ.decode(aStr, index, temp);\n value = temp.value;\n index = temp.rest;\n segment.push(value);\n }\n\n if (segment.length === 2) {\n throw new Error('Found a source, but no line and column');\n }\n\n if (segment.length === 3) {\n throw new Error('Found a source and line, but no column');\n }\n\n cachedSegments[str] = segment;\n }\n\n // Generated column.\n mapping.generatedColumn = previousGeneratedColumn + segment[0];\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (segment.length > 1) {\n // Original source.\n mapping.source = previousSource + segment[1];\n previousSource += segment[1];\n\n // Original line.\n mapping.originalLine = previousOriginalLine + segment[2];\n previousOriginalLine = mapping.originalLine;\n // Lines are stored 0-based\n mapping.originalLine += 1;\n\n // Original column.\n mapping.originalColumn = previousOriginalColumn + segment[3];\n previousOriginalColumn = mapping.originalColumn;\n\n if (segment.length > 4) {\n // Original name.\n mapping.name = previousName + segment[4];\n previousName += segment[4];\n }\n }\n\n generatedMappings.push(mapping);\n if (typeof mapping.originalLine === 'number') {\n originalMappings.push(mapping);\n }\n }\n }\n\n quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);\n this.__generatedMappings = generatedMappings;\n\n quickSort(originalMappings, util.compareByOriginalPositions);\n this.__originalMappings = originalMappings;\n };\n\n/**\n * Find the mapping that best matches the hypothetical \"needle\" mapping that\n * we are searching for in the given \"haystack\" of mappings.\n */\nBasicSourceMapConsumer.prototype._findMapping =\n function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n aColumnName, aComparator, aBias) {\n // To return the position we are searching for, we must first find the\n // mapping for the given position and then return the opposite position it\n // points to. Because the mappings are sorted, we can use binary search to\n // find the best mapping.\n\n if (aNeedle[aLineName] <= 0) {\n throw new TypeError('Line must be greater than or equal to 1, got '\n + aNeedle[aLineName]);\n }\n if (aNeedle[aColumnName] < 0) {\n throw new TypeError('Column must be greater than or equal to 0, got '\n + aNeedle[aColumnName]);\n }\n\n return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n };\n\n/**\n * Compute the last column for each generated mapping. The last column is\n * inclusive.\n */\nBasicSourceMapConsumer.prototype.computeColumnSpans =\n function SourceMapConsumer_computeColumnSpans() {\n for (var index = 0; index < this._generatedMappings.length; ++index) {\n var mapping = this._generatedMappings[index];\n\n // Mappings do not contain a field for the last generated columnt. We\n // can come up with an optimistic estimate, however, by assuming that\n // mappings are contiguous (i.e. given two consecutive mappings, the\n // first mapping ends where the second one starts).\n if (index + 1 < this._generatedMappings.length) {\n var nextMapping = this._generatedMappings[index + 1];\n\n if (mapping.generatedLine === nextMapping.generatedLine) {\n mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n continue;\n }\n }\n\n // The last mapping for each line spans the entire line.\n mapping.lastGeneratedColumn = Infinity;\n }\n };\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nBasicSourceMapConsumer.prototype.originalPositionFor =\n function SourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._generatedMappings,\n \"generatedLine\",\n \"generatedColumn\",\n util.compareByGeneratedPositionsDeflated,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._generatedMappings[index];\n\n if (mapping.generatedLine === needle.generatedLine) {\n var source = util.getArg(mapping, 'source', null);\n if (source !== null) {\n source = this._sources.at(source);\n source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);\n }\n var name = util.getArg(mapping, 'name', null);\n if (name !== null) {\n name = this._names.at(name);\n }\n return {\n source: source,\n line: util.getArg(mapping, 'originalLine', null),\n column: util.getArg(mapping, 'originalColumn', null),\n name: name\n };\n }\n }\n\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n function BasicSourceMapConsumer_hasContentsOfAllSources() {\n if (!this.sourcesContent) {\n return false;\n }\n return this.sourcesContent.length >= this._sources.size() &&\n !this.sourcesContent.some(function (sc) { return sc == null; });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nBasicSourceMapConsumer.prototype.sourceContentFor =\n function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n if (!this.sourcesContent) {\n return null;\n }\n\n var index = this._findSourceIndex(aSource);\n if (index >= 0) {\n return this.sourcesContent[index];\n }\n\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n var url;\n if (this.sourceRoot != null\n && (url = util.urlParse(this.sourceRoot))) {\n // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n // many users. We can help them out when they expect file:// URIs to\n // behave like it would if they were running a local HTTP server. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n var fileUriAbsPath = relativeSource.replace(/^file:\\/\\//, \"\");\n if (url.scheme == \"file\"\n && this._sources.has(fileUriAbsPath)) {\n return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n }\n\n if ((!url.path || url.path == \"/\")\n && this._sources.has(\"/\" + relativeSource)) {\n return this.sourcesContent[this._sources.indexOf(\"/\" + relativeSource)];\n }\n }\n\n // This function is used recursively from\n // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n // don't want to throw if we can't find the source - we just want to\n // return null, so we provide a flag to exit gracefully.\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + relativeSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nBasicSourceMapConsumer.prototype.generatedPositionFor =\n function SourceMapConsumer_generatedPositionFor(aArgs) {\n var source = util.getArg(aArgs, 'source');\n source = this._findSourceIndex(source);\n if (source < 0) {\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n }\n\n var needle = {\n source: source,\n originalLine: util.getArg(aArgs, 'line'),\n originalColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (mapping.source === needle.source) {\n return {\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n };\n }\n }\n\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n };\n\nexports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\n/**\n * An IndexedSourceMapConsumer instance represents a parsed source map which\n * we can query for information. It differs from BasicSourceMapConsumer in\n * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n * input.\n *\n * The first parameter is a raw source map (either as a JSON string, or already\n * parsed to an object). According to the spec for indexed source maps, they\n * have the following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - file: Optional. The generated file this source map is associated with.\n * - sections: A list of section definitions.\n *\n * Each value under the \"sections\" field has two fields:\n * - offset: The offset into the original specified at which this section\n * begins to apply, defined as an object with a \"line\" and \"column\"\n * field.\n * - map: A source map definition. This source map could also be indexed,\n * but doesn't have to be.\n *\n * Instead of the \"map\" field, it's also possible to have a \"url\" field\n * specifying a URL to retrieve a source map from, but that's currently\n * unsupported.\n *\n * Here's an example source map, taken from the source map spec[0], but\n * modified to omit a section which uses the \"url\" field.\n *\n * {\n * version : 3,\n * file: \"app.js\",\n * sections: [{\n * offset: {line:100, column:10},\n * map: {\n * version : 3,\n * file: \"section.js\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AAAA,E;;ABCDE;\"\n * }\n * }],\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n */\nfunction IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sections = util.getArg(sourceMap, 'sections');\n\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n this._sources = new ArraySet();\n this._names = new ArraySet();\n\n var lastOffset = {\n line: -1,\n column: 0\n };\n this._sections = sections.map(function (s) {\n if (s.url) {\n // The url field will require support for asynchronicity.\n // See https://github.com/mozilla/source-map/issues/16\n throw new Error('Support for url field in sections not implemented.');\n }\n var offset = util.getArg(s, 'offset');\n var offsetLine = util.getArg(offset, 'line');\n var offsetColumn = util.getArg(offset, 'column');\n\n if (offsetLine < lastOffset.line ||\n (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n throw new Error('Section offsets must be ordered and non-overlapping.');\n }\n lastOffset = offset;\n\n return {\n generatedOffset: {\n // The offset fields are 0-based, but we use 1-based indices when\n // encoding/decoding from VLQ.\n generatedLine: offsetLine + 1,\n generatedColumn: offsetColumn + 1\n },\n consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)\n }\n });\n}\n\nIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nIndexedSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n get: function () {\n var sources = [];\n for (var i = 0; i < this._sections.length; i++) {\n for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n sources.push(this._sections[i].consumer.sources[j]);\n }\n }\n return sources;\n }\n});\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nIndexedSourceMapConsumer.prototype.originalPositionFor =\n function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n // Find the section containing the generated position we're trying to map\n // to an original position.\n var sectionIndex = binarySearch.search(needle, this._sections,\n function(needle, section) {\n var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n if (cmp) {\n return cmp;\n }\n\n return (needle.generatedColumn -\n section.generatedOffset.generatedColumn);\n });\n var section = this._sections[sectionIndex];\n\n if (!section) {\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n }\n\n return section.consumer.originalPositionFor({\n line: needle.generatedLine -\n (section.generatedOffset.generatedLine - 1),\n column: needle.generatedColumn -\n (section.generatedOffset.generatedLine === needle.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n bias: aArgs.bias\n });\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n return this._sections.every(function (s) {\n return s.consumer.hasContentsOfAllSources();\n });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nIndexedSourceMapConsumer.prototype.sourceContentFor =\n function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n var content = section.consumer.sourceContentFor(aSource, true);\n if (content) {\n return content;\n }\n }\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based. \n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nIndexedSourceMapConsumer.prototype.generatedPositionFor =\n function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n // Only consider this section if the requested source is in the list of\n // sources of the consumer.\n if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {\n continue;\n }\n var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n if (generatedPosition) {\n var ret = {\n line: generatedPosition.line +\n (section.generatedOffset.generatedLine - 1),\n column: generatedPosition.column +\n (section.generatedOffset.generatedLine === generatedPosition.line\n ? section.generatedOffset.generatedColumn - 1\n : 0)\n };\n return ret;\n }\n }\n\n return {\n line: null,\n column: null\n };\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nIndexedSourceMapConsumer.prototype._parseMappings =\n function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n this.__generatedMappings = [];\n this.__originalMappings = [];\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n var sectionMappings = section.consumer._generatedMappings;\n for (var j = 0; j < sectionMappings.length; j++) {\n var mapping = sectionMappings[j];\n\n var source = section.consumer._sources.at(mapping.source);\n source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);\n this._sources.add(source);\n source = this._sources.indexOf(source);\n\n var name = null;\n if (mapping.name) {\n name = section.consumer._names.at(mapping.name);\n this._names.add(name);\n name = this._names.indexOf(name);\n }\n\n // The mappings coming from the consumer for the section have\n // generated positions relative to the start of the section, so we\n // need to offset them to be relative to the start of the concatenated\n // generated file.\n var adjustedMapping = {\n source: source,\n generatedLine: mapping.generatedLine +\n (section.generatedOffset.generatedLine - 1),\n generatedColumn: mapping.generatedColumn +\n (section.generatedOffset.generatedLine === mapping.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: name\n };\n\n this.__generatedMappings.push(adjustedMapping);\n if (typeof adjustedMapping.originalLine === 'number') {\n this.__originalMappings.push(adjustedMapping);\n }\n }\n }\n\n quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n quickSort(this.__originalMappings, util.compareByOriginalPositions);\n };\n\nexports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-map-consumer.js\n// module id = 7\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nexports.GREATEST_LOWER_BOUND = 1;\nexports.LEAST_UPPER_BOUND = 2;\n\n/**\n * Recursive implementation of binary search.\n *\n * @param aLow Indices here and lower do not contain the needle.\n * @param aHigh Indices here and higher do not contain the needle.\n * @param aNeedle The element being searched for.\n * @param aHaystack The non-empty array being searched.\n * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n */\nfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n // This function terminates when one of the following is true:\n //\n // 1. We find the exact element we are looking for.\n //\n // 2. We did not find the exact element, but we can return the index of\n // the next-closest element.\n //\n // 3. We did not find the exact element, and there is no next-closest\n // element than the one we are searching for, so we return -1.\n var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n var cmp = aCompare(aNeedle, aHaystack[mid], true);\n if (cmp === 0) {\n // Found the element we are looking for.\n return mid;\n }\n else if (cmp > 0) {\n // Our needle is greater than aHaystack[mid].\n if (aHigh - mid > 1) {\n // The element is in the upper half.\n return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // The exact needle element was not found in this haystack. Determine if\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return aHigh < aHaystack.length ? aHigh : -1;\n } else {\n return mid;\n }\n }\n else {\n // Our needle is less than aHaystack[mid].\n if (mid - aLow > 1) {\n // The element is in the lower half.\n return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return mid;\n } else {\n return aLow < 0 ? -1 : aLow;\n }\n }\n}\n\n/**\n * This is an implementation of binary search which will always try and return\n * the index of the closest element if there is no exact hit. This is because\n * mappings between original and generated line/col pairs are single points,\n * and there is an implicit region between each of them, so a miss just means\n * that you aren't on the very start of a region.\n *\n * @param aNeedle The element you are looking for.\n * @param aHaystack The array that is being searched.\n * @param aCompare A function which takes the needle and an element in the\n * array and returns -1, 0, or 1 depending on whether the needle is less\n * than, equal to, or greater than the element, respectively.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n */\nexports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n if (aHaystack.length === 0) {\n return -1;\n }\n\n var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n if (index < 0) {\n return -1;\n }\n\n // We have found either the exact element, or the next-closest element than\n // the one we are searching for. However, there may be more than one such\n // element. Make sure we always return the smallest of these.\n while (index - 1 >= 0) {\n if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n break;\n }\n --index;\n }\n\n return index;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/binary-search.js\n// module id = 8\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n// It turns out that some (most?) JavaScript engines don't self-host\n// `Array.prototype.sort`. This makes sense because C++ will likely remain\n// faster than JS when doing raw CPU-intensive sorting. However, when using a\n// custom comparator function, calling back and forth between the VM's C++ and\n// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n// worse generated code for the comparator function than would be optimal. In\n// fact, when sorting with a comparator, these costs outweigh the benefits of\n// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n// a ~3500ms mean speed-up in `bench/bench.html`.\n\n/**\n * Swap the elements indexed by `x` and `y` in the array `ary`.\n *\n * @param {Array} ary\n * The array.\n * @param {Number} x\n * The index of the first item.\n * @param {Number} y\n * The index of the second item.\n */\nfunction swap(ary, x, y) {\n var temp = ary[x];\n ary[x] = ary[y];\n ary[y] = temp;\n}\n\n/**\n * Returns a random integer within the range `low .. high` inclusive.\n *\n * @param {Number} low\n * The lower bound on the range.\n * @param {Number} high\n * The upper bound on the range.\n */\nfunction randomIntInRange(low, high) {\n return Math.round(low + (Math.random() * (high - low)));\n}\n\n/**\n * The Quick Sort algorithm.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n * @param {Number} p\n * Start index of the array\n * @param {Number} r\n * End index of the array\n */\nfunction doQuickSort(ary, comparator, p, r) {\n // If our lower bound is less than our upper bound, we (1) partition the\n // array into two pieces and (2) recurse on each half. If it is not, this is\n // the empty array and our base case.\n\n if (p < r) {\n // (1) Partitioning.\n //\n // The partitioning chooses a pivot between `p` and `r` and moves all\n // elements that are less than or equal to the pivot to the before it, and\n // all the elements that are greater than it after it. The effect is that\n // once partition is done, the pivot is in the exact place it will be when\n // the array is put in sorted order, and it will not need to be moved\n // again. This runs in O(n) time.\n\n // Always choose a random pivot so that an input array which is reverse\n // sorted does not cause O(n^2) running time.\n var pivotIndex = randomIntInRange(p, r);\n var i = p - 1;\n\n swap(ary, pivotIndex, r);\n var pivot = ary[r];\n\n // Immediately after `j` is incremented in this loop, the following hold\n // true:\n //\n // * Every element in `ary[p .. i]` is less than or equal to the pivot.\n //\n // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n for (var j = p; j < r; j++) {\n if (comparator(ary[j], pivot) <= 0) {\n i += 1;\n swap(ary, i, j);\n }\n }\n\n swap(ary, i + 1, j);\n var q = i + 1;\n\n // (2) Recurse on each half.\n\n doQuickSort(ary, comparator, p, q - 1);\n doQuickSort(ary, comparator, q + 1, r);\n }\n}\n\n/**\n * Sort the given array in-place with the given comparator function.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n */\nexports.quickSort = function (ary, comparator) {\n doQuickSort(ary, comparator, 0, ary.length - 1);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/quick-sort.js\n// module id = 9\n// module chunks = 0","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;\nvar util = require('./util');\n\n// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n// operating systems these days (capturing the result).\nvar REGEX_NEWLINE = /(\\r?\\n)/;\n\n// Newline character code for charCodeAt() comparisons\nvar NEWLINE_CODE = 10;\n\n// Private symbol for identifying `SourceNode`s when multiple versions of\n// the source-map library are loaded. This MUST NOT CHANGE across\n// versions!\nvar isSourceNode = \"$$$isSourceNode$$$\";\n\n/**\n * SourceNodes provide a way to abstract over interpolating/concatenating\n * snippets of generated JavaScript source code while maintaining the line and\n * column information associated with the original source code.\n *\n * @param aLine The original line number.\n * @param aColumn The original column number.\n * @param aSource The original source's filename.\n * @param aChunks Optional. An array of strings which are snippets of\n * generated JS, or other SourceNodes.\n * @param aName The original identifier.\n */\nfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n this.children = [];\n this.sourceContents = {};\n this.line = aLine == null ? null : aLine;\n this.column = aColumn == null ? null : aColumn;\n this.source = aSource == null ? null : aSource;\n this.name = aName == null ? null : aName;\n this[isSourceNode] = true;\n if (aChunks != null) this.add(aChunks);\n}\n\n/**\n * Creates a SourceNode from generated code and a SourceMapConsumer.\n *\n * @param aGeneratedCode The generated code\n * @param aSourceMapConsumer The SourceMap for the generated code\n * @param aRelativePath Optional. The path that relative sources in the\n * SourceMapConsumer should be relative to.\n */\nSourceNode.fromStringWithSourceMap =\n function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n // The SourceNode we want to fill with the generated code\n // and the SourceMap\n var node = new SourceNode();\n\n // All even indices of this array are one line of the generated code,\n // while all odd indices are the newlines between two adjacent lines\n // (since `REGEX_NEWLINE` captures its match).\n // Processed fragments are accessed by calling `shiftNextLine`.\n var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n var remainingLinesIndex = 0;\n var shiftNextLine = function() {\n var lineContents = getNextLine();\n // The last line of a file might not have a newline.\n var newLine = getNextLine() || \"\";\n return lineContents + newLine;\n\n function getNextLine() {\n return remainingLinesIndex < remainingLines.length ?\n remainingLines[remainingLinesIndex++] : undefined;\n }\n };\n\n // We need to remember the position of \"remainingLines\"\n var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\n // The generate SourceNodes we need a code range.\n // To extract it current and last mapping is used.\n // Here we store the last mapping.\n var lastMapping = null;\n\n aSourceMapConsumer.eachMapping(function (mapping) {\n if (lastMapping !== null) {\n // We add the code from \"lastMapping\" to \"mapping\":\n // First check if there is a new line in between.\n if (lastGeneratedLine < mapping.generatedLine) {\n // Associate first line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n lastGeneratedLine++;\n lastGeneratedColumn = 0;\n // The remaining code is added without mapping\n } else {\n // There is no new line in between.\n // Associate the code between \"lastGeneratedColumn\" and\n // \"mapping.generatedColumn\" with \"lastMapping\"\n var nextLine = remainingLines[remainingLinesIndex] || '';\n var code = nextLine.substr(0, mapping.generatedColumn -\n lastGeneratedColumn);\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n lastGeneratedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n addMappingWithCode(lastMapping, code);\n // No more remaining code, continue\n lastMapping = mapping;\n return;\n }\n }\n // We add the generated code until the first mapping\n // to the SourceNode without any mapping.\n // Each line is added as separate string.\n while (lastGeneratedLine < mapping.generatedLine) {\n node.add(shiftNextLine());\n lastGeneratedLine++;\n }\n if (lastGeneratedColumn < mapping.generatedColumn) {\n var nextLine = remainingLines[remainingLinesIndex] || '';\n node.add(nextLine.substr(0, mapping.generatedColumn));\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n }\n lastMapping = mapping;\n }, this);\n // We have processed all mappings.\n if (remainingLinesIndex < remainingLines.length) {\n if (lastMapping) {\n // Associate the remaining code in the current line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n }\n // and add the remaining lines without any mapping\n node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n }\n\n // Copy sourcesContent into SourceNode\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aRelativePath != null) {\n sourceFile = util.join(aRelativePath, sourceFile);\n }\n node.setSourceContent(sourceFile, content);\n }\n });\n\n return node;\n\n function addMappingWithCode(mapping, code) {\n if (mapping === null || mapping.source === undefined) {\n node.add(code);\n } else {\n var source = aRelativePath\n ? util.join(aRelativePath, mapping.source)\n : mapping.source;\n node.add(new SourceNode(mapping.originalLine,\n mapping.originalColumn,\n source,\n code,\n mapping.name));\n }\n }\n };\n\n/**\n * Add a chunk of generated JS to this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.add = function SourceNode_add(aChunk) {\n if (Array.isArray(aChunk)) {\n aChunk.forEach(function (chunk) {\n this.add(chunk);\n }, this);\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n if (aChunk) {\n this.children.push(aChunk);\n }\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Add a chunk of generated JS to the beginning of this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n if (Array.isArray(aChunk)) {\n for (var i = aChunk.length-1; i >= 0; i--) {\n this.prepend(aChunk[i]);\n }\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n this.children.unshift(aChunk);\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Walk over the tree of JS snippets in this node and its children. The\n * walking function is called once for each snippet of JS and is passed that\n * snippet and the its original associated source's line/column location.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n var chunk;\n for (var i = 0, len = this.children.length; i < len; i++) {\n chunk = this.children[i];\n if (chunk[isSourceNode]) {\n chunk.walk(aFn);\n }\n else {\n if (chunk !== '') {\n aFn(chunk, { source: this.source,\n line: this.line,\n column: this.column,\n name: this.name });\n }\n }\n }\n};\n\n/**\n * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n * each of `this.children`.\n *\n * @param aSep The separator.\n */\nSourceNode.prototype.join = function SourceNode_join(aSep) {\n var newChildren;\n var i;\n var len = this.children.length;\n if (len > 0) {\n newChildren = [];\n for (i = 0; i < len-1; i++) {\n newChildren.push(this.children[i]);\n newChildren.push(aSep);\n }\n newChildren.push(this.children[i]);\n this.children = newChildren;\n }\n return this;\n};\n\n/**\n * Call String.prototype.replace on the very right-most source snippet. Useful\n * for trimming whitespace from the end of a source node, etc.\n *\n * @param aPattern The pattern to replace.\n * @param aReplacement The thing to replace the pattern with.\n */\nSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n var lastChild = this.children[this.children.length - 1];\n if (lastChild[isSourceNode]) {\n lastChild.replaceRight(aPattern, aReplacement);\n }\n else if (typeof lastChild === 'string') {\n this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n }\n else {\n this.children.push(''.replace(aPattern, aReplacement));\n }\n return this;\n};\n\n/**\n * Set the source content for a source file. This will be added to the SourceMapGenerator\n * in the sourcesContent field.\n *\n * @param aSourceFile The filename of the source file\n * @param aSourceContent The content of the source file\n */\nSourceNode.prototype.setSourceContent =\n function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n };\n\n/**\n * Walk over the tree of SourceNodes. The walking function is called for each\n * source file content and is passed the filename and source content.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walkSourceContents =\n function SourceNode_walkSourceContents(aFn) {\n for (var i = 0, len = this.children.length; i < len; i++) {\n if (this.children[i][isSourceNode]) {\n this.children[i].walkSourceContents(aFn);\n }\n }\n\n var sources = Object.keys(this.sourceContents);\n for (var i = 0, len = sources.length; i < len; i++) {\n aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n }\n };\n\n/**\n * Return the string representation of this source node. Walks over the tree\n * and concatenates all the various snippets together to one string.\n */\nSourceNode.prototype.toString = function SourceNode_toString() {\n var str = \"\";\n this.walk(function (chunk) {\n str += chunk;\n });\n return str;\n};\n\n/**\n * Returns the string representation of this source node along with a source\n * map.\n */\nSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n var generated = {\n code: \"\",\n line: 1,\n column: 0\n };\n var map = new SourceMapGenerator(aArgs);\n var sourceMappingActive = false;\n var lastOriginalSource = null;\n var lastOriginalLine = null;\n var lastOriginalColumn = null;\n var lastOriginalName = null;\n this.walk(function (chunk, original) {\n generated.code += chunk;\n if (original.source !== null\n && original.line !== null\n && original.column !== null) {\n if(lastOriginalSource !== original.source\n || lastOriginalLine !== original.line\n || lastOriginalColumn !== original.column\n || lastOriginalName !== original.name) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n lastOriginalSource = original.source;\n lastOriginalLine = original.line;\n lastOriginalColumn = original.column;\n lastOriginalName = original.name;\n sourceMappingActive = true;\n } else if (sourceMappingActive) {\n map.addMapping({\n generated: {\n line: generated.line,\n column: generated.column\n }\n });\n lastOriginalSource = null;\n sourceMappingActive = false;\n }\n for (var idx = 0, length = chunk.length; idx < length; idx++) {\n if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n generated.line++;\n generated.column = 0;\n // Mappings end at eol\n if (idx + 1 === length) {\n lastOriginalSource = null;\n sourceMappingActive = false;\n } else if (sourceMappingActive) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n } else {\n generated.column++;\n }\n }\n });\n this.walkSourceContents(function (sourceFile, sourceContent) {\n map.setSourceContent(sourceFile, sourceContent);\n });\n\n return { code: generated.code, map: map };\n};\n\nexports.SourceNode = SourceNode;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./lib/source-node.js\n// module id = 10\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/source-map/lib/array-set.js b/node_modules/source-map/lib/array-set.js new file mode 100644 index 0000000..fbd5c81 --- /dev/null +++ b/node_modules/source-map/lib/array-set.js @@ -0,0 +1,121 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var has = Object.prototype.hasOwnProperty; +var hasNativeMap = typeof Map !== "undefined"; + +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); +} + +/** + * Static method for creating ArraySet instances from an existing array. + */ +ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; +}; + +/** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ +ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; +}; + +/** + * Add the given string to this set. + * + * @param String aStr + */ +ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } +}; + +/** + * Is the given string a member of this set? + * + * @param String aStr + */ +ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } +}; + +/** + * What is the index of the given string in the array? + * + * @param String aStr + */ +ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); +}; + +/** + * What is the element at the given index? + * + * @param Number aIdx + */ +ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); +}; + +/** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ +ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); +}; + +exports.ArraySet = ArraySet; diff --git a/node_modules/source-map/lib/base64-vlq.js b/node_modules/source-map/lib/base64-vlq.js new file mode 100644 index 0000000..612b404 --- /dev/null +++ b/node_modules/source-map/lib/base64-vlq.js @@ -0,0 +1,140 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +var base64 = require('./base64'); + +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. +// +// Continuation +// | Sign +// | | +// V V +// 101011 + +var VLQ_BASE_SHIFT = 5; + +// binary: 100000 +var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + +// binary: 011111 +var VLQ_BASE_MASK = VLQ_BASE - 1; + +// binary: 100000 +var VLQ_CONTINUATION_BIT = VLQ_BASE; + +/** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ +function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; +} + +/** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ +function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; +} + +/** + * Returns the base 64 VLQ encoded value. + */ +exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; +}; + +/** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ +exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; +}; diff --git a/node_modules/source-map/lib/base64.js b/node_modules/source-map/lib/base64.js new file mode 100644 index 0000000..8aa86b3 --- /dev/null +++ b/node_modules/source-map/lib/base64.js @@ -0,0 +1,67 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + +/** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ +exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); +}; + +/** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ +exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; +}; diff --git a/node_modules/source-map/lib/binary-search.js b/node_modules/source-map/lib/binary-search.js new file mode 100644 index 0000000..010ac94 --- /dev/null +++ b/node_modules/source-map/lib/binary-search.js @@ -0,0 +1,111 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +exports.GREATEST_LOWER_BOUND = 1; +exports.LEAST_UPPER_BOUND = 2; + +/** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ +function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } +} + +/** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ +exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; +}; diff --git a/node_modules/source-map/lib/mapping-list.js b/node_modules/source-map/lib/mapping-list.js new file mode 100644 index 0000000..06d1274 --- /dev/null +++ b/node_modules/source-map/lib/mapping-list.js @@ -0,0 +1,79 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); + +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; +} + +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ +function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; +} + +/** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ +MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + +/** + * Add the given source mapping. + * + * @param Object aMapping + */ +MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } +}; + +/** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ +MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; +}; + +exports.MappingList = MappingList; diff --git a/node_modules/source-map/lib/quick-sort.js b/node_modules/source-map/lib/quick-sort.js new file mode 100644 index 0000000..6a7caad --- /dev/null +++ b/node_modules/source-map/lib/quick-sort.js @@ -0,0 +1,114 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +// It turns out that some (most?) JavaScript engines don't self-host +// `Array.prototype.sort`. This makes sense because C++ will likely remain +// faster than JS when doing raw CPU-intensive sorting. However, when using a +// custom comparator function, calling back and forth between the VM's C++ and +// JIT'd JS is rather slow *and* loses JIT type information, resulting in +// worse generated code for the comparator function than would be optimal. In +// fact, when sorting with a comparator, these costs outweigh the benefits of +// sorting in C++. By using our own JS-implemented Quick Sort (below), we get +// a ~3500ms mean speed-up in `bench/bench.html`. + +/** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ +function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; +} + +/** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ +function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); +} + +/** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ +function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } +} + +/** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ +exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); +}; diff --git a/node_modules/source-map/lib/source-map-consumer.js b/node_modules/source-map/lib/source-map-consumer.js new file mode 100644 index 0000000..7b99d1d --- /dev/null +++ b/node_modules/source-map/lib/source-map-consumer.js @@ -0,0 +1,1145 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var binarySearch = require('./binary-search'); +var ArraySet = require('./array-set').ArraySet; +var base64VLQ = require('./base64-vlq'); +var quickSort = require('./quick-sort').quickSort; + +function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); +} + +SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); +} + +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer.prototype._version = 3; + +// `__generatedMappings` and `__originalMappings` are arrays that hold the +// parsed mapping coordinates from the source map's "mappings" attribute. They +// are lazily instantiated, accessed via the `_generatedMappings` and +// `_originalMappings` getters respectively, and we only parse the mappings +// and create these arrays once queried for a source location. We jump through +// these hoops because there can be many thousands of mappings, and parsing +// them is expensive, so we only want to do it if we must. +// +// Each object in the arrays is of the form: +// +// { +// generatedLine: The line number in the generated code, +// generatedColumn: The column number in the generated code, +// source: The path to the original source file that generated this +// chunk of code, +// originalLine: The line number in the original source that +// corresponds to this chunk of generated code, +// originalColumn: The column number in the original source that +// corresponds to this chunk of generated code, +// name: The name of the original symbol which generated this chunk of +// code. +// } +// +// All properties except for `generatedLine` and `generatedColumn` can be +// `null`. +// +// `_generatedMappings` is ordered by the generated positions. +// +// `_originalMappings` is ordered by the original positions. + +SourceMapConsumer.prototype.__generatedMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } +}); + +SourceMapConsumer.prototype.__originalMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } +}); + +SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + +SourceMapConsumer.GENERATED_ORDER = 1; +SourceMapConsumer.ORIGINAL_ORDER = 2; + +SourceMapConsumer.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer.LEAST_UPPER_BOUND = 2; + +/** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ +SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + +/** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + +exports.SourceMapConsumer = SourceMapConsumer; + +/** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; +} + +BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + +/** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ +BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; +}; + +/** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ +BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + +/** + * The version of the source mapping spec that we are consuming. + */ +BasicSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } +}); + +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; +} + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + +/** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ +BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + +/** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ +BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + +exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); +} + +IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + +/** + * The version of the source mapping spec that we are consuming. + */ +IndexedSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } +}); + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + +exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; diff --git a/node_modules/source-map/lib/source-map-generator.js b/node_modules/source-map/lib/source-map-generator.js new file mode 100644 index 0000000..508bcfb --- /dev/null +++ b/node_modules/source-map/lib/source-map-generator.js @@ -0,0 +1,425 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var base64VLQ = require('./base64-vlq'); +var util = require('./util'); +var ArraySet = require('./array-set').ArraySet; +var MappingList = require('./mapping-list').MappingList; + +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; +} + +SourceMapGenerator.prototype._version = 3; + +/** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ +SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + +/** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ +SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + +/** + * Set the source content for a source file. + */ +SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + +/** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ +SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + +/** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ +SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + +/** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ +SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + +SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + +/** + * Externalize the source map. + */ +SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + +/** + * Render the source map being generated to a string. + */ +SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + +exports.SourceMapGenerator = SourceMapGenerator; diff --git a/node_modules/source-map/lib/source-node.js b/node_modules/source-map/lib/source-node.js new file mode 100644 index 0000000..8bcdbe3 --- /dev/null +++ b/node_modules/source-map/lib/source-node.js @@ -0,0 +1,413 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; +var util = require('./util'); + +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +var REGEX_NEWLINE = /(\r?\n)/; + +// Newline character code for charCodeAt() comparisons +var NEWLINE_CODE = 10; + +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +var isSourceNode = "$$$isSourceNode$$$"; + +/** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); +} + +/** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ +SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + +/** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } +}; + +/** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ +SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; +}; + +/** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ +SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; +}; + +/** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ +SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + +/** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + +/** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ +SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; +}; + +/** + * Returns the string representation of this source node along with a source + * map. + */ +SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; +}; + +exports.SourceNode = SourceNode; diff --git a/node_modules/source-map/lib/util.js b/node_modules/source-map/lib/util.js new file mode 100644 index 0000000..3ca92e5 --- /dev/null +++ b/node_modules/source-map/lib/util.js @@ -0,0 +1,488 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ +function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } +} +exports.getArg = getArg; + +var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; +var dataUrlRegexp = /^data:.+\,.+$/; + +function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; +} +exports.urlParse = urlParse; + +function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; +} +exports.urlGenerate = urlGenerate; + +/** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ +function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; +} +exports.normalize = normalize; + +/** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ +function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; +} +exports.join = join; + +exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); +}; + +/** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ +function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); +} +exports.relative = relative; + +var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); +}()); + +function identity (s) { + return s; +} + +/** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ +function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; +} +exports.toSetString = supportsNullProto ? identity : toSetString; + +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; +} +exports.fromSetString = supportsNullProto ? identity : fromSetString; + +function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; +} + +/** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByOriginalPositions = compareByOriginalPositions; + +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ +function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; +} + +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + +/** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ +function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); +} +exports.parseSourceMapInput = parseSourceMapInput; + +/** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ +function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); +} +exports.computeSourceURL = computeSourceURL; diff --git a/node_modules/source-map/package.json b/node_modules/source-map/package.json new file mode 100644 index 0000000..2466341 --- /dev/null +++ b/node_modules/source-map/package.json @@ -0,0 +1,73 @@ +{ + "name": "source-map", + "description": "Generates and consumes source maps", + "version": "0.6.1", + "homepage": "https://github.com/mozilla/source-map", + "author": "Nick Fitzgerald ", + "contributors": [ + "Tobias Koppers ", + "Duncan Beevers ", + "Stephen Crane ", + "Ryan Seddon ", + "Miles Elam ", + "Mihai Bazon ", + "Michael Ficarra ", + "Todd Wolfson ", + "Alexander Solovyov ", + "Felix Gnass ", + "Conrad Irwin ", + "usrbincc ", + "David Glasser ", + "Chase Douglas ", + "Evan Wallace ", + "Heather Arthur ", + "Hugh Kennedy ", + "David Glasser ", + "Simon Lydell ", + "Jmeas Smith ", + "Michael Z Goddard ", + "azu ", + "John Gozde ", + "Adam Kirkton ", + "Chris Montgomery ", + "J. Ryan Stinnett ", + "Jack Herrington ", + "Chris Truter ", + "Daniel Espeset ", + "Jamie Wong ", + "Eddy Bruël ", + "Hawken Rives ", + "Gilad Peleg ", + "djchie ", + "Gary Ye ", + "Nicolas Lalevée " + ], + "repository": { + "type": "git", + "url": "http://github.com/mozilla/source-map.git" + }, + "main": "./source-map.js", + "files": [ + "source-map.js", + "source-map.d.ts", + "lib/", + "dist/source-map.debug.js", + "dist/source-map.js", + "dist/source-map.min.js", + "dist/source-map.min.js.map" + ], + "engines": { + "node": ">=0.10.0" + }, + "license": "BSD-3-Clause", + "scripts": { + "test": "npm run build && node test/run-tests.js", + "build": "webpack --color", + "toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md" + }, + "devDependencies": { + "doctoc": "^0.15.0", + "webpack": "^1.12.0" + }, + "typings": "source-map" +} diff --git a/node_modules/source-map/source-map.d.ts b/node_modules/source-map/source-map.d.ts new file mode 100644 index 0000000..8f972b0 --- /dev/null +++ b/node_modules/source-map/source-map.d.ts @@ -0,0 +1,98 @@ +export interface StartOfSourceMap { + file?: string; + sourceRoot?: string; +} + +export interface RawSourceMap extends StartOfSourceMap { + version: string; + sources: string[]; + names: string[]; + sourcesContent?: string[]; + mappings: string; +} + +export interface Position { + line: number; + column: number; +} + +export interface LineRange extends Position { + lastColumn: number; +} + +export interface FindPosition extends Position { + // SourceMapConsumer.GREATEST_LOWER_BOUND or SourceMapConsumer.LEAST_UPPER_BOUND + bias?: number; +} + +export interface SourceFindPosition extends FindPosition { + source: string; +} + +export interface MappedPosition extends Position { + source: string; + name?: string; +} + +export interface MappingItem { + source: string; + generatedLine: number; + generatedColumn: number; + originalLine: number; + originalColumn: number; + name: string; +} + +export class SourceMapConsumer { + static GENERATED_ORDER: number; + static ORIGINAL_ORDER: number; + + static GREATEST_LOWER_BOUND: number; + static LEAST_UPPER_BOUND: number; + + constructor(rawSourceMap: RawSourceMap); + computeColumnSpans(): void; + originalPositionFor(generatedPosition: FindPosition): MappedPosition; + generatedPositionFor(originalPosition: SourceFindPosition): LineRange; + allGeneratedPositionsFor(originalPosition: MappedPosition): Position[]; + hasContentsOfAllSources(): boolean; + sourceContentFor(source: string, returnNullOnMissing?: boolean): string; + eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void; +} + +export interface Mapping { + generated: Position; + original: Position; + source: string; + name?: string; +} + +export class SourceMapGenerator { + constructor(startOfSourceMap?: StartOfSourceMap); + static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator; + addMapping(mapping: Mapping): void; + setSourceContent(sourceFile: string, sourceContent: string): void; + applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void; + toString(): string; +} + +export interface CodeWithSourceMap { + code: string; + map: SourceMapGenerator; +} + +export class SourceNode { + constructor(); + constructor(line: number, column: number, source: string); + constructor(line: number, column: number, source: string, chunk?: string, name?: string); + static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode; + add(chunk: string): void; + prepend(chunk: string): void; + setSourceContent(sourceFile: string, sourceContent: string): void; + walk(fn: (chunk: string, mapping: MappedPosition) => void): void; + walkSourceContents(fn: (file: string, content: string) => void): void; + join(sep: string): SourceNode; + replaceRight(pattern: string, replacement: string): SourceNode; + toString(): string; + toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap; +} diff --git a/node_modules/source-map/source-map.js b/node_modules/source-map/source-map.js new file mode 100644 index 0000000..bc88fe8 --- /dev/null +++ b/node_modules/source-map/source-map.js @@ -0,0 +1,8 @@ +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator; +exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer; +exports.SourceNode = require('./lib/source-node').SourceNode; diff --git a/node_modules/supports-color/browser.js b/node_modules/supports-color/browser.js new file mode 100644 index 0000000..62afa3a --- /dev/null +++ b/node_modules/supports-color/browser.js @@ -0,0 +1,5 @@ +'use strict'; +module.exports = { + stdout: false, + stderr: false +}; diff --git a/node_modules/supports-color/index.js b/node_modules/supports-color/index.js new file mode 100644 index 0000000..1704131 --- /dev/null +++ b/node_modules/supports-color/index.js @@ -0,0 +1,131 @@ +'use strict'; +const os = require('os'); +const hasFlag = require('has-flag'); + +const env = process.env; + +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = true; +} +if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } + + const min = forceColor ? 1 : 0; + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(process.versions.node.split('.')[0]) >= 8 && + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + if (env.TERM === 'dumb') { + return min; + } + + return min; +} + +function getSupportLevel(stream) { + const level = supportsColor(stream); + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) +}; diff --git a/node_modules/supports-color/license b/node_modules/supports-color/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/supports-color/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/supports-color/package.json b/node_modules/supports-color/package.json new file mode 100644 index 0000000..ad199f5 --- /dev/null +++ b/node_modules/supports-color/package.json @@ -0,0 +1,53 @@ +{ + "name": "supports-color", + "version": "5.5.0", + "description": "Detect whether a terminal supports color", + "license": "MIT", + "repository": "chalk/supports-color", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=4" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js", + "browser.js" + ], + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "ansi", + "styles", + "tty", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "support", + "supports", + "capability", + "detect", + "truecolor", + "16m" + ], + "dependencies": { + "has-flag": "^3.0.0" + }, + "devDependencies": { + "ava": "^0.25.0", + "import-fresh": "^2.0.0", + "xo": "^0.20.0" + }, + "browser": "browser.js" +} diff --git a/node_modules/supports-color/readme.md b/node_modules/supports-color/readme.md new file mode 100644 index 0000000..f6e4019 --- /dev/null +++ b/node_modules/supports-color/readme.md @@ -0,0 +1,66 @@ +# supports-color [![Build Status](https://travis-ci.org/chalk/supports-color.svg?branch=master)](https://travis-ci.org/chalk/supports-color) + +> Detect whether a terminal supports color + + +## Install + +``` +$ npm install supports-color +``` + + +## Usage + +```js +const supportsColor = require('supports-color'); + +if (supportsColor.stdout) { + console.log('Terminal stdout supports color'); +} + +if (supportsColor.stdout.has256) { + console.log('Terminal stdout supports 256 colors'); +} + +if (supportsColor.stderr.has16m) { + console.log('Terminal stderr supports 16 million colors (truecolor)'); +} +``` + + +## API + +Returns an `Object` with a `stdout` and `stderr` property for testing either streams. Each property is an `Object`, or `false` if color is not supported. + +The `stdout`/`stderr` objects specifies a level of support for color through a `.level` property and a corresponding flag: + +- `.level = 1` and `.hasBasic = true`: Basic color support (16 colors) +- `.level = 2` and `.has256 = true`: 256 color support +- `.level = 3` and `.has16m = true`: Truecolor support (16 million colors) + + +## Info + +It obeys the `--color` and `--no-color` CLI flags. + +Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, add the environment variable `FORCE_COLOR=1` to forcefully enable color or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks. + +Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively. + + +## Related + +- [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + + +## License + +MIT diff --git a/node_modules/tapable/LICENSE b/node_modules/tapable/LICENSE new file mode 100644 index 0000000..03c083c --- /dev/null +++ b/node_modules/tapable/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright JS Foundation and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/tapable/README.md b/node_modules/tapable/README.md new file mode 100644 index 0000000..1377197 --- /dev/null +++ b/node_modules/tapable/README.md @@ -0,0 +1,296 @@ +# Tapable + +The tapable package expose many Hook classes, which can be used to create hooks for plugins. + +``` javascript +const { + SyncHook, + SyncBailHook, + SyncWaterfallHook, + SyncLoopHook, + AsyncParallelHook, + AsyncParallelBailHook, + AsyncSeriesHook, + AsyncSeriesBailHook, + AsyncSeriesWaterfallHook + } = require("tapable"); +``` + +## Installation + +``` shell +npm install --save tapable +``` + +## Usage + +All Hook constructors take one optional argument, which is a list of argument names as strings. + +``` js +const hook = new SyncHook(["arg1", "arg2", "arg3"]); +``` + +The best practice is to expose all hooks of a class in a `hooks` property: + +``` js +class Car { + constructor() { + this.hooks = { + accelerate: new SyncHook(["newSpeed"]), + brake: new SyncHook(), + calculateRoutes: new AsyncParallelHook(["source", "target", "routesList"]) + }; + } + + /* ... */ +} +``` + +Other people can now use these hooks: + +``` js +const myCar = new Car(); + +// Use the tap method to add a consument +myCar.hooks.brake.tap("WarningLampPlugin", () => warningLamp.on()); +``` + +It's required to pass a name to identify the plugin/reason. + +You may receive arguments: + +``` js +myCar.hooks.accelerate.tap("LoggerPlugin", newSpeed => console.log(`Accelerating to ${newSpeed}`)); +``` + +For sync hooks, `tap` is the only valid method to add a plugin. Async hooks also support async plugins: + +``` js +myCar.hooks.calculateRoutes.tapPromise("GoogleMapsPlugin", (source, target, routesList) => { + // return a promise + return google.maps.findRoute(source, target).then(route => { + routesList.add(route); + }); +}); +myCar.hooks.calculateRoutes.tapAsync("BingMapsPlugin", (source, target, routesList, callback) => { + bing.findRoute(source, target, (err, route) => { + if(err) return callback(err); + routesList.add(route); + // call the callback + callback(); + }); +}); + +// You can still use sync plugins +myCar.hooks.calculateRoutes.tap("CachedRoutesPlugin", (source, target, routesList) => { + const cachedRoute = cache.get(source, target); + if(cachedRoute) + routesList.add(cachedRoute); +}) +``` +The class declaring these hooks need to call them: + +``` js +class Car { + /** + * You won't get returned value from SyncHook or AsyncParallelHook, + * to do that, use SyncWaterfallHook and AsyncSeriesWaterfallHook respectively + **/ + + setSpeed(newSpeed) { + // following call returns undefined even when you returned values + this.hooks.accelerate.call(newSpeed); + } + + useNavigationSystemPromise(source, target) { + const routesList = new List(); + return this.hooks.calculateRoutes.promise(source, target, routesList).then((res) => { + // res is undefined for AsyncParallelHook + return routesList.getRoutes(); + }); + } + + useNavigationSystemAsync(source, target, callback) { + const routesList = new List(); + this.hooks.calculateRoutes.callAsync(source, target, routesList, err => { + if(err) return callback(err); + callback(null, routesList.getRoutes()); + }); + } +} +``` + +The Hook will compile a method with the most efficient way of running your plugins. It generates code depending on: +* The number of registered plugins (none, one, many) +* The kind of registered plugins (sync, async, promise) +* The used call method (sync, async, promise) +* The number of arguments +* Whether interception is used + +This ensures fastest possible execution. + +## Hook types + +Each hook can be tapped with one or several functions. How they are executed depends on the hook type: + +* Basic hook (without “Waterfall”, “Bail” or “Loop” in its name). This hook simply calls every function it tapped in a row. + +* __Waterfall__. A waterfall hook also calls each tapped function in a row. Unlike the basic hook, it passes a return value from each function to the next function. + +* __Bail__. A bail hook allows exiting early. When any of the tapped function returns anything, the bail hook will stop executing the remaining ones. + +* __Loop__. When a plugin in a loop hook returns a non-undefined value the hook will restart from the first plugin. It will loop until all plugins return undefined. + +Additionally, hooks can be synchronous or asynchronous. To reflect this, there’re “Sync”, “AsyncSeries”, and “AsyncParallel” hook classes: + +* __Sync__. A sync hook can only be tapped with synchronous functions (using `myHook.tap()`). + +* __AsyncSeries__. An async-series hook can be tapped with synchronous, callback-based and promise-based functions (using `myHook.tap()`, `myHook.tapAsync()` and `myHook.tapPromise()`). They call each async method in a row. + +* __AsyncParallel__. An async-parallel hook can also be tapped with synchronous, callback-based and promise-based functions (using `myHook.tap()`, `myHook.tapAsync()` and `myHook.tapPromise()`). However, they run each async method in parallel. + +The hook type is reflected in its class name. E.g., `AsyncSeriesWaterfallHook` allows asynchronous functions and runs them in series, passing each function’s return value into the next function. + + +## Interception + +All Hooks offer an additional interception API: + +``` js +myCar.hooks.calculateRoutes.intercept({ + call: (source, target, routesList) => { + console.log("Starting to calculate routes"); + }, + register: (tapInfo) => { + // tapInfo = { type: "promise", name: "GoogleMapsPlugin", fn: ... } + console.log(`${tapInfo.name} is doing its job`); + return tapInfo; // may return a new tapInfo object + } +}) +``` + +**call**: `(...args) => void` Adding `call` to your interceptor will trigger when hooks are triggered. You have access to the hooks arguments. + +**tap**: `(tap: Tap) => void` Adding `tap` to your interceptor will trigger when a plugin taps into a hook. Provided is the `Tap` object. `Tap` object can't be changed. + +**loop**: `(...args) => void` Adding `loop` to your interceptor will trigger for each loop of a looping hook. + +**register**: `(tap: Tap) => Tap | undefined` Adding `register` to your interceptor will trigger for each added `Tap` and allows to modify it. + +## Context + +Plugins and interceptors can opt-in to access an optional `context` object, which can be used to pass arbitrary values to subsequent plugins and interceptors. + +``` js +myCar.hooks.accelerate.intercept({ + context: true, + tap: (context, tapInfo) => { + // tapInfo = { type: "sync", name: "NoisePlugin", fn: ... } + console.log(`${tapInfo.name} is doing it's job`); + + // `context` starts as an empty object if at least one plugin uses `context: true`. + // If no plugins use `context: true`, then `context` is undefined. + if (context) { + // Arbitrary properties can be added to `context`, which plugins can then access. + context.hasMuffler = true; + } + } +}); + +myCar.hooks.accelerate.tap({ + name: "NoisePlugin", + context: true +}, (context, newSpeed) => { + if (context && context.hasMuffler) { + console.log("Silence..."); + } else { + console.log("Vroom!"); + } +}); +``` + +## HookMap + +A HookMap is a helper class for a Map with Hooks + +``` js +const keyedHook = new HookMap(key => new SyncHook(["arg"])) +``` + +``` js +keyedHook.for("some-key").tap("MyPlugin", (arg) => { /* ... */ }); +keyedHook.for("some-key").tapAsync("MyPlugin", (arg, callback) => { /* ... */ }); +keyedHook.for("some-key").tapPromise("MyPlugin", (arg) => { /* ... */ }); +``` + +``` js +const hook = keyedHook.get("some-key"); +if(hook !== undefined) { + hook.callAsync("arg", err => { /* ... */ }); +} +``` + +## Hook/HookMap interface + +Public: + +``` ts +interface Hook { + tap: (name: string | Tap, fn: (context?, ...args) => Result) => void, + tapAsync: (name: string | Tap, fn: (context?, ...args, callback: (err, result: Result) => void) => void) => void, + tapPromise: (name: string | Tap, fn: (context?, ...args) => Promise) => void, + intercept: (interceptor: HookInterceptor) => void +} + +interface HookInterceptor { + call: (context?, ...args) => void, + loop: (context?, ...args) => void, + tap: (context?, tap: Tap) => void, + register: (tap: Tap) => Tap, + context: boolean +} + +interface HookMap { + for: (key: any) => Hook, + intercept: (interceptor: HookMapInterceptor) => void +} + +interface HookMapInterceptor { + factory: (key: any, hook: Hook) => Hook +} + +interface Tap { + name: string, + type: string + fn: Function, + stage: number, + context: boolean, + before?: string | Array +} +``` + +Protected (only for the class containing the hook): + +``` ts +interface Hook { + isUsed: () => boolean, + call: (...args) => Result, + promise: (...args) => Promise, + callAsync: (...args, callback: (err, result: Result) => void) => void, +} + +interface HookMap { + get: (key: any) => Hook | undefined, + for: (key: any) => Hook +} +``` + +## MultiHook + +A helper Hook-like class to redirect taps to multiple other hooks: + +``` js +const { MultiHook } = require("tapable"); + +this.hooks.allHooks = new MultiHook([this.hooks.hookA, this.hooks.hookB]); +``` diff --git a/node_modules/tapable/lib/AsyncParallelBailHook.js b/node_modules/tapable/lib/AsyncParallelBailHook.js new file mode 100644 index 0000000..45eca33 --- /dev/null +++ b/node_modules/tapable/lib/AsyncParallelBailHook.js @@ -0,0 +1,85 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +class AsyncParallelBailHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, onDone }) { + let code = ""; + code += `var _results = new Array(${this.options.taps.length});\n`; + code += "var _checkDone = function() {\n"; + code += "for(var i = 0; i < _results.length; i++) {\n"; + code += "var item = _results[i];\n"; + code += "if(item === undefined) return false;\n"; + code += "if(item.result !== undefined) {\n"; + code += onResult("item.result"); + code += "return true;\n"; + code += "}\n"; + code += "if(item.error) {\n"; + code += onError("item.error"); + code += "return true;\n"; + code += "}\n"; + code += "}\n"; + code += "return false;\n"; + code += "}\n"; + code += this.callTapsParallel({ + onError: (i, err, done, doneBreak) => { + let code = ""; + code += `if(${i} < _results.length && ((_results.length = ${i + + 1}), (_results[${i}] = { error: ${err} }), _checkDone())) {\n`; + code += doneBreak(true); + code += "} else {\n"; + code += done(); + code += "}\n"; + return code; + }, + onResult: (i, result, done, doneBreak) => { + let code = ""; + code += `if(${i} < _results.length && (${result} !== undefined && (_results.length = ${i + + 1}), (_results[${i}] = { result: ${result} }), _checkDone())) {\n`; + code += doneBreak(true); + code += "} else {\n"; + code += done(); + code += "}\n"; + return code; + }, + onTap: (i, run, done, doneBreak) => { + let code = ""; + if (i > 0) { + code += `if(${i} >= _results.length) {\n`; + code += done(); + code += "} else {\n"; + } + code += run(); + if (i > 0) code += "}\n"; + return code; + }, + onDone + }); + return code; + } +} + +const factory = new AsyncParallelBailHookCodeFactory(); + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function AsyncParallelBailHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = AsyncParallelBailHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; +} + +AsyncParallelBailHook.prototype = null; + +module.exports = AsyncParallelBailHook; diff --git a/node_modules/tapable/lib/AsyncParallelHook.js b/node_modules/tapable/lib/AsyncParallelHook.js new file mode 100644 index 0000000..b7a3631 --- /dev/null +++ b/node_modules/tapable/lib/AsyncParallelHook.js @@ -0,0 +1,37 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +class AsyncParallelHookCodeFactory extends HookCodeFactory { + content({ onError, onDone }) { + return this.callTapsParallel({ + onError: (i, err, done, doneBreak) => onError(err) + doneBreak(true), + onDone + }); + } +} + +const factory = new AsyncParallelHookCodeFactory(); + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function AsyncParallelHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = AsyncParallelHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; +} + +AsyncParallelHook.prototype = null; + +module.exports = AsyncParallelHook; diff --git a/node_modules/tapable/lib/AsyncSeriesBailHook.js b/node_modules/tapable/lib/AsyncSeriesBailHook.js new file mode 100644 index 0000000..5df66df --- /dev/null +++ b/node_modules/tapable/lib/AsyncSeriesBailHook.js @@ -0,0 +1,42 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +class AsyncSeriesBailHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, resultReturns, onDone }) { + return this.callTapsSeries({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onResult: (i, result, next) => + `if(${result} !== undefined) {\n${onResult( + result + )}\n} else {\n${next()}}\n`, + resultReturns, + onDone + }); + } +} + +const factory = new AsyncSeriesBailHookCodeFactory(); + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function AsyncSeriesBailHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = AsyncSeriesBailHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; +} + +AsyncSeriesBailHook.prototype = null; + +module.exports = AsyncSeriesBailHook; diff --git a/node_modules/tapable/lib/AsyncSeriesHook.js b/node_modules/tapable/lib/AsyncSeriesHook.js new file mode 100644 index 0000000..3edad00 --- /dev/null +++ b/node_modules/tapable/lib/AsyncSeriesHook.js @@ -0,0 +1,37 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +class AsyncSeriesHookCodeFactory extends HookCodeFactory { + content({ onError, onDone }) { + return this.callTapsSeries({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onDone + }); + } +} + +const factory = new AsyncSeriesHookCodeFactory(); + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function AsyncSeriesHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = AsyncSeriesHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; +} + +AsyncSeriesHook.prototype = null; + +module.exports = AsyncSeriesHook; diff --git a/node_modules/tapable/lib/AsyncSeriesLoopHook.js b/node_modules/tapable/lib/AsyncSeriesLoopHook.js new file mode 100644 index 0000000..fb5f067 --- /dev/null +++ b/node_modules/tapable/lib/AsyncSeriesLoopHook.js @@ -0,0 +1,37 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +class AsyncSeriesLoopHookCodeFactory extends HookCodeFactory { + content({ onError, onDone }) { + return this.callTapsLooping({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onDone + }); + } +} + +const factory = new AsyncSeriesLoopHookCodeFactory(); + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function AsyncSeriesLoopHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = AsyncSeriesLoopHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; +} + +AsyncSeriesLoopHook.prototype = null; + +module.exports = AsyncSeriesLoopHook; diff --git a/node_modules/tapable/lib/AsyncSeriesWaterfallHook.js b/node_modules/tapable/lib/AsyncSeriesWaterfallHook.js new file mode 100644 index 0000000..910b536 --- /dev/null +++ b/node_modules/tapable/lib/AsyncSeriesWaterfallHook.js @@ -0,0 +1,47 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +class AsyncSeriesWaterfallHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, onDone }) { + return this.callTapsSeries({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onResult: (i, result, next) => { + let code = ""; + code += `if(${result} !== undefined) {\n`; + code += `${this._args[0]} = ${result};\n`; + code += `}\n`; + code += next(); + return code; + }, + onDone: () => onResult(this._args[0]) + }); + } +} + +const factory = new AsyncSeriesWaterfallHookCodeFactory(); + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function AsyncSeriesWaterfallHook(args = [], name = undefined) { + if (args.length < 1) + throw new Error("Waterfall hooks must have at least one argument"); + const hook = new Hook(args, name); + hook.constructor = AsyncSeriesWaterfallHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; +} + +AsyncSeriesWaterfallHook.prototype = null; + +module.exports = AsyncSeriesWaterfallHook; diff --git a/node_modules/tapable/lib/Hook.js b/node_modules/tapable/lib/Hook.js new file mode 100644 index 0000000..db04426 --- /dev/null +++ b/node_modules/tapable/lib/Hook.js @@ -0,0 +1,175 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const util = require("util"); + +const deprecateContext = util.deprecate(() => {}, +"Hook.context is deprecated and will be removed"); + +const CALL_DELEGATE = function(...args) { + this.call = this._createCall("sync"); + return this.call(...args); +}; +const CALL_ASYNC_DELEGATE = function(...args) { + this.callAsync = this._createCall("async"); + return this.callAsync(...args); +}; +const PROMISE_DELEGATE = function(...args) { + this.promise = this._createCall("promise"); + return this.promise(...args); +}; + +class Hook { + constructor(args = [], name = undefined) { + this._args = args; + this.name = name; + this.taps = []; + this.interceptors = []; + this._call = CALL_DELEGATE; + this.call = CALL_DELEGATE; + this._callAsync = CALL_ASYNC_DELEGATE; + this.callAsync = CALL_ASYNC_DELEGATE; + this._promise = PROMISE_DELEGATE; + this.promise = PROMISE_DELEGATE; + this._x = undefined; + + this.compile = this.compile; + this.tap = this.tap; + this.tapAsync = this.tapAsync; + this.tapPromise = this.tapPromise; + } + + compile(options) { + throw new Error("Abstract: should be overridden"); + } + + _createCall(type) { + return this.compile({ + taps: this.taps, + interceptors: this.interceptors, + args: this._args, + type: type + }); + } + + _tap(type, options, fn) { + if (typeof options === "string") { + options = { + name: options.trim() + }; + } else if (typeof options !== "object" || options === null) { + throw new Error("Invalid tap options"); + } + if (typeof options.name !== "string" || options.name === "") { + throw new Error("Missing name for tap"); + } + if (typeof options.context !== "undefined") { + deprecateContext(); + } + options = Object.assign({ type, fn }, options); + options = this._runRegisterInterceptors(options); + this._insert(options); + } + + tap(options, fn) { + this._tap("sync", options, fn); + } + + tapAsync(options, fn) { + this._tap("async", options, fn); + } + + tapPromise(options, fn) { + this._tap("promise", options, fn); + } + + _runRegisterInterceptors(options) { + for (const interceptor of this.interceptors) { + if (interceptor.register) { + const newOptions = interceptor.register(options); + if (newOptions !== undefined) { + options = newOptions; + } + } + } + return options; + } + + withOptions(options) { + const mergeOptions = opt => + Object.assign({}, options, typeof opt === "string" ? { name: opt } : opt); + + return { + name: this.name, + tap: (opt, fn) => this.tap(mergeOptions(opt), fn), + tapAsync: (opt, fn) => this.tapAsync(mergeOptions(opt), fn), + tapPromise: (opt, fn) => this.tapPromise(mergeOptions(opt), fn), + intercept: interceptor => this.intercept(interceptor), + isUsed: () => this.isUsed(), + withOptions: opt => this.withOptions(mergeOptions(opt)) + }; + } + + isUsed() { + return this.taps.length > 0 || this.interceptors.length > 0; + } + + intercept(interceptor) { + this._resetCompilation(); + this.interceptors.push(Object.assign({}, interceptor)); + if (interceptor.register) { + for (let i = 0; i < this.taps.length; i++) { + this.taps[i] = interceptor.register(this.taps[i]); + } + } + } + + _resetCompilation() { + this.call = this._call; + this.callAsync = this._callAsync; + this.promise = this._promise; + } + + _insert(item) { + this._resetCompilation(); + let before; + if (typeof item.before === "string") { + before = new Set([item.before]); + } else if (Array.isArray(item.before)) { + before = new Set(item.before); + } + let stage = 0; + if (typeof item.stage === "number") { + stage = item.stage; + } + let i = this.taps.length; + while (i > 0) { + i--; + const x = this.taps[i]; + this.taps[i + 1] = x; + const xStage = x.stage || 0; + if (before) { + if (before.has(x.name)) { + before.delete(x.name); + continue; + } + if (before.size > 0) { + continue; + } + } + if (xStage > stage) { + continue; + } + i++; + break; + } + this.taps[i] = item; + } +} + +Object.setPrototypeOf(Hook.prototype, null); + +module.exports = Hook; diff --git a/node_modules/tapable/lib/HookCodeFactory.js b/node_modules/tapable/lib/HookCodeFactory.js new file mode 100644 index 0000000..c9f5340 --- /dev/null +++ b/node_modules/tapable/lib/HookCodeFactory.js @@ -0,0 +1,468 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +class HookCodeFactory { + constructor(config) { + this.config = config; + this.options = undefined; + this._args = undefined; + } + + create(options) { + this.init(options); + let fn; + switch (this.options.type) { + case "sync": + fn = new Function( + this.args(), + '"use strict";\n' + + this.header() + + this.contentWithInterceptors({ + onError: err => `throw ${err};\n`, + onResult: result => `return ${result};\n`, + resultReturns: true, + onDone: () => "", + rethrowIfPossible: true + }) + ); + break; + case "async": + fn = new Function( + this.args({ + after: "_callback" + }), + '"use strict";\n' + + this.header() + + this.contentWithInterceptors({ + onError: err => `_callback(${err});\n`, + onResult: result => `_callback(null, ${result});\n`, + onDone: () => "_callback();\n" + }) + ); + break; + case "promise": + let errorHelperUsed = false; + const content = this.contentWithInterceptors({ + onError: err => { + errorHelperUsed = true; + return `_error(${err});\n`; + }, + onResult: result => `_resolve(${result});\n`, + onDone: () => "_resolve();\n" + }); + let code = ""; + code += '"use strict";\n'; + code += this.header(); + code += "return new Promise((function(_resolve, _reject) {\n"; + if (errorHelperUsed) { + code += "var _sync = true;\n"; + code += "function _error(_err) {\n"; + code += "if(_sync)\n"; + code += + "_resolve(Promise.resolve().then((function() { throw _err; })));\n"; + code += "else\n"; + code += "_reject(_err);\n"; + code += "};\n"; + } + code += content; + if (errorHelperUsed) { + code += "_sync = false;\n"; + } + code += "}));\n"; + fn = new Function(this.args(), code); + break; + } + this.deinit(); + return fn; + } + + setup(instance, options) { + instance._x = options.taps.map(t => t.fn); + } + + /** + * @param {{ type: "sync" | "promise" | "async", taps: Array, interceptors: Array }} options + */ + init(options) { + this.options = options; + this._args = options.args.slice(); + } + + deinit() { + this.options = undefined; + this._args = undefined; + } + + contentWithInterceptors(options) { + if (this.options.interceptors.length > 0) { + const onError = options.onError; + const onResult = options.onResult; + const onDone = options.onDone; + let code = ""; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.call) { + code += `${this.getInterceptor(i)}.call(${this.args({ + before: interceptor.context ? "_context" : undefined + })});\n`; + } + } + code += this.content( + Object.assign(options, { + onError: + onError && + (err => { + let code = ""; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.error) { + code += `${this.getInterceptor(i)}.error(${err});\n`; + } + } + code += onError(err); + return code; + }), + onResult: + onResult && + (result => { + let code = ""; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.result) { + code += `${this.getInterceptor(i)}.result(${result});\n`; + } + } + code += onResult(result); + return code; + }), + onDone: + onDone && + (() => { + let code = ""; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.done) { + code += `${this.getInterceptor(i)}.done();\n`; + } + } + code += onDone(); + return code; + }) + }) + ); + return code; + } else { + return this.content(options); + } + } + + header() { + let code = ""; + if (this.needContext()) { + code += "var _context = {};\n"; + } else { + code += "var _context;\n"; + } + code += "var _x = this._x;\n"; + if (this.options.interceptors.length > 0) { + code += "var _taps = this.taps;\n"; + code += "var _interceptors = this.interceptors;\n"; + } + return code; + } + + needContext() { + for (const tap of this.options.taps) if (tap.context) return true; + return false; + } + + callTap(tapIndex, { onError, onResult, onDone, rethrowIfPossible }) { + let code = ""; + let hasTapCached = false; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.tap) { + if (!hasTapCached) { + code += `var _tap${tapIndex} = ${this.getTap(tapIndex)};\n`; + hasTapCached = true; + } + code += `${this.getInterceptor(i)}.tap(${ + interceptor.context ? "_context, " : "" + }_tap${tapIndex});\n`; + } + } + code += `var _fn${tapIndex} = ${this.getTapFn(tapIndex)};\n`; + const tap = this.options.taps[tapIndex]; + switch (tap.type) { + case "sync": + if (!rethrowIfPossible) { + code += `var _hasError${tapIndex} = false;\n`; + code += "try {\n"; + } + if (onResult) { + code += `var _result${tapIndex} = _fn${tapIndex}(${this.args({ + before: tap.context ? "_context" : undefined + })});\n`; + } else { + code += `_fn${tapIndex}(${this.args({ + before: tap.context ? "_context" : undefined + })});\n`; + } + if (!rethrowIfPossible) { + code += "} catch(_err) {\n"; + code += `_hasError${tapIndex} = true;\n`; + code += onError("_err"); + code += "}\n"; + code += `if(!_hasError${tapIndex}) {\n`; + } + if (onResult) { + code += onResult(`_result${tapIndex}`); + } + if (onDone) { + code += onDone(); + } + if (!rethrowIfPossible) { + code += "}\n"; + } + break; + case "async": + let cbCode = ""; + if (onResult) + cbCode += `(function(_err${tapIndex}, _result${tapIndex}) {\n`; + else cbCode += `(function(_err${tapIndex}) {\n`; + cbCode += `if(_err${tapIndex}) {\n`; + cbCode += onError(`_err${tapIndex}`); + cbCode += "} else {\n"; + if (onResult) { + cbCode += onResult(`_result${tapIndex}`); + } + if (onDone) { + cbCode += onDone(); + } + cbCode += "}\n"; + cbCode += "})"; + code += `_fn${tapIndex}(${this.args({ + before: tap.context ? "_context" : undefined, + after: cbCode + })});\n`; + break; + case "promise": + code += `var _hasResult${tapIndex} = false;\n`; + code += `var _promise${tapIndex} = _fn${tapIndex}(${this.args({ + before: tap.context ? "_context" : undefined + })});\n`; + code += `if (!_promise${tapIndex} || !_promise${tapIndex}.then)\n`; + code += ` throw new Error('Tap function (tapPromise) did not return promise (returned ' + _promise${tapIndex} + ')');\n`; + code += `_promise${tapIndex}.then((function(_result${tapIndex}) {\n`; + code += `_hasResult${tapIndex} = true;\n`; + if (onResult) { + code += onResult(`_result${tapIndex}`); + } + if (onDone) { + code += onDone(); + } + code += `}), function(_err${tapIndex}) {\n`; + code += `if(_hasResult${tapIndex}) throw _err${tapIndex};\n`; + code += onError(`_err${tapIndex}`); + code += "});\n"; + break; + } + return code; + } + + callTapsSeries({ + onError, + onResult, + resultReturns, + onDone, + doneReturns, + rethrowIfPossible + }) { + if (this.options.taps.length === 0) return onDone(); + const firstAsync = this.options.taps.findIndex(t => t.type !== "sync"); + const somethingReturns = resultReturns || doneReturns; + let code = ""; + let current = onDone; + let unrollCounter = 0; + for (let j = this.options.taps.length - 1; j >= 0; j--) { + const i = j; + const unroll = + current !== onDone && + (this.options.taps[i].type !== "sync" || unrollCounter++ > 20); + if (unroll) { + unrollCounter = 0; + code += `function _next${i}() {\n`; + code += current(); + code += `}\n`; + current = () => `${somethingReturns ? "return " : ""}_next${i}();\n`; + } + const done = current; + const doneBreak = skipDone => { + if (skipDone) return ""; + return onDone(); + }; + const content = this.callTap(i, { + onError: error => onError(i, error, done, doneBreak), + onResult: + onResult && + (result => { + return onResult(i, result, done, doneBreak); + }), + onDone: !onResult && done, + rethrowIfPossible: + rethrowIfPossible && (firstAsync < 0 || i < firstAsync) + }); + current = () => content; + } + code += current(); + return code; + } + + callTapsLooping({ onError, onDone, rethrowIfPossible }) { + if (this.options.taps.length === 0) return onDone(); + const syncOnly = this.options.taps.every(t => t.type === "sync"); + let code = ""; + if (!syncOnly) { + code += "var _looper = (function() {\n"; + code += "var _loopAsync = false;\n"; + } + code += "var _loop;\n"; + code += "do {\n"; + code += "_loop = false;\n"; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.loop) { + code += `${this.getInterceptor(i)}.loop(${this.args({ + before: interceptor.context ? "_context" : undefined + })});\n`; + } + } + code += this.callTapsSeries({ + onError, + onResult: (i, result, next, doneBreak) => { + let code = ""; + code += `if(${result} !== undefined) {\n`; + code += "_loop = true;\n"; + if (!syncOnly) code += "if(_loopAsync) _looper();\n"; + code += doneBreak(true); + code += `} else {\n`; + code += next(); + code += `}\n`; + return code; + }, + onDone: + onDone && + (() => { + let code = ""; + code += "if(!_loop) {\n"; + code += onDone(); + code += "}\n"; + return code; + }), + rethrowIfPossible: rethrowIfPossible && syncOnly + }); + code += "} while(_loop);\n"; + if (!syncOnly) { + code += "_loopAsync = true;\n"; + code += "});\n"; + code += "_looper();\n"; + } + return code; + } + + callTapsParallel({ + onError, + onResult, + onDone, + rethrowIfPossible, + onTap = (i, run) => run() + }) { + if (this.options.taps.length <= 1) { + return this.callTapsSeries({ + onError, + onResult, + onDone, + rethrowIfPossible + }); + } + let code = ""; + code += "do {\n"; + code += `var _counter = ${this.options.taps.length};\n`; + if (onDone) { + code += "var _done = (function() {\n"; + code += onDone(); + code += "});\n"; + } + for (let i = 0; i < this.options.taps.length; i++) { + const done = () => { + if (onDone) return "if(--_counter === 0) _done();\n"; + else return "--_counter;"; + }; + const doneBreak = skipDone => { + if (skipDone || !onDone) return "_counter = 0;\n"; + else return "_counter = 0;\n_done();\n"; + }; + code += "if(_counter <= 0) break;\n"; + code += onTap( + i, + () => + this.callTap(i, { + onError: error => { + let code = ""; + code += "if(_counter > 0) {\n"; + code += onError(i, error, done, doneBreak); + code += "}\n"; + return code; + }, + onResult: + onResult && + (result => { + let code = ""; + code += "if(_counter > 0) {\n"; + code += onResult(i, result, done, doneBreak); + code += "}\n"; + return code; + }), + onDone: + !onResult && + (() => { + return done(); + }), + rethrowIfPossible + }), + done, + doneBreak + ); + } + code += "} while(false);\n"; + return code; + } + + args({ before, after } = {}) { + let allArgs = this._args; + if (before) allArgs = [before].concat(allArgs); + if (after) allArgs = allArgs.concat(after); + if (allArgs.length === 0) { + return ""; + } else { + return allArgs.join(", "); + } + } + + getTapFn(idx) { + return `_x[${idx}]`; + } + + getTap(idx) { + return `_taps[${idx}]`; + } + + getInterceptor(idx) { + return `_interceptors[${idx}]`; + } +} + +module.exports = HookCodeFactory; diff --git a/node_modules/tapable/lib/HookMap.js b/node_modules/tapable/lib/HookMap.js new file mode 100644 index 0000000..129ad6a --- /dev/null +++ b/node_modules/tapable/lib/HookMap.js @@ -0,0 +1,61 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const util = require("util"); + +const defaultFactory = (key, hook) => hook; + +class HookMap { + constructor(factory, name = undefined) { + this._map = new Map(); + this.name = name; + this._factory = factory; + this._interceptors = []; + } + + get(key) { + return this._map.get(key); + } + + for(key) { + const hook = this.get(key); + if (hook !== undefined) { + return hook; + } + let newHook = this._factory(key); + const interceptors = this._interceptors; + for (let i = 0; i < interceptors.length; i++) { + newHook = interceptors[i].factory(key, newHook); + } + this._map.set(key, newHook); + return newHook; + } + + intercept(interceptor) { + this._interceptors.push( + Object.assign( + { + factory: defaultFactory + }, + interceptor + ) + ); + } +} + +HookMap.prototype.tap = util.deprecate(function(key, options, fn) { + return this.for(key).tap(options, fn); +}, "HookMap#tap(key,…) is deprecated. Use HookMap#for(key).tap(…) instead."); + +HookMap.prototype.tapAsync = util.deprecate(function(key, options, fn) { + return this.for(key).tapAsync(options, fn); +}, "HookMap#tapAsync(key,…) is deprecated. Use HookMap#for(key).tapAsync(…) instead."); + +HookMap.prototype.tapPromise = util.deprecate(function(key, options, fn) { + return this.for(key).tapPromise(options, fn); +}, "HookMap#tapPromise(key,…) is deprecated. Use HookMap#for(key).tapPromise(…) instead."); + +module.exports = HookMap; diff --git a/node_modules/tapable/lib/MultiHook.js b/node_modules/tapable/lib/MultiHook.js new file mode 100644 index 0000000..e4fc2ce --- /dev/null +++ b/node_modules/tapable/lib/MultiHook.js @@ -0,0 +1,54 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); + +class MultiHook { + constructor(hooks, name = undefined) { + this.hooks = hooks; + this.name = name; + } + + tap(options, fn) { + for (const hook of this.hooks) { + hook.tap(options, fn); + } + } + + tapAsync(options, fn) { + for (const hook of this.hooks) { + hook.tapAsync(options, fn); + } + } + + tapPromise(options, fn) { + for (const hook of this.hooks) { + hook.tapPromise(options, fn); + } + } + + isUsed() { + for (const hook of this.hooks) { + if (hook.isUsed()) return true; + } + return false; + } + + intercept(interceptor) { + for (const hook of this.hooks) { + hook.intercept(interceptor); + } + } + + withOptions(options) { + return new MultiHook( + this.hooks.map(h => h.withOptions(options)), + this.name + ); + } +} + +module.exports = MultiHook; diff --git a/node_modules/tapable/lib/SyncBailHook.js b/node_modules/tapable/lib/SyncBailHook.js new file mode 100644 index 0000000..bdd5b45 --- /dev/null +++ b/node_modules/tapable/lib/SyncBailHook.js @@ -0,0 +1,51 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +class SyncBailHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, resultReturns, onDone, rethrowIfPossible }) { + return this.callTapsSeries({ + onError: (i, err) => onError(err), + onResult: (i, result, next) => + `if(${result} !== undefined) {\n${onResult( + result + )};\n} else {\n${next()}}\n`, + resultReturns, + onDone, + rethrowIfPossible + }); + } +} + +const factory = new SyncBailHookCodeFactory(); + +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncBailHook"); +}; + +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncBailHook"); +}; + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function SyncBailHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = SyncBailHook; + hook.tapAsync = TAP_ASYNC; + hook.tapPromise = TAP_PROMISE; + hook.compile = COMPILE; + return hook; +} + +SyncBailHook.prototype = null; + +module.exports = SyncBailHook; diff --git a/node_modules/tapable/lib/SyncHook.js b/node_modules/tapable/lib/SyncHook.js new file mode 100644 index 0000000..e2512be --- /dev/null +++ b/node_modules/tapable/lib/SyncHook.js @@ -0,0 +1,46 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +class SyncHookCodeFactory extends HookCodeFactory { + content({ onError, onDone, rethrowIfPossible }) { + return this.callTapsSeries({ + onError: (i, err) => onError(err), + onDone, + rethrowIfPossible + }); + } +} + +const factory = new SyncHookCodeFactory(); + +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncHook"); +}; + +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncHook"); +}; + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function SyncHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = SyncHook; + hook.tapAsync = TAP_ASYNC; + hook.tapPromise = TAP_PROMISE; + hook.compile = COMPILE; + return hook; +} + +SyncHook.prototype = null; + +module.exports = SyncHook; diff --git a/node_modules/tapable/lib/SyncLoopHook.js b/node_modules/tapable/lib/SyncLoopHook.js new file mode 100644 index 0000000..be0e4fd --- /dev/null +++ b/node_modules/tapable/lib/SyncLoopHook.js @@ -0,0 +1,46 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +class SyncLoopHookCodeFactory extends HookCodeFactory { + content({ onError, onDone, rethrowIfPossible }) { + return this.callTapsLooping({ + onError: (i, err) => onError(err), + onDone, + rethrowIfPossible + }); + } +} + +const factory = new SyncLoopHookCodeFactory(); + +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncLoopHook"); +}; + +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncLoopHook"); +}; + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function SyncLoopHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = SyncLoopHook; + hook.tapAsync = TAP_ASYNC; + hook.tapPromise = TAP_PROMISE; + hook.compile = COMPILE; + return hook; +} + +SyncLoopHook.prototype = null; + +module.exports = SyncLoopHook; diff --git a/node_modules/tapable/lib/SyncWaterfallHook.js b/node_modules/tapable/lib/SyncWaterfallHook.js new file mode 100644 index 0000000..c878b7f --- /dev/null +++ b/node_modules/tapable/lib/SyncWaterfallHook.js @@ -0,0 +1,57 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +class SyncWaterfallHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, resultReturns, rethrowIfPossible }) { + return this.callTapsSeries({ + onError: (i, err) => onError(err), + onResult: (i, result, next) => { + let code = ""; + code += `if(${result} !== undefined) {\n`; + code += `${this._args[0]} = ${result};\n`; + code += `}\n`; + code += next(); + return code; + }, + onDone: () => onResult(this._args[0]), + doneReturns: resultReturns, + rethrowIfPossible + }); + } +} + +const factory = new SyncWaterfallHookCodeFactory(); + +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncWaterfallHook"); +}; + +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncWaterfallHook"); +}; + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function SyncWaterfallHook(args = [], name = undefined) { + if (args.length < 1) + throw new Error("Waterfall hooks must have at least one argument"); + const hook = new Hook(args, name); + hook.constructor = SyncWaterfallHook; + hook.tapAsync = TAP_ASYNC; + hook.tapPromise = TAP_PROMISE; + hook.compile = COMPILE; + return hook; +} + +SyncWaterfallHook.prototype = null; + +module.exports = SyncWaterfallHook; diff --git a/node_modules/tapable/lib/index.js b/node_modules/tapable/lib/index.js new file mode 100644 index 0000000..0a94a53 --- /dev/null +++ b/node_modules/tapable/lib/index.js @@ -0,0 +1,19 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +exports.__esModule = true; +exports.SyncHook = require("./SyncHook"); +exports.SyncBailHook = require("./SyncBailHook"); +exports.SyncWaterfallHook = require("./SyncWaterfallHook"); +exports.SyncLoopHook = require("./SyncLoopHook"); +exports.AsyncParallelHook = require("./AsyncParallelHook"); +exports.AsyncParallelBailHook = require("./AsyncParallelBailHook"); +exports.AsyncSeriesHook = require("./AsyncSeriesHook"); +exports.AsyncSeriesBailHook = require("./AsyncSeriesBailHook"); +exports.AsyncSeriesLoopHook = require("./AsyncSeriesLoopHook"); +exports.AsyncSeriesWaterfallHook = require("./AsyncSeriesWaterfallHook"); +exports.HookMap = require("./HookMap"); +exports.MultiHook = require("./MultiHook"); diff --git a/node_modules/tapable/lib/util-browser.js b/node_modules/tapable/lib/util-browser.js new file mode 100644 index 0000000..ee4fb9a --- /dev/null +++ b/node_modules/tapable/lib/util-browser.js @@ -0,0 +1,16 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +exports.deprecate = (fn, msg) => { + let once = true; + return function() { + if (once) { + console.warn("DeprecationWarning: " + msg); + once = false; + } + return fn.apply(this, arguments); + }; +}; diff --git a/node_modules/tapable/package.json b/node_modules/tapable/package.json new file mode 100644 index 0000000..3c13120 --- /dev/null +++ b/node_modules/tapable/package.json @@ -0,0 +1,44 @@ +{ + "name": "tapable", + "version": "2.2.1", + "author": "Tobias Koppers @sokra", + "description": "Just a little module for plugins.", + "license": "MIT", + "homepage": "https://github.com/webpack/tapable", + "repository": { + "type": "git", + "url": "http://github.com/webpack/tapable.git" + }, + "devDependencies": { + "@babel/core": "^7.4.4", + "@babel/preset-env": "^7.4.4", + "babel-jest": "^24.8.0", + "codecov": "^3.5.0", + "jest": "^24.8.0", + "prettier": "^1.17.1" + }, + "engines": { + "node": ">=6" + }, + "files": [ + "lib", + "!lib/__tests__", + "tapable.d.ts" + ], + "main": "lib/index.js", + "types": "./tapable.d.ts", + "browser": { + "util": "./lib/util-browser.js" + }, + "scripts": { + "test": "jest", + "travis": "yarn pretty-lint && jest --coverage && codecov", + "pretty-lint": "prettier --check lib/*.js lib/__tests__/*.js", + "pretty": "prettier --loglevel warn --write lib/*.js lib/__tests__/*.js" + }, + "jest": { + "transform": { + "__tests__[\\\\/].+\\.js$": "babel-jest" + } + } +} diff --git a/node_modules/tapable/tapable.d.ts b/node_modules/tapable/tapable.d.ts new file mode 100644 index 0000000..0201c9a --- /dev/null +++ b/node_modules/tapable/tapable.d.ts @@ -0,0 +1,116 @@ +type FixedSizeArray = T extends 0 + ? void[] + : ReadonlyArray & { + 0: U; + length: T; + }; +type Measure = T extends 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 + ? T + : never; +type Append = { + 0: [U]; + 1: [T[0], U]; + 2: [T[0], T[1], U]; + 3: [T[0], T[1], T[2], U]; + 4: [T[0], T[1], T[2], T[3], U]; + 5: [T[0], T[1], T[2], T[3], T[4], U]; + 6: [T[0], T[1], T[2], T[3], T[4], T[5], U]; + 7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], U]; + 8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], U]; +}[Measure]; +type AsArray = T extends any[] ? T : [T]; + +declare class UnsetAdditionalOptions { + _UnsetAdditionalOptions: true +} +type IfSet = X extends UnsetAdditionalOptions ? {} : X; + +type Callback = (error: E | null, result?: T) => void; +type InnerCallback = (error?: E | null | false, result?: T) => void; + +type FullTap = Tap & { + type: "sync" | "async" | "promise", + fn: Function +} + +type Tap = TapOptions & { + name: string; +}; + +type TapOptions = { + before?: string; + stage?: number; +}; + +interface HookInterceptor { + name?: string; + tap?: (tap: FullTap & IfSet) => void; + call?: (...args: any[]) => void; + loop?: (...args: any[]) => void; + error?: (err: Error) => void; + result?: (result: R) => void; + done?: () => void; + register?: (tap: FullTap & IfSet) => FullTap & IfSet; +} + +type ArgumentNames = FixedSizeArray; + +declare class Hook { + constructor(args?: ArgumentNames>, name?: string); + name: string | undefined; + taps: FullTap[]; + intercept(interceptor: HookInterceptor): void; + isUsed(): boolean; + callAsync(...args: Append, Callback>): void; + promise(...args: AsArray): Promise; + tap(options: string | Tap & IfSet, fn: (...args: AsArray) => R): void; + withOptions(options: TapOptions & IfSet): Omit; +} + +export class SyncHook extends Hook { + call(...args: AsArray): R; +} + +export class SyncBailHook extends SyncHook {} +export class SyncLoopHook extends SyncHook {} +export class SyncWaterfallHook extends SyncHook[0], AdditionalOptions> {} + +declare class AsyncHook extends Hook { + tapAsync( + options: string | Tap & IfSet, + fn: (...args: Append, InnerCallback>) => void + ): void; + tapPromise( + options: string | Tap & IfSet, + fn: (...args: AsArray) => Promise + ): void; +} + +export class AsyncParallelHook extends AsyncHook {} +export class AsyncParallelBailHook extends AsyncHook {} +export class AsyncSeriesHook extends AsyncHook {} +export class AsyncSeriesBailHook extends AsyncHook {} +export class AsyncSeriesLoopHook extends AsyncHook {} +export class AsyncSeriesWaterfallHook extends AsyncHook[0], AdditionalOptions> {} + +type HookFactory = (key: any, hook?: H) => H; + +interface HookMapInterceptor { + factory?: HookFactory; +} + +export class HookMap { + constructor(factory: HookFactory, name?: string); + name: string | undefined; + get(key: any): H | undefined; + for(key: any): H; + intercept(interceptor: HookMapInterceptor): void; +} + +export class MultiHook { + constructor(hooks: H[], name?: string); + name: string | undefined; + tap(options: string | Tap, fn?: Function): void; + tapAsync(options: string | Tap, fn?: Function): void; + tapPromise(options: string | Tap, fn?: Function): void; +} diff --git a/node_modules/terser-webpack-plugin/LICENSE b/node_modules/terser-webpack-plugin/LICENSE new file mode 100644 index 0000000..8c11fc7 --- /dev/null +++ b/node_modules/terser-webpack-plugin/LICENSE @@ -0,0 +1,20 @@ +Copyright JS Foundation and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/terser-webpack-plugin/README.md b/node_modules/terser-webpack-plugin/README.md new file mode 100644 index 0000000..a3c24e3 --- /dev/null +++ b/node_modules/terser-webpack-plugin/README.md @@ -0,0 +1,934 @@ + + +[![npm][npm]][npm-url] +[![node][node]][node-url] +[![tests][tests]][tests-url] +[![cover][cover]][cover-url] +[![discussion][discussion]][discussion-url] +[![size][size]][size-url] + +# terser-webpack-plugin + +This plugin uses [terser](https://github.com/terser/terser) to minify/minimize your JavaScript. + +## Getting Started + +Webpack v5 comes with the latest `terser-webpack-plugin` out of the box. If you are using Webpack v5 or above and wish to customize the options, you will still need to install `terser-webpack-plugin`. Using Webpack v4, you have to install `terser-webpack-plugin` v4. + +To begin, you'll need to install `terser-webpack-plugin`: + +```console +npm install terser-webpack-plugin --save-dev +``` + +or + +```console +yarn add -D terser-webpack-plugin +``` + +or + +```console +pnpm add -D terser-webpack-plugin +``` + +Then add the plugin to your `webpack` config. For example: + +**webpack.config.js** + +```js +const TerserPlugin = require("terser-webpack-plugin"); + +module.exports = { + optimization: { + minimize: true, + minimizer: [new TerserPlugin()], + }, +}; +``` + +And run `webpack` via your preferred method. + +## Note about source maps + +**Works only with `source-map`, `inline-source-map`, `hidden-source-map` and `nosources-source-map` values for the [`devtool`](https://webpack.js.org/configuration/devtool/) option.** + +Why? + +- `eval` wraps modules in `eval("string")` and the minimizer does not handle strings. +- `cheap` has not column information and minimizer generate only a single line, which leave only a single mapping. + +Using supported `devtool` values enable source map generation. + +## Options + +- **[`test`](#test)** +- **[`include`](#include)** +- **[`exclude`](#exclude)** +- **[`parallel`](#parallel)** +- **[`minify`](#minify)** +- **[`terserOptions`](#terseroptions)** +- **[`extractComments`](#extractcomments)** + +### `test` + +Type: + +```ts +type test = string | RegExp | Array; +``` + +Default: `/\.m?js(\?.*)?$/i` + +Test to match files against. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + test: /\.js(\?.*)?$/i, + }), + ], + }, +}; +``` + +### `include` + +Type: + +```ts +type include = string | RegExp | Array; +``` + +Default: `undefined` + +Files to include. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + include: /\/includes/, + }), + ], + }, +}; +``` + +### `exclude` + +Type: + +```ts +type exclude = string | RegExp | Array; +``` + +Default: `undefined` + +Files to exclude. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + exclude: /\/excludes/, + }), + ], + }, +}; +``` + +### `parallel` + +Type: + +```ts +type parallel = boolean | number; +``` + +Default: `true` + +Use multi-process parallel running to improve the build speed. +Default number of concurrent runs: `os.cpus().length - 1`. + +> **Note** +> +> Parallelization can speedup your build significantly and is therefore **highly recommended**. + +> **Warning** +> +> If you use **Circle CI** or any other environment that doesn't provide real available count of CPUs then you need to setup explicitly number of CPUs to avoid `Error: Call retries were exceeded` (see [#143](https://github.com/webpack-contrib/terser-webpack-plugin/issues/143), [#202](https://github.com/webpack-contrib/terser-webpack-plugin/issues/202)). + +#### `boolean` + +Enable/disable multi-process parallel running. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + parallel: true, + }), + ], + }, +}; +``` + +#### `number` + +Enable multi-process parallel running and set number of concurrent runs. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + parallel: 4, + }), + ], + }, +}; +``` + +### `minify` + +Type: + +```ts +type minify = ( + input: { + [file: string]: string; + }, + sourceMap: import("@jridgewell/trace-mapping").SourceMapInput | undefined, + minifyOptions: { + module?: boolean | undefined; + ecma?: import("terser").ECMA | undefined; + }, + extractComments: + | boolean + | "all" + | "some" + | RegExp + | (( + astNode: any, + comment: { + value: string; + type: "comment1" | "comment2" | "comment3" | "comment4"; + pos: number; + line: number; + col: number; + } + ) => boolean) + | { + condition?: + | boolean + | "all" + | "some" + | RegExp + | (( + astNode: any, + comment: { + value: string; + type: "comment1" | "comment2" | "comment3" | "comment4"; + pos: number; + line: number; + col: number; + } + ) => boolean) + | undefined; + filename?: string | ((fileData: any) => string) | undefined; + banner?: + | string + | boolean + | ((commentsFile: string) => string) + | undefined; + } + | undefined +) => Promise<{ + code: string; + map?: import("@jridgewell/trace-mapping").SourceMapInput | undefined; + errors?: (string | Error)[] | undefined; + warnings?: (string | Error)[] | undefined; + extractedComments?: string[] | undefined; +}>; +``` + +Default: `TerserPlugin.terserMinify` + +Allows you to override default minify function. +By default plugin uses [terser](https://github.com/terser/terser) package. +Useful for using and testing unpublished versions or forks. + +> **Warning** +> +> **Always use `require` inside `minify` function when `parallel` option enabled**. + +**webpack.config.js** + +```js +// Can be async +const minify = (input, sourceMap, minimizerOptions, extractsComments) => { + // The `minimizerOptions` option contains option from the `terserOptions` option + // You can use `minimizerOptions.myCustomOption` + + // Custom logic for extract comments + const { map, code } = require("uglify-module") // Or require('./path/to/uglify-module') + .minify(input, { + /* Your options for minification */ + }); + + return { map, code, warnings: [], errors: [], extractedComments: [] }; +}; + +// Used to regenerate `fullhash`/`chunkhash` between different implementation +// Example: you fix a bug in custom minimizer/custom function, but unfortunately webpack doesn't know about it, so you will get the same fullhash/chunkhash +// to avoid this you can provide version of your custom minimizer +// You don't need if you use only `contenthash` +minify.getMinimizerVersion = () => { + let packageJson; + + try { + // eslint-disable-next-line global-require, import/no-extraneous-dependencies + packageJson = require("uglify-module/package.json"); + } catch (error) { + // Ignore + } + + return packageJson && packageJson.version; +}; + +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + terserOptions: { + myCustomOption: true, + }, + minify, + }), + ], + }, +}; +``` + +### `terserOptions` + +Type: + +```ts +type terserOptions = { + compress?: boolean | CompressOptions; + ecma?: ECMA; + enclose?: boolean | string; + ie8?: boolean; + keep_classnames?: boolean | RegExp; + keep_fnames?: boolean | RegExp; + mangle?: boolean | MangleOptions; + module?: boolean; + nameCache?: object; + format?: FormatOptions; + /** @deprecated */ + output?: FormatOptions; + parse?: ParseOptions; + safari10?: boolean; + sourceMap?: boolean | SourceMapOptions; + toplevel?: boolean; +}; +``` + +Default: [default](https://github.com/terser/terser#minify-options) + +Terser [options](https://github.com/terser/terser#minify-options). + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + terserOptions: { + ecma: undefined, + parse: {}, + compress: {}, + mangle: true, // Note `mangle.properties` is `false` by default. + module: false, + // Deprecated + output: null, + format: null, + toplevel: false, + nameCache: null, + ie8: false, + keep_classnames: undefined, + keep_fnames: false, + safari10: false, + }, + }), + ], + }, +}; +``` + +### `extractComments` + +Type: + +```ts +type extractComments = + | boolean + | string + | RegExp + | (( + astNode: any, + comment: { + value: string; + type: "comment1" | "comment2" | "comment3" | "comment4"; + pos: number; + line: number; + col: number; + } + ) => boolean) + | { + condition?: + | boolean + | "all" + | "some" + | RegExp + | (( + astNode: any, + comment: { + value: string; + type: "comment1" | "comment2" | "comment3" | "comment4"; + pos: number; + line: number; + col: number; + } + ) => boolean) + | undefined; + filename?: string | ((fileData: any) => string) | undefined; + banner?: + | string + | boolean + | ((commentsFile: string) => string) + | undefined; + }; +``` + +Default: `true` + +Whether comments shall be extracted to a separate file, (see [details](https://github.com/webpack/webpack/commit/71933e979e51c533b432658d5e37917f9e71595a)). +By default extract only comments using `/^\**!|@preserve|@license|@cc_on/i` regexp condition and remove remaining comments. +If the original file is named `foo.js`, then the comments will be stored to `foo.js.LICENSE.txt`. +The `terserOptions.format.comments` option specifies whether the comment will be preserved, i.e. it is possible to preserve some comments (e.g. annotations) while extracting others or even preserving comments that have been extracted. + +#### `boolean` + +Enable/disable extracting comments. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + extractComments: true, + }), + ], + }, +}; +``` + +#### `string` + +Extract `all` or `some` (use `/^\**!|@preserve|@license|@cc_on/i` RegExp) comments. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + extractComments: "all", + }), + ], + }, +}; +``` + +#### `RegExp` + +All comments that match the given expression will be extracted to the separate file. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + extractComments: /@extract/i, + }), + ], + }, +}; +``` + +#### `function` + +All comments that match the given expression will be extracted to the separate file. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + extractComments: (astNode, comment) => { + if (/@extract/i.test(comment.value)) { + return true; + } + + return false; + }, + }), + ], + }, +}; +``` + +#### `object` + +Allow to customize condition for extract comments, specify extracted file name and banner. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + extractComments: { + condition: /^\**!|@preserve|@license|@cc_on/i, + filename: (fileData) => { + // The "fileData" argument contains object with "filename", "basename", "query" and "hash" + return `${fileData.filename}.LICENSE.txt${fileData.query}`; + }, + banner: (licenseFile) => { + return `License information can be found in ${licenseFile}`; + }, + }, + }), + ], + }, +}; +``` + +##### `condition` + +Type: + +```ts +type condition = + | boolean + | "all" + | "some" + | RegExp + | (( + astNode: any, + comment: { + value: string; + type: "comment1" | "comment2" | "comment3" | "comment4"; + pos: number; + line: number; + col: number; + } + ) => boolean) + | undefined; +``` + +Condition what comments you need extract. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + extractComments: { + condition: "some", + filename: (fileData) => { + // The "fileData" argument contains object with "filename", "basename", "query" and "hash" + return `${fileData.filename}.LICENSE.txt${fileData.query}`; + }, + banner: (licenseFile) => { + return `License information can be found in ${licenseFile}`; + }, + }, + }), + ], + }, +}; +``` + +##### `filename` + +Type: + +```ts +type filename = string | ((fileData: any) => string) | undefined; +``` + +Default: `[file].LICENSE.txt[query]` + +Available placeholders: `[file]`, `[query]` and `[filebase]` (`[base]` for webpack 5). + +The file where the extracted comments will be stored. +Default is to append the suffix `.LICENSE.txt` to the original filename. + +> **Warning** +> +> We highly recommend using the `txt` extension. Using `js`/`cjs`/`mjs` extensions may conflict with existing assets which leads to broken code. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + extractComments: { + condition: /^\**!|@preserve|@license|@cc_on/i, + filename: "extracted-comments.js", + banner: (licenseFile) => { + return `License information can be found in ${licenseFile}`; + }, + }, + }), + ], + }, +}; +``` + +##### `banner` + +Type: + +```ts +type banner = string | boolean | ((commentsFile: string) => string) | undefined; +``` + +Default: `/*! For license information please see ${commentsFile} */` + +The banner text that points to the extracted file and will be added on top of the original file. +Can be `false` (no banner), a `String`, or a `Function<(string) -> String>` that will be called with the filename where extracted comments have been stored. +Will be wrapped into comment. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + extractComments: { + condition: true, + filename: (fileData) => { + // The "fileData" argument contains object with "filename", "basename", "query" and "hash" + return `${fileData.filename}.LICENSE.txt${fileData.query}`; + }, + banner: (commentsFile) => { + return `My custom banner about license information ${commentsFile}`; + }, + }, + }), + ], + }, +}; +``` + +## Examples + +### Preserve Comments + +Extract all legal comments (i.e. `/^\**!|@preserve|@license|@cc_on/i`) and preserve `/@license/i` comments. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + terserOptions: { + format: { + comments: /@license/i, + }, + }, + extractComments: true, + }), + ], + }, +}; +``` + +### Remove Comments + +If you avoid building with comments, use this config: + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + terserOptions: { + format: { + comments: false, + }, + }, + extractComments: false, + }), + ], + }, +}; +``` + +### [`uglify-js`](https://github.com/mishoo/UglifyJS) + +[`UglifyJS`](https://github.com/mishoo/UglifyJS) is a JavaScript parser, minifier, compressor and beautifier toolkit. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + minify: TerserPlugin.uglifyJsMinify, + // `terserOptions` options will be passed to `uglify-js` + // Link to options - https://github.com/mishoo/UglifyJS#minify-options + terserOptions: {}, + }), + ], + }, +}; +``` + +### [`swc`](https://github.com/swc-project/swc) + +[`swc`](https://github.com/swc-project/swc) is a super-fast compiler written in rust; producing widely-supported javascript from modern standards and typescript. + +> **Warning** +> +> the `extractComments` option is not supported and all comments will be removed by default, it will be fixed in future + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + minify: TerserPlugin.swcMinify, + // `terserOptions` options will be passed to `swc` (`@swc/core`) + // Link to options - https://swc.rs/docs/config-js-minify + terserOptions: {}, + }), + ], + }, +}; +``` + +### [`esbuild`](https://github.com/evanw/esbuild) + +[`esbuild`](https://github.com/evanw/esbuild) is an extremely fast JavaScript bundler and minifier. + +> **Warning** +> +> the `extractComments` option is not supported and all legal comments (i.e. copyright, licenses and etc) will be preserved + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + minify: TerserPlugin.esbuildMinify, + // `terserOptions` options will be passed to `esbuild` + // Link to options - https://esbuild.github.io/api/#minify + // Note: the `minify` options is true by default (and override other `minify*` options), so if you want to disable the `minifyIdentifiers` option (or other `minify*` options) please use: + // terserOptions: { + // minify: false, + // minifyWhitespace: true, + // minifyIdentifiers: false, + // minifySyntax: true, + // }, + terserOptions: {}, + }), + ], + }, +}; +``` + +### Custom Minify Function + +Override default minify function - use `uglify-js` for minification. + +**webpack.config.js** + +```js +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + minify: (file, sourceMap) => { + // https://github.com/mishoo/UglifyJS2#minify-options + const uglifyJsOptions = { + /* your `uglify-js` package options */ + }; + + if (sourceMap) { + uglifyJsOptions.sourceMap = { + content: sourceMap, + }; + } + + return require("uglify-js").minify(file, uglifyJsOptions); + }, + }), + ], + }, +}; +``` + +### Typescript + +With default terser minify function: + +```ts +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + terserOptions: { + compress: true, + }, + }), + ], + }, +}; +``` + +With built-in minify functions: + +```ts +import type { JsMinifyOptions as SwcOptions } from "@swc/core"; +import type { MinifyOptions as UglifyJSOptions } from "uglify-js"; +import type { TransformOptions as EsbuildOptions } from "esbuild"; +import type { MinifyOptions as TerserOptions } from "terser"; + +module.exports = { + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + minify: TerserPlugin.swcMinify, + terserOptions: { + // `swc` options + }, + }), + new TerserPlugin({ + minify: TerserPlugin.uglifyJsMinify, + terserOptions: { + // `uglif-js` options + }, + }), + new TerserPlugin({ + minify: TerserPlugin.esbuildMinify, + terserOptions: { + // `esbuild` options + }, + }), + + // Alternative usage: + new TerserPlugin({ + minify: TerserPlugin.terserMinify, + terserOptions: { + // `terser` options + }, + }), + ], + }, +}; +``` + +## Contributing + +Please take a moment to read our contributing guidelines if you haven't yet done so. + +[CONTRIBUTING](./.github/CONTRIBUTING.md) + +## License + +[MIT](./LICENSE) + +[npm]: https://img.shields.io/npm/v/terser-webpack-plugin.svg +[npm-url]: https://npmjs.com/package/terser-webpack-plugin +[node]: https://img.shields.io/node/v/terser-webpack-plugin.svg +[node-url]: https://nodejs.org +[tests]: https://github.com/webpack-contrib/terser-webpack-plugin/workflows/terser-webpack-plugin/badge.svg +[tests-url]: https://github.com/webpack-contrib/terser-webpack-plugin/actions +[cover]: https://codecov.io/gh/webpack-contrib/terser-webpack-plugin/branch/master/graph/badge.svg +[cover-url]: https://codecov.io/gh/webpack-contrib/terser-webpack-plugin +[discussion]: https://img.shields.io/github/discussions/webpack/webpack +[discussion-url]: https://github.com/webpack/webpack/discussions +[size]: https://packagephobia.now.sh/badge?p=terser-webpack-plugin +[size-url]: https://packagephobia.now.sh/result?p=terser-webpack-plugin diff --git a/node_modules/terser-webpack-plugin/dist/index.js b/node_modules/terser-webpack-plugin/dist/index.js new file mode 100644 index 0000000..7c54448 --- /dev/null +++ b/node_modules/terser-webpack-plugin/dist/index.js @@ -0,0 +1,692 @@ +"use strict"; + +const path = require("path"); +const os = require("os"); +const { + validate +} = require("schema-utils"); +const { + throttleAll, + memoize, + terserMinify, + uglifyJsMinify, + swcMinify, + esbuildMinify +} = require("./utils"); +const schema = require("./options.json"); +const { + minify +} = require("./minify"); + +/** @typedef {import("schema-utils/declarations/validate").Schema} Schema */ +/** @typedef {import("webpack").Compiler} Compiler */ +/** @typedef {import("webpack").Compilation} Compilation */ +/** @typedef {import("webpack").WebpackError} WebpackError */ +/** @typedef {import("webpack").Asset} Asset */ +/** @typedef {import("./utils.js").TerserECMA} TerserECMA */ +/** @typedef {import("./utils.js").TerserOptions} TerserOptions */ +/** @typedef {import("jest-worker").Worker} JestWorker */ +/** @typedef {import("@jridgewell/trace-mapping").SourceMapInput} SourceMapInput */ +/** @typedef {import("@jridgewell/trace-mapping").TraceMap} TraceMap */ + +/** @typedef {RegExp | string} Rule */ +/** @typedef {Rule[] | Rule} Rules */ + +/** + * @callback ExtractCommentsFunction + * @param {any} astNode + * @param {{ value: string, type: 'comment1' | 'comment2' | 'comment3' | 'comment4', pos: number, line: number, col: number }} comment + * @returns {boolean} + */ + +/** + * @typedef {boolean | 'all' | 'some' | RegExp | ExtractCommentsFunction} ExtractCommentsCondition + */ + +/** + * @typedef {string | ((fileData: any) => string)} ExtractCommentsFilename + */ + +/** + * @typedef {boolean | string | ((commentsFile: string) => string)} ExtractCommentsBanner + */ + +/** + * @typedef {Object} ExtractCommentsObject + * @property {ExtractCommentsCondition} [condition] + * @property {ExtractCommentsFilename} [filename] + * @property {ExtractCommentsBanner} [banner] + */ + +/** + * @typedef {ExtractCommentsCondition | ExtractCommentsObject} ExtractCommentsOptions + */ + +/** + * @typedef {Object} MinimizedResult + * @property {string} code + * @property {SourceMapInput} [map] + * @property {Array} [errors] + * @property {Array} [warnings] + * @property {Array} [extractedComments] + */ + +/** + * @typedef {{ [file: string]: string }} Input + */ + +/** + * @typedef {{ [key: string]: any }} CustomOptions + */ + +/** + * @template T + * @typedef {T extends infer U ? U : CustomOptions} InferDefaultType + */ + +/** + * @typedef {Object} PredefinedOptions + * @property {boolean} [module] + * @property {TerserECMA} [ecma] + */ + +/** + * @template T + * @typedef {PredefinedOptions & InferDefaultType} MinimizerOptions + */ + +/** + * @template T + * @callback BasicMinimizerImplementation + * @param {Input} input + * @param {SourceMapInput | undefined} sourceMap + * @param {MinimizerOptions} minifyOptions + * @param {ExtractCommentsOptions | undefined} extractComments + * @returns {Promise} + */ + +/** + * @typedef {object} MinimizeFunctionHelpers + * @property {() => string | undefined} [getMinimizerVersion] + */ + +/** + * @template T + * @typedef {BasicMinimizerImplementation & MinimizeFunctionHelpers} MinimizerImplementation + */ + +/** + * @template T + * @typedef {Object} InternalOptions + * @property {string} name + * @property {string} input + * @property {SourceMapInput | undefined} inputSourceMap + * @property {ExtractCommentsOptions | undefined} extractComments + * @property {{ implementation: MinimizerImplementation, options: MinimizerOptions }} minimizer + */ + +/** + * @template T + * @typedef {JestWorker & { transform: (options: string) => MinimizedResult, minify: (options: InternalOptions) => MinimizedResult }} MinimizerWorker + */ + +/** + * @typedef {undefined | boolean | number} Parallel + */ + +/** + * @typedef {Object} BasePluginOptions + * @property {Rules} [test] + * @property {Rules} [include] + * @property {Rules} [exclude] + * @property {ExtractCommentsOptions} [extractComments] + * @property {Parallel} [parallel] + */ + +/** + * @template T + * @typedef {T extends TerserOptions ? { minify?: MinimizerImplementation | undefined, terserOptions?: MinimizerOptions | undefined } : { minify: MinimizerImplementation, terserOptions?: MinimizerOptions | undefined }} DefinedDefaultMinimizerAndOptions + */ + +/** + * @template T + * @typedef {BasePluginOptions & { minimizer: { implementation: MinimizerImplementation, options: MinimizerOptions } }} InternalPluginOptions + */ + +const getTraceMapping = memoize(() => +// eslint-disable-next-line global-require +require("@jridgewell/trace-mapping")); +const getSerializeJavascript = memoize(() => +// eslint-disable-next-line global-require +require("serialize-javascript")); + +/** + * @template [T=TerserOptions] + */ +class TerserPlugin { + /** + * @param {BasePluginOptions & DefinedDefaultMinimizerAndOptions} [options] + */ + constructor(options) { + validate( /** @type {Schema} */schema, options || {}, { + name: "Terser Plugin", + baseDataPath: "options" + }); + + // TODO make `minimizer` option instead `minify` and `terserOptions` in the next major release, also rename `terserMinify` to `terserMinimize` + const { + minify = ( /** @type {MinimizerImplementation} */terserMinify), + terserOptions = ( /** @type {MinimizerOptions} */{}), + test = /\.[cm]?js(\?.*)?$/i, + extractComments = true, + parallel = true, + include, + exclude + } = options || {}; + + /** + * @private + * @type {InternalPluginOptions} + */ + this.options = { + test, + extractComments, + parallel, + include, + exclude, + minimizer: { + implementation: minify, + options: terserOptions + } + }; + } + + /** + * @private + * @param {any} input + * @returns {boolean} + */ + static isSourceMap(input) { + // All required options for `new TraceMap(...options)` + // https://github.com/jridgewell/trace-mapping#usage + return Boolean(input && input.version && input.sources && Array.isArray(input.sources) && typeof input.mappings === "string"); + } + + /** + * @private + * @param {unknown} warning + * @param {string} file + * @returns {Error} + */ + static buildWarning(warning, file) { + /** + * @type {Error & { hideStack: true, file: string }} + */ + // @ts-ignore + const builtWarning = new Error(warning.toString()); + builtWarning.name = "Warning"; + builtWarning.hideStack = true; + builtWarning.file = file; + return builtWarning; + } + + /** + * @private + * @param {any} error + * @param {string} file + * @param {TraceMap} [sourceMap] + * @param {Compilation["requestShortener"]} [requestShortener] + * @returns {Error} + */ + static buildError(error, file, sourceMap, requestShortener) { + /** + * @type {Error & { file?: string }} + */ + let builtError; + if (typeof error === "string") { + builtError = new Error(`${file} from Terser plugin\n${error}`); + builtError.file = file; + return builtError; + } + if (error.line) { + const original = sourceMap && getTraceMapping().originalPositionFor(sourceMap, { + line: error.line, + column: error.col + }); + if (original && original.source && requestShortener) { + builtError = new Error(`${file} from Terser plugin\n${error.message} [${requestShortener.shorten(original.source)}:${original.line},${original.column}][${file}:${error.line},${error.col}]${error.stack ? `\n${error.stack.split("\n").slice(1).join("\n")}` : ""}`); + builtError.file = file; + return builtError; + } + builtError = new Error(`${file} from Terser plugin\n${error.message} [${file}:${error.line},${error.col}]${error.stack ? `\n${error.stack.split("\n").slice(1).join("\n")}` : ""}`); + builtError.file = file; + return builtError; + } + if (error.stack) { + builtError = new Error(`${file} from Terser plugin\n${typeof error.message !== "undefined" ? error.message : ""}\n${error.stack}`); + builtError.file = file; + return builtError; + } + builtError = new Error(`${file} from Terser plugin\n${error.message}`); + builtError.file = file; + return builtError; + } + + /** + * @private + * @param {Parallel} parallel + * @returns {number} + */ + static getAvailableNumberOfCores(parallel) { + // In some cases cpus() returns undefined + // https://github.com/nodejs/node/issues/19022 + const cpus = os.cpus() || { + length: 1 + }; + return parallel === true ? cpus.length - 1 : Math.min(Number(parallel) || 0, cpus.length - 1); + } + + /** + * @private + * @param {Compiler} compiler + * @param {Compilation} compilation + * @param {Record} assets + * @param {{availableNumberOfCores: number}} optimizeOptions + * @returns {Promise} + */ + async optimize(compiler, compilation, assets, optimizeOptions) { + const cache = compilation.getCache("TerserWebpackPlugin"); + let numberOfAssets = 0; + const assetsForMinify = await Promise.all(Object.keys(assets).filter(name => { + const { + info + } = /** @type {Asset} */compilation.getAsset(name); + if ( + // Skip double minimize assets from child compilation + info.minimized || + // Skip minimizing for extracted comments assets + info.extractedComments) { + return false; + } + if (!compiler.webpack.ModuleFilenameHelpers.matchObject.bind( + // eslint-disable-next-line no-undefined + undefined, this.options)(name)) { + return false; + } + return true; + }).map(async name => { + const { + info, + source + } = /** @type {Asset} */ + compilation.getAsset(name); + const eTag = cache.getLazyHashedEtag(source); + const cacheItem = cache.getItemCache(name, eTag); + const output = await cacheItem.getPromise(); + if (!output) { + numberOfAssets += 1; + } + return { + name, + info, + inputSource: source, + output, + cacheItem + }; + })); + if (assetsForMinify.length === 0) { + return; + } + + /** @type {undefined | (() => MinimizerWorker)} */ + let getWorker; + /** @type {undefined | MinimizerWorker} */ + let initializedWorker; + /** @type {undefined | number} */ + let numberOfWorkers; + if (optimizeOptions.availableNumberOfCores > 0) { + // Do not create unnecessary workers when the number of files is less than the available cores, it saves memory + numberOfWorkers = Math.min(numberOfAssets, optimizeOptions.availableNumberOfCores); + // eslint-disable-next-line consistent-return + getWorker = () => { + if (initializedWorker) { + return initializedWorker; + } + + // eslint-disable-next-line global-require + const { + Worker + } = require("jest-worker"); + initializedWorker = /** @type {MinimizerWorker} */ + + new Worker(require.resolve("./minify"), { + numWorkers: numberOfWorkers, + enableWorkerThreads: true + }); + + // https://github.com/facebook/jest/issues/8872#issuecomment-524822081 + const workerStdout = initializedWorker.getStdout(); + if (workerStdout) { + workerStdout.on("data", chunk => process.stdout.write(chunk)); + } + const workerStderr = initializedWorker.getStderr(); + if (workerStderr) { + workerStderr.on("data", chunk => process.stderr.write(chunk)); + } + return initializedWorker; + }; + } + const { + SourceMapSource, + ConcatSource, + RawSource + } = compiler.webpack.sources; + + /** @typedef {{ extractedCommentsSource : import("webpack").sources.RawSource, commentsFilename: string }} ExtractedCommentsInfo */ + /** @type {Map} */ + const allExtractedComments = new Map(); + const scheduledTasks = []; + for (const asset of assetsForMinify) { + scheduledTasks.push(async () => { + const { + name, + inputSource, + info, + cacheItem + } = asset; + let { + output + } = asset; + if (!output) { + let input; + /** @type {SourceMapInput | undefined} */ + let inputSourceMap; + const { + source: sourceFromInputSource, + map + } = inputSource.sourceAndMap(); + input = sourceFromInputSource; + if (map) { + if (!TerserPlugin.isSourceMap(map)) { + compilation.warnings.push( /** @type {WebpackError} */ + new Error(`${name} contains invalid source map`)); + } else { + inputSourceMap = /** @type {SourceMapInput} */map; + } + } + if (Buffer.isBuffer(input)) { + input = input.toString(); + } + + /** + * @type {InternalOptions} + */ + const options = { + name, + input, + inputSourceMap, + minimizer: { + implementation: this.options.minimizer.implementation, + // @ts-ignore https://github.com/Microsoft/TypeScript/issues/10727 + options: { + ...this.options.minimizer.options + } + }, + extractComments: this.options.extractComments + }; + if (typeof options.minimizer.options.module === "undefined") { + if (typeof info.javascriptModule !== "undefined") { + options.minimizer.options.module = info.javascriptModule; + } else if (/\.mjs(\?.*)?$/i.test(name)) { + options.minimizer.options.module = true; + } else if (/\.cjs(\?.*)?$/i.test(name)) { + options.minimizer.options.module = false; + } + } + if (typeof options.minimizer.options.ecma === "undefined") { + options.minimizer.options.ecma = TerserPlugin.getEcmaVersion(compiler.options.output.environment || {}); + } + try { + output = await (getWorker ? getWorker().transform(getSerializeJavascript()(options)) : minify(options)); + } catch (error) { + const hasSourceMap = inputSourceMap && TerserPlugin.isSourceMap(inputSourceMap); + compilation.errors.push( /** @type {WebpackError} */ + + TerserPlugin.buildError(error, name, hasSourceMap ? new (getTraceMapping().TraceMap)( /** @type {SourceMapInput} */inputSourceMap) : + // eslint-disable-next-line no-undefined + undefined, + // eslint-disable-next-line no-undefined + hasSourceMap ? compilation.requestShortener : undefined)); + return; + } + if (typeof output.code === "undefined") { + compilation.errors.push( /** @type {WebpackError} */ + + new Error(`${name} from Terser plugin\nMinimizer doesn't return result`)); + return; + } + if (output.warnings && output.warnings.length > 0) { + output.warnings = output.warnings.map( + /** + * @param {Error | string} item + */ + item => TerserPlugin.buildWarning(item, name)); + } + if (output.errors && output.errors.length > 0) { + const hasSourceMap = inputSourceMap && TerserPlugin.isSourceMap(inputSourceMap); + output.errors = output.errors.map( + /** + * @param {Error | string} item + */ + item => TerserPlugin.buildError(item, name, hasSourceMap ? new (getTraceMapping().TraceMap)( /** @type {SourceMapInput} */inputSourceMap) : + // eslint-disable-next-line no-undefined + undefined, + // eslint-disable-next-line no-undefined + hasSourceMap ? compilation.requestShortener : undefined)); + } + let shebang; + if ( /** @type {ExtractCommentsObject} */ + this.options.extractComments.banner !== false && output.extractedComments && output.extractedComments.length > 0 && output.code.startsWith("#!")) { + const firstNewlinePosition = output.code.indexOf("\n"); + shebang = output.code.substring(0, firstNewlinePosition); + output.code = output.code.substring(firstNewlinePosition + 1); + } + if (output.map) { + output.source = new SourceMapSource(output.code, name, output.map, input, /** @type {SourceMapInput} */inputSourceMap, true); + } else { + output.source = new RawSource(output.code); + } + if (output.extractedComments && output.extractedComments.length > 0) { + const commentsFilename = /** @type {ExtractCommentsObject} */ + this.options.extractComments.filename || "[file].LICENSE.txt[query]"; + let query = ""; + let filename = name; + const querySplit = filename.indexOf("?"); + if (querySplit >= 0) { + query = filename.slice(querySplit); + filename = filename.slice(0, querySplit); + } + const lastSlashIndex = filename.lastIndexOf("/"); + const basename = lastSlashIndex === -1 ? filename : filename.slice(lastSlashIndex + 1); + const data = { + filename, + basename, + query + }; + output.commentsFilename = compilation.getPath(commentsFilename, data); + let banner; + + // Add a banner to the original file + if ( /** @type {ExtractCommentsObject} */ + this.options.extractComments.banner !== false) { + banner = /** @type {ExtractCommentsObject} */ + this.options.extractComments.banner || `For license information please see ${path.relative(path.dirname(name), output.commentsFilename).replace(/\\/g, "/")}`; + if (typeof banner === "function") { + banner = banner(output.commentsFilename); + } + if (banner) { + output.source = new ConcatSource(shebang ? `${shebang}\n` : "", `/*! ${banner} */\n`, output.source); + } + } + const extractedCommentsString = output.extractedComments.sort().join("\n\n"); + output.extractedCommentsSource = new RawSource(`${extractedCommentsString}\n`); + } + await cacheItem.storePromise({ + source: output.source, + errors: output.errors, + warnings: output.warnings, + commentsFilename: output.commentsFilename, + extractedCommentsSource: output.extractedCommentsSource + }); + } + if (output.warnings && output.warnings.length > 0) { + for (const warning of output.warnings) { + compilation.warnings.push( /** @type {WebpackError} */warning); + } + } + if (output.errors && output.errors.length > 0) { + for (const error of output.errors) { + compilation.errors.push( /** @type {WebpackError} */error); + } + } + + /** @type {Record} */ + const newInfo = { + minimized: true + }; + const { + source, + extractedCommentsSource + } = output; + + // Write extracted comments to commentsFilename + if (extractedCommentsSource) { + const { + commentsFilename + } = output; + newInfo.related = { + license: commentsFilename + }; + allExtractedComments.set(name, { + extractedCommentsSource, + commentsFilename + }); + } + compilation.updateAsset(name, source, newInfo); + }); + } + const limit = getWorker && numberOfAssets > 0 ? ( /** @type {number} */numberOfWorkers) : scheduledTasks.length; + await throttleAll(limit, scheduledTasks); + if (initializedWorker) { + await initializedWorker.end(); + } + + /** @typedef {{ source: import("webpack").sources.Source, commentsFilename: string, from: string }} ExtractedCommentsInfoWIthFrom */ + await Array.from(allExtractedComments).sort().reduce( + /** + * @param {Promise} previousPromise + * @param {[string, ExtractedCommentsInfo]} extractedComments + * @returns {Promise} + */ + async (previousPromise, [from, value]) => { + const previous = /** @type {ExtractedCommentsInfoWIthFrom | undefined} **/ + await previousPromise; + const { + commentsFilename, + extractedCommentsSource + } = value; + if (previous && previous.commentsFilename === commentsFilename) { + const { + from: previousFrom, + source: prevSource + } = previous; + const mergedName = `${previousFrom}|${from}`; + const name = `${commentsFilename}|${mergedName}`; + const eTag = [prevSource, extractedCommentsSource].map(item => cache.getLazyHashedEtag(item)).reduce((previousValue, currentValue) => cache.mergeEtags(previousValue, currentValue)); + let source = await cache.getPromise(name, eTag); + if (!source) { + source = new ConcatSource(Array.from(new Set([... /** @type {string}*/prevSource.source().split("\n\n"), ... /** @type {string}*/extractedCommentsSource.source().split("\n\n")])).join("\n\n")); + await cache.storePromise(name, eTag, source); + } + compilation.updateAsset(commentsFilename, source); + return { + source, + commentsFilename, + from: mergedName + }; + } + const existingAsset = compilation.getAsset(commentsFilename); + if (existingAsset) { + return { + source: existingAsset.source, + commentsFilename, + from: commentsFilename + }; + } + compilation.emitAsset(commentsFilename, extractedCommentsSource, { + extractedComments: true + }); + return { + source: extractedCommentsSource, + commentsFilename, + from + }; + }, /** @type {Promise} */Promise.resolve()); + } + + /** + * @private + * @param {any} environment + * @returns {TerserECMA} + */ + static getEcmaVersion(environment) { + // ES 6th + if (environment.arrowFunction || environment.const || environment.destructuring || environment.forOf || environment.module) { + return 2015; + } + + // ES 11th + if (environment.bigIntLiteral || environment.dynamicImport) { + return 2020; + } + return 5; + } + + /** + * @param {Compiler} compiler + * @returns {void} + */ + apply(compiler) { + const pluginName = this.constructor.name; + const availableNumberOfCores = TerserPlugin.getAvailableNumberOfCores(this.options.parallel); + compiler.hooks.compilation.tap(pluginName, compilation => { + const hooks = compiler.webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(compilation); + const data = getSerializeJavascript()({ + minimizer: typeof this.options.minimizer.implementation.getMinimizerVersion !== "undefined" ? this.options.minimizer.implementation.getMinimizerVersion() || "0.0.0" : "0.0.0", + options: this.options.minimizer.options + }); + hooks.chunkHash.tap(pluginName, (chunk, hash) => { + hash.update("TerserPlugin"); + hash.update(data); + }); + compilation.hooks.processAssets.tapPromise({ + name: pluginName, + stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE, + additionalAssets: true + }, assets => this.optimize(compiler, compilation, assets, { + availableNumberOfCores + })); + compilation.hooks.statsPrinter.tap(pluginName, stats => { + stats.hooks.print.for("asset.info.minimized").tap("terser-webpack-plugin", (minimized, { + green, + formatFlag + }) => minimized ? /** @type {Function} */green( /** @type {Function} */formatFlag("minimized")) : ""); + }); + }); + } +} +TerserPlugin.terserMinify = terserMinify; +TerserPlugin.uglifyJsMinify = uglifyJsMinify; +TerserPlugin.swcMinify = swcMinify; +TerserPlugin.esbuildMinify = esbuildMinify; +module.exports = TerserPlugin; \ No newline at end of file diff --git a/node_modules/terser-webpack-plugin/dist/minify.js b/node_modules/terser-webpack-plugin/dist/minify.js new file mode 100644 index 0000000..69c56f4 --- /dev/null +++ b/node_modules/terser-webpack-plugin/dist/minify.js @@ -0,0 +1,48 @@ +"use strict"; + +/** @typedef {import("./index.js").MinimizedResult} MinimizedResult */ +/** @typedef {import("./index.js").CustomOptions} CustomOptions */ + +/** + * @template T + * @param {import("./index.js").InternalOptions} options + * @returns {Promise} + */ +async function minify(options) { + const { + name, + input, + inputSourceMap, + extractComments + } = options; + const { + implementation, + options: minimizerOptions + } = options.minimizer; + return implementation({ + [name]: input + }, inputSourceMap, minimizerOptions, extractComments); +} + +/** + * @param {string} options + * @returns {Promise} + */ +async function transform(options) { + // 'use strict' => this === undefined (Clean Scope) + // Safer for possible security issues, albeit not critical at all here + // eslint-disable-next-line no-param-reassign + const evaluatedOptions = + /** + * @template T + * @type {import("./index.js").InternalOptions} + * */ + + // eslint-disable-next-line no-new-func + new Function("exports", "require", "module", "__filename", "__dirname", `'use strict'\nreturn ${options}`)(exports, require, module, __filename, __dirname); + return minify(evaluatedOptions); +} +module.exports = { + minify, + transform +}; \ No newline at end of file diff --git a/node_modules/terser-webpack-plugin/dist/options.json b/node_modules/terser-webpack-plugin/dist/options.json new file mode 100644 index 0000000..83d2cfd --- /dev/null +++ b/node_modules/terser-webpack-plugin/dist/options.json @@ -0,0 +1,164 @@ +{ + "definitions": { + "Rule": { + "description": "Filtering rule as regex or string.", + "anyOf": [ + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "string", + "minLength": 1 + } + ] + }, + "Rules": { + "description": "Filtering rules.", + "anyOf": [ + { + "type": "array", + "items": { + "description": "A rule condition.", + "oneOf": [ + { + "$ref": "#/definitions/Rule" + } + ] + } + }, + { + "$ref": "#/definitions/Rule" + } + ] + } + }, + "title": "TerserPluginOptions", + "type": "object", + "additionalProperties": false, + "properties": { + "test": { + "description": "Include all modules that pass test assertion.", + "link": "https://github.com/webpack-contrib/terser-webpack-plugin#test", + "oneOf": [ + { + "$ref": "#/definitions/Rules" + } + ] + }, + "include": { + "description": "Include all modules matching any of these conditions.", + "link": "https://github.com/webpack-contrib/terser-webpack-plugin#include", + "oneOf": [ + { + "$ref": "#/definitions/Rules" + } + ] + }, + "exclude": { + "description": "Exclude all modules matching any of these conditions.", + "link": "https://github.com/webpack-contrib/terser-webpack-plugin#exclude", + "oneOf": [ + { + "$ref": "#/definitions/Rules" + } + ] + }, + "terserOptions": { + "description": "Options for `terser` (by default) or custom `minify` function.", + "link": "https://github.com/webpack-contrib/terser-webpack-plugin#terseroptions", + "additionalProperties": true, + "type": "object" + }, + "extractComments": { + "description": "Whether comments shall be extracted to a separate file.", + "link": "https://github.com/webpack-contrib/terser-webpack-plugin#extractcomments", + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "string", + "minLength": 1 + }, + { + "instanceof": "RegExp" + }, + { + "instanceof": "Function" + }, + { + "additionalProperties": false, + "properties": { + "condition": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "string", + "minLength": 1 + }, + { + "instanceof": "RegExp" + }, + { + "instanceof": "Function" + } + ], + "description": "Condition what comments you need extract.", + "link": "https://github.com/webpack-contrib/terser-webpack-plugin#condition" + }, + "filename": { + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "instanceof": "Function" + } + ], + "description": "The file where the extracted comments will be stored. Default is to append the suffix .LICENSE.txt to the original filename.", + "link": "https://github.com/webpack-contrib/terser-webpack-plugin#filename" + }, + "banner": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "string", + "minLength": 1 + }, + { + "instanceof": "Function" + } + ], + "description": "The banner text that points to the extracted file and will be added on top of the original file", + "link": "https://github.com/webpack-contrib/terser-webpack-plugin#banner" + } + }, + "type": "object" + } + ] + }, + "parallel": { + "description": "Use multi-process parallel running to improve the build speed.", + "link": "https://github.com/webpack-contrib/terser-webpack-plugin#parallel", + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "integer" + } + ] + }, + "minify": { + "description": "Allows you to override default minify function.", + "link": "https://github.com/webpack-contrib/terser-webpack-plugin#number", + "instanceof": "Function" + } + } +} diff --git a/node_modules/terser-webpack-plugin/dist/utils.js b/node_modules/terser-webpack-plugin/dist/utils.js new file mode 100644 index 0000000..65e5780 --- /dev/null +++ b/node_modules/terser-webpack-plugin/dist/utils.js @@ -0,0 +1,637 @@ +"use strict"; + +/** @typedef {import("@jridgewell/trace-mapping").SourceMapInput} SourceMapInput */ +/** @typedef {import("terser").FormatOptions} TerserFormatOptions */ +/** @typedef {import("terser").MinifyOptions} TerserOptions */ +/** @typedef {import("terser").CompressOptions} TerserCompressOptions */ +/** @typedef {import("terser").ECMA} TerserECMA */ +/** @typedef {import("./index.js").ExtractCommentsOptions} ExtractCommentsOptions */ +/** @typedef {import("./index.js").ExtractCommentsFunction} ExtractCommentsFunction */ +/** @typedef {import("./index.js").ExtractCommentsCondition} ExtractCommentsCondition */ +/** @typedef {import("./index.js").Input} Input */ +/** @typedef {import("./index.js").MinimizedResult} MinimizedResult */ +/** @typedef {import("./index.js").PredefinedOptions} PredefinedOptions */ +/** @typedef {import("./index.js").CustomOptions} CustomOptions */ + +/** + * @typedef {Array} ExtractedComments + */ + +const notSettled = Symbol(`not-settled`); + +/** + * @template T + * @typedef {() => Promise} Task + */ + +/** + * Run tasks with limited concurrency. + * @template T + * @param {number} limit - Limit of tasks that run at once. + * @param {Task[]} tasks - List of tasks to run. + * @returns {Promise} A promise that fulfills to an array of the results + */ +function throttleAll(limit, tasks) { + if (!Number.isInteger(limit) || limit < 1) { + throw new TypeError(`Expected \`limit\` to be a finite number > 0, got \`${limit}\` (${typeof limit})`); + } + if (!Array.isArray(tasks) || !tasks.every(task => typeof task === `function`)) { + throw new TypeError(`Expected \`tasks\` to be a list of functions returning a promise`); + } + return new Promise((resolve, reject) => { + const result = Array(tasks.length).fill(notSettled); + const entries = tasks.entries(); + const next = () => { + const { + done, + value + } = entries.next(); + if (done) { + const isLast = !result.includes(notSettled); + if (isLast) resolve( /** @type{T[]} **/result); + return; + } + const [index, task] = value; + + /** + * @param {T} x + */ + const onFulfilled = x => { + result[index] = x; + next(); + }; + task().then(onFulfilled, reject); + }; + Array(limit).fill(0).forEach(next); + }); +} + +/* istanbul ignore next */ +/** + * @param {Input} input + * @param {SourceMapInput | undefined} sourceMap + * @param {PredefinedOptions & CustomOptions} minimizerOptions + * @param {ExtractCommentsOptions | undefined} extractComments + * @return {Promise} + */ +async function terserMinify(input, sourceMap, minimizerOptions, extractComments) { + /** + * @param {any} value + * @returns {boolean} + */ + const isObject = value => { + const type = typeof value; + return value != null && (type === "object" || type === "function"); + }; + + /** + * @param {TerserOptions & { sourceMap: undefined } & ({ output: TerserFormatOptions & { beautify: boolean } } | { format: TerserFormatOptions & { beautify: boolean } })} terserOptions + * @param {ExtractedComments} extractedComments + * @returns {ExtractCommentsFunction} + */ + const buildComments = (terserOptions, extractedComments) => { + /** @type {{ [index: string]: ExtractCommentsCondition }} */ + const condition = {}; + let comments; + if (terserOptions.format) { + ({ + comments + } = terserOptions.format); + } else if (terserOptions.output) { + ({ + comments + } = terserOptions.output); + } + condition.preserve = typeof comments !== "undefined" ? comments : false; + if (typeof extractComments === "boolean" && extractComments) { + condition.extract = "some"; + } else if (typeof extractComments === "string" || extractComments instanceof RegExp) { + condition.extract = extractComments; + } else if (typeof extractComments === "function") { + condition.extract = extractComments; + } else if (extractComments && isObject(extractComments)) { + condition.extract = typeof extractComments.condition === "boolean" && extractComments.condition ? "some" : typeof extractComments.condition !== "undefined" ? extractComments.condition : "some"; + } else { + // No extract + // Preserve using "commentsOpts" or "some" + condition.preserve = typeof comments !== "undefined" ? comments : "some"; + condition.extract = false; + } + + // Ensure that both conditions are functions + ["preserve", "extract"].forEach(key => { + /** @type {undefined | string} */ + let regexStr; + /** @type {undefined | RegExp} */ + let regex; + switch (typeof condition[key]) { + case "boolean": + condition[key] = condition[key] ? () => true : () => false; + break; + case "function": + break; + case "string": + if (condition[key] === "all") { + condition[key] = () => true; + break; + } + if (condition[key] === "some") { + condition[key] = /** @type {ExtractCommentsFunction} */ + (astNode, comment) => (comment.type === "comment2" || comment.type === "comment1") && /@preserve|@lic|@cc_on|^\**!/i.test(comment.value); + break; + } + regexStr = /** @type {string} */condition[key]; + condition[key] = /** @type {ExtractCommentsFunction} */ + (astNode, comment) => new RegExp( /** @type {string} */regexStr).test(comment.value); + break; + default: + regex = /** @type {RegExp} */condition[key]; + condition[key] = /** @type {ExtractCommentsFunction} */ + (astNode, comment) => /** @type {RegExp} */regex.test(comment.value); + } + }); + + // Redefine the comments function to extract and preserve + // comments according to the two conditions + return (astNode, comment) => { + if ( /** @type {{ extract: ExtractCommentsFunction }} */ + condition.extract(astNode, comment)) { + const commentText = comment.type === "comment2" ? `/*${comment.value}*/` : `//${comment.value}`; + + // Don't include duplicate comments + if (!extractedComments.includes(commentText)) { + extractedComments.push(commentText); + } + } + return /** @type {{ preserve: ExtractCommentsFunction }} */condition.preserve(astNode, comment); + }; + }; + + /** + * @param {PredefinedOptions & TerserOptions} [terserOptions={}] + * @returns {TerserOptions & { sourceMap: undefined } & { compress: TerserCompressOptions } & ({ output: TerserFormatOptions & { beautify: boolean } } | { format: TerserFormatOptions & { beautify: boolean } })} + */ + const buildTerserOptions = (terserOptions = {}) => { + // Need deep copy objects to avoid https://github.com/terser/terser/issues/366 + return { + ...terserOptions, + compress: typeof terserOptions.compress === "boolean" ? terserOptions.compress ? {} : false : { + ...terserOptions.compress + }, + // ecma: terserOptions.ecma, + // ie8: terserOptions.ie8, + // keep_classnames: terserOptions.keep_classnames, + // keep_fnames: terserOptions.keep_fnames, + mangle: terserOptions.mangle == null ? true : typeof terserOptions.mangle === "boolean" ? terserOptions.mangle : { + ...terserOptions.mangle + }, + // module: terserOptions.module, + // nameCache: { ...terserOptions.toplevel }, + // the `output` option is deprecated + ...(terserOptions.format ? { + format: { + beautify: false, + ...terserOptions.format + } + } : { + output: { + beautify: false, + ...terserOptions.output + } + }), + parse: { + ...terserOptions.parse + }, + // safari10: terserOptions.safari10, + // Ignoring sourceMap from options + // eslint-disable-next-line no-undefined + sourceMap: undefined + // toplevel: terserOptions.toplevel + }; + }; + + // eslint-disable-next-line global-require + const { + minify + } = require("terser"); + // Copy `terser` options + const terserOptions = buildTerserOptions(minimizerOptions); + + // Let terser generate a SourceMap + if (sourceMap) { + // @ts-ignore + terserOptions.sourceMap = { + asObject: true + }; + } + + /** @type {ExtractedComments} */ + const extractedComments = []; + if (terserOptions.output) { + terserOptions.output.comments = buildComments(terserOptions, extractedComments); + } else if (terserOptions.format) { + terserOptions.format.comments = buildComments(terserOptions, extractedComments); + } + if (terserOptions.compress) { + // More optimizations + if (typeof terserOptions.compress.ecma === "undefined") { + terserOptions.compress.ecma = terserOptions.ecma; + } + + // https://github.com/webpack/webpack/issues/16135 + if (terserOptions.ecma === 5 && typeof terserOptions.compress.arrows === "undefined") { + terserOptions.compress.arrows = false; + } + } + const [[filename, code]] = Object.entries(input); + const result = await minify({ + [filename]: code + }, terserOptions); + return { + code: ( /** @type {string} **/result.code), + // @ts-ignore + // eslint-disable-next-line no-undefined + map: result.map ? ( /** @type {SourceMapInput} **/result.map) : undefined, + extractedComments + }; +} + +/** + * @returns {string | undefined} + */ +terserMinify.getMinimizerVersion = () => { + let packageJson; + try { + // eslint-disable-next-line global-require + packageJson = require("terser/package.json"); + } catch (error) { + // Ignore + } + return packageJson && packageJson.version; +}; + +/* istanbul ignore next */ +/** + * @param {Input} input + * @param {SourceMapInput | undefined} sourceMap + * @param {PredefinedOptions & CustomOptions} minimizerOptions + * @param {ExtractCommentsOptions | undefined} extractComments + * @return {Promise} + */ +async function uglifyJsMinify(input, sourceMap, minimizerOptions, extractComments) { + /** + * @param {any} value + * @returns {boolean} + */ + const isObject = value => { + const type = typeof value; + return value != null && (type === "object" || type === "function"); + }; + + /** + * @param {import("uglify-js").MinifyOptions & { sourceMap: undefined } & { output: import("uglify-js").OutputOptions & { beautify: boolean }}} uglifyJsOptions + * @param {ExtractedComments} extractedComments + * @returns {ExtractCommentsFunction} + */ + const buildComments = (uglifyJsOptions, extractedComments) => { + /** @type {{ [index: string]: ExtractCommentsCondition }} */ + const condition = {}; + const { + comments + } = uglifyJsOptions.output; + condition.preserve = typeof comments !== "undefined" ? comments : false; + if (typeof extractComments === "boolean" && extractComments) { + condition.extract = "some"; + } else if (typeof extractComments === "string" || extractComments instanceof RegExp) { + condition.extract = extractComments; + } else if (typeof extractComments === "function") { + condition.extract = extractComments; + } else if (extractComments && isObject(extractComments)) { + condition.extract = typeof extractComments.condition === "boolean" && extractComments.condition ? "some" : typeof extractComments.condition !== "undefined" ? extractComments.condition : "some"; + } else { + // No extract + // Preserve using "commentsOpts" or "some" + condition.preserve = typeof comments !== "undefined" ? comments : "some"; + condition.extract = false; + } + + // Ensure that both conditions are functions + ["preserve", "extract"].forEach(key => { + /** @type {undefined | string} */ + let regexStr; + /** @type {undefined | RegExp} */ + let regex; + switch (typeof condition[key]) { + case "boolean": + condition[key] = condition[key] ? () => true : () => false; + break; + case "function": + break; + case "string": + if (condition[key] === "all") { + condition[key] = () => true; + break; + } + if (condition[key] === "some") { + condition[key] = /** @type {ExtractCommentsFunction} */ + (astNode, comment) => (comment.type === "comment2" || comment.type === "comment1") && /@preserve|@lic|@cc_on|^\**!/i.test(comment.value); + break; + } + regexStr = /** @type {string} */condition[key]; + condition[key] = /** @type {ExtractCommentsFunction} */ + (astNode, comment) => new RegExp( /** @type {string} */regexStr).test(comment.value); + break; + default: + regex = /** @type {RegExp} */condition[key]; + condition[key] = /** @type {ExtractCommentsFunction} */ + (astNode, comment) => /** @type {RegExp} */regex.test(comment.value); + } + }); + + // Redefine the comments function to extract and preserve + // comments according to the two conditions + return (astNode, comment) => { + if ( /** @type {{ extract: ExtractCommentsFunction }} */ + condition.extract(astNode, comment)) { + const commentText = comment.type === "comment2" ? `/*${comment.value}*/` : `//${comment.value}`; + + // Don't include duplicate comments + if (!extractedComments.includes(commentText)) { + extractedComments.push(commentText); + } + } + return /** @type {{ preserve: ExtractCommentsFunction }} */condition.preserve(astNode, comment); + }; + }; + + /** + * @param {PredefinedOptions & import("uglify-js").MinifyOptions} [uglifyJsOptions={}] + * @returns {import("uglify-js").MinifyOptions & { sourceMap: undefined } & { output: import("uglify-js").OutputOptions & { beautify: boolean }}} + */ + const buildUglifyJsOptions = (uglifyJsOptions = {}) => { + // eslint-disable-next-line no-param-reassign + delete minimizerOptions.ecma; + // eslint-disable-next-line no-param-reassign + delete minimizerOptions.module; + + // Need deep copy objects to avoid https://github.com/terser/terser/issues/366 + return { + ...uglifyJsOptions, + // warnings: uglifyJsOptions.warnings, + parse: { + ...uglifyJsOptions.parse + }, + compress: typeof uglifyJsOptions.compress === "boolean" ? uglifyJsOptions.compress : { + ...uglifyJsOptions.compress + }, + mangle: uglifyJsOptions.mangle == null ? true : typeof uglifyJsOptions.mangle === "boolean" ? uglifyJsOptions.mangle : { + ...uglifyJsOptions.mangle + }, + output: { + beautify: false, + ...uglifyJsOptions.output + }, + // Ignoring sourceMap from options + // eslint-disable-next-line no-undefined + sourceMap: undefined + // toplevel: uglifyJsOptions.toplevel + // nameCache: { ...uglifyJsOptions.toplevel }, + // ie8: uglifyJsOptions.ie8, + // keep_fnames: uglifyJsOptions.keep_fnames, + }; + }; + + // eslint-disable-next-line global-require, import/no-extraneous-dependencies + const { + minify + } = require("uglify-js"); + + // Copy `uglify-js` options + const uglifyJsOptions = buildUglifyJsOptions(minimizerOptions); + + // Let terser generate a SourceMap + if (sourceMap) { + // @ts-ignore + uglifyJsOptions.sourceMap = true; + } + + /** @type {ExtractedComments} */ + const extractedComments = []; + + // @ts-ignore + uglifyJsOptions.output.comments = buildComments(uglifyJsOptions, extractedComments); + const [[filename, code]] = Object.entries(input); + const result = await minify({ + [filename]: code + }, uglifyJsOptions); + return { + code: result.code, + // eslint-disable-next-line no-undefined + map: result.map ? JSON.parse(result.map) : undefined, + errors: result.error ? [result.error] : [], + warnings: result.warnings || [], + extractedComments + }; +} + +/** + * @returns {string | undefined} + */ +uglifyJsMinify.getMinimizerVersion = () => { + let packageJson; + try { + // eslint-disable-next-line global-require, import/no-extraneous-dependencies + packageJson = require("uglify-js/package.json"); + } catch (error) { + // Ignore + } + return packageJson && packageJson.version; +}; + +/* istanbul ignore next */ +/** + * @param {Input} input + * @param {SourceMapInput | undefined} sourceMap + * @param {PredefinedOptions & CustomOptions} minimizerOptions + * @return {Promise} + */ +async function swcMinify(input, sourceMap, minimizerOptions) { + /** + * @param {PredefinedOptions & import("@swc/core").JsMinifyOptions} [swcOptions={}] + * @returns {import("@swc/core").JsMinifyOptions & { sourceMap: undefined } & { compress: import("@swc/core").TerserCompressOptions }} + */ + const buildSwcOptions = (swcOptions = {}) => { + // Need deep copy objects to avoid https://github.com/terser/terser/issues/366 + return { + ...swcOptions, + compress: typeof swcOptions.compress === "boolean" ? swcOptions.compress ? {} : false : { + ...swcOptions.compress + }, + mangle: swcOptions.mangle == null ? true : typeof swcOptions.mangle === "boolean" ? swcOptions.mangle : { + ...swcOptions.mangle + }, + // ecma: swcOptions.ecma, + // keep_classnames: swcOptions.keep_classnames, + // keep_fnames: swcOptions.keep_fnames, + // module: swcOptions.module, + // safari10: swcOptions.safari10, + // toplevel: swcOptions.toplevel + // eslint-disable-next-line no-undefined + sourceMap: undefined + }; + }; + + // eslint-disable-next-line import/no-extraneous-dependencies, global-require + const swc = require("@swc/core"); + // Copy `swc` options + const swcOptions = buildSwcOptions(minimizerOptions); + + // Let `swc` generate a SourceMap + if (sourceMap) { + // @ts-ignore + swcOptions.sourceMap = true; + } + if (swcOptions.compress) { + // More optimizations + if (typeof swcOptions.compress.ecma === "undefined") { + swcOptions.compress.ecma = swcOptions.ecma; + } + + // https://github.com/webpack/webpack/issues/16135 + if (swcOptions.ecma === 5 && typeof swcOptions.compress.arrows === "undefined") { + swcOptions.compress.arrows = false; + } + } + const [[filename, code]] = Object.entries(input); + const result = await swc.minify(code, swcOptions); + let map; + if (result.map) { + map = JSON.parse(result.map); + + // TODO workaround for swc because `filename` is not preset as in `swc` signature as for `terser` + map.sources = [filename]; + delete map.sourcesContent; + } + return { + code: result.code, + map + }; +} + +/** + * @returns {string | undefined} + */ +swcMinify.getMinimizerVersion = () => { + let packageJson; + try { + // eslint-disable-next-line global-require, import/no-extraneous-dependencies + packageJson = require("@swc/core/package.json"); + } catch (error) { + // Ignore + } + return packageJson && packageJson.version; +}; + +/* istanbul ignore next */ +/** + * @param {Input} input + * @param {SourceMapInput | undefined} sourceMap + * @param {PredefinedOptions & CustomOptions} minimizerOptions + * @return {Promise} + */ +async function esbuildMinify(input, sourceMap, minimizerOptions) { + /** + * @param {PredefinedOptions & import("esbuild").TransformOptions} [esbuildOptions={}] + * @returns {import("esbuild").TransformOptions} + */ + const buildEsbuildOptions = (esbuildOptions = {}) => { + // eslint-disable-next-line no-param-reassign + delete esbuildOptions.ecma; + if (esbuildOptions.module) { + // eslint-disable-next-line no-param-reassign + esbuildOptions.format = "esm"; + } + + // eslint-disable-next-line no-param-reassign + delete esbuildOptions.module; + + // Need deep copy objects to avoid https://github.com/terser/terser/issues/366 + return { + minify: true, + legalComments: "inline", + ...esbuildOptions, + sourcemap: false + }; + }; + + // eslint-disable-next-line import/no-extraneous-dependencies, global-require + const esbuild = require("esbuild"); + + // Copy `esbuild` options + const esbuildOptions = buildEsbuildOptions(minimizerOptions); + + // Let `esbuild` generate a SourceMap + if (sourceMap) { + esbuildOptions.sourcemap = true; + esbuildOptions.sourcesContent = false; + } + const [[filename, code]] = Object.entries(input); + esbuildOptions.sourcefile = filename; + const result = await esbuild.transform(code, esbuildOptions); + return { + code: result.code, + // eslint-disable-next-line no-undefined + map: result.map ? JSON.parse(result.map) : undefined, + warnings: result.warnings.length > 0 ? result.warnings.map(item => { + const plugin = item.pluginName ? `\nPlugin Name: ${item.pluginName}` : ""; + const location = item.location ? `\n\n${item.location.file}:${item.location.line}:${item.location.column}:\n ${item.location.line} | ${item.location.lineText}\n\nSuggestion: ${item.location.suggestion}` : ""; + const notes = item.notes.length > 0 ? `\n\nNotes:\n${item.notes.map(note => `${note.location ? `[${note.location.file}:${note.location.line}:${note.location.column}] ` : ""}${note.text}${note.location ? `\nSuggestion: ${note.location.suggestion}` : ""}${note.location ? `\nLine text:\n${note.location.lineText}\n` : ""}`).join("\n")}` : ""; + return `${item.text} [${item.id}]${plugin}${location}${item.detail ? `\nDetails:\n${item.detail}` : ""}${notes}`; + }) : [] + }; +} + +/** + * @returns {string | undefined} + */ +esbuildMinify.getMinimizerVersion = () => { + let packageJson; + try { + // eslint-disable-next-line global-require, import/no-extraneous-dependencies + packageJson = require("esbuild/package.json"); + } catch (error) { + // Ignore + } + return packageJson && packageJson.version; +}; + +/** + * @template T + * @param fn {(function(): any) | undefined} + * @returns {function(): T} + */ +function memoize(fn) { + let cache = false; + /** @type {T} */ + let result; + return () => { + if (cache) { + return result; + } + result = /** @type {function(): any} */fn(); + cache = true; + // Allow to clean up memory for fn + // and all dependent resources + // eslint-disable-next-line no-undefined, no-param-reassign + fn = undefined; + return result; + }; +} +module.exports = { + throttleAll, + memoize, + terserMinify, + uglifyJsMinify, + swcMinify, + esbuildMinify +}; \ No newline at end of file diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/LICENSE b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/LICENSE new file mode 100644 index 0000000..90139aa --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Evgeny Poberezkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/README.md b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/README.md new file mode 100644 index 0000000..1964a22 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/README.md @@ -0,0 +1,836 @@ +# ajv-keywords + +Custom JSON-Schema keywords for [Ajv](https://github.com/epoberezkin/ajv) validator + +[![Build Status](https://travis-ci.org/ajv-validator/ajv-keywords.svg?branch=master)](https://travis-ci.org/ajv-validator/ajv-keywords) +[![npm](https://img.shields.io/npm/v/ajv-keywords.svg)](https://www.npmjs.com/package/ajv-keywords) +[![npm downloads](https://img.shields.io/npm/dm/ajv-keywords.svg)](https://www.npmjs.com/package/ajv-keywords) +[![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv-keywords/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv-keywords?branch=master) +[![Dependabot](https://api.dependabot.com/badges/status?host=github&repo=ajv-validator/ajv-keywords)](https://app.dependabot.com/accounts/ajv-validator/repos/60477053) +[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) + + +## Contents + +- [Install](#install) +- [Usage](#usage) +- [Keywords](#keywords) + - [Types](#types) + - [typeof](#typeof) + - [instanceof](#instanceof) + - [Keywords for numbers](#keywords-for-numbers) + - [range and exclusiveRange](#range-and-exclusiverange) + - [Keywords for strings](#keywords-for-strings) + - [regexp](#regexp) + - [formatMaximum / formatMinimum and formatExclusiveMaximum / formatExclusiveMinimum](#formatmaximum--formatminimum-and-formatexclusivemaximum--formatexclusiveminimum) + - [transform](#transform)\* + - [Keywords for arrays](#keywords-for-arrays) + - [uniqueItemProperties](#uniqueitemproperties) + - [Keywords for objects](#keywords-for-objects) + - [allRequired](#allrequired) + - [anyRequired](#anyrequired) + - [oneRequired](#onerequired) + - [patternRequired](#patternrequired) + - [prohibited](#prohibited) + - [deepProperties](#deepproperties) + - [deepRequired](#deeprequired) + - [Compound keywords](#compound-keywords) + - [switch](#switch) (deprecated) + - [select/selectCases/selectDefault](#selectselectcasesselectdefault) (BETA) + - [Keywords for all types](#keywords-for-all-types) + - [dynamicDefaults](#dynamicdefaults)\* +- [Security contact](#security-contact) +- [Open-source software support](#open-source-software-support) +- [License](#license) + +\* - keywords that modify data + + +## Install + +``` +npm install ajv-keywords +``` + + +## Usage + +To add all available keywords: + +```javascript +var Ajv = require('ajv'); +var ajv = new Ajv; +require('ajv-keywords')(ajv); + +ajv.validate({ instanceof: 'RegExp' }, /.*/); // true +ajv.validate({ instanceof: 'RegExp' }, '.*'); // false +``` + +To add a single keyword: + +```javascript +require('ajv-keywords')(ajv, 'instanceof'); +``` + +To add multiple keywords: + +```javascript +require('ajv-keywords')(ajv, ['typeof', 'instanceof']); +``` + +To add a single keyword in browser (to avoid adding unused code): + +```javascript +require('ajv-keywords/keywords/instanceof')(ajv); +``` + + +## Keywords + +### Types + +#### `typeof` + +Based on JavaScript `typeof` operation. + +The value of the keyword should be a string (`"undefined"`, `"string"`, `"number"`, `"object"`, `"function"`, `"boolean"` or `"symbol"`) or array of strings. + +To pass validation the result of `typeof` operation on the value should be equal to the string (or one of the strings in the array). + +``` +ajv.validate({ typeof: 'undefined' }, undefined); // true +ajv.validate({ typeof: 'undefined' }, null); // false +ajv.validate({ typeof: ['undefined', 'object'] }, null); // true +``` + + +#### `instanceof` + +Based on JavaScript `instanceof` operation. + +The value of the keyword should be a string (`"Object"`, `"Array"`, `"Function"`, `"Number"`, `"String"`, `"Date"`, `"RegExp"`, `"Promise"` or `"Buffer"`) or array of strings. + +To pass validation the result of `data instanceof ...` operation on the value should be true: + +``` +ajv.validate({ instanceof: 'Array' }, []); // true +ajv.validate({ instanceof: 'Array' }, {}); // false +ajv.validate({ instanceof: ['Array', 'Function'] }, function(){}); // true +``` + +You can add your own constructor function to be recognised by this keyword: + +```javascript +function MyClass() {} +var instanceofDefinition = require('ajv-keywords').get('instanceof').definition; +// or require('ajv-keywords/keywords/instanceof').definition; +instanceofDefinition.CONSTRUCTORS.MyClass = MyClass; + +ajv.validate({ instanceof: 'MyClass' }, new MyClass); // true +``` + + +### Keywords for numbers + +#### `range` and `exclusiveRange` + +Syntax sugar for the combination of minimum and maximum keywords, also fails schema compilation if there are no numbers in the range. + +The value of this keyword must be the array consisting of two numbers, the second must be greater or equal than the first one. + +If the validated value is not a number the validation passes, otherwise to pass validation the value should be greater (or equal) than the first number and smaller (or equal) than the second number in the array. If `exclusiveRange` keyword is present in the same schema and its value is true, the validated value must not be equal to the range boundaries. + +```javascript +var schema = { range: [1, 3] }; +ajv.validate(schema, 1); // true +ajv.validate(schema, 2); // true +ajv.validate(schema, 3); // true +ajv.validate(schema, 0.99); // false +ajv.validate(schema, 3.01); // false + +var schema = { range: [1, 3], exclusiveRange: true }; +ajv.validate(schema, 1.01); // true +ajv.validate(schema, 2); // true +ajv.validate(schema, 2.99); // true +ajv.validate(schema, 1); // false +ajv.validate(schema, 3); // false +``` + + +### Keywords for strings + +#### `regexp` + +This keyword allows to use regular expressions with flags in schemas (the standard `pattern` keyword does not support flags). + +This keyword applies only to strings. If the data is not a string, the validation succeeds. + +The value of this keyword can be either a string (the result of `regexp.toString()`) or an object with the properties `pattern` and `flags` (the same strings that should be passed to RegExp constructor). + +```javascript +var schema = { + type: 'object', + properties: { + foo: { regexp: '/foo/i' }, + bar: { regexp: { pattern: 'bar', flags: 'i' } } + } +}; + +var validData = { + foo: 'Food', + bar: 'Barmen' +}; + +var invalidData = { + foo: 'fog', + bar: 'bad' +}; +``` + + +#### `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` + +These keywords allow to define minimum/maximum constraints when the format keyword defines ordering. + +These keywords apply only to strings. If the data is not a string, the validation succeeds. + +The value of keyword `formatMaximum` (`formatMinimum`) should be a string. This value is the maximum (minimum) allowed value for the data to be valid as determined by `format` keyword. If `format` is not present schema compilation will throw exception. + +When this keyword is added, it defines comparison rules for formats `"date"`, `"time"` and `"date-time"`. Custom formats also can have comparison rules. See [addFormat](https://github.com/epoberezkin/ajv#api-addformat) method. + +The value of keyword `formatExclusiveMaximum` (`formatExclusiveMinimum`) should be a boolean value. These keyword cannot be used without `formatMaximum` (`formatMinimum`). If this keyword value is equal to `true`, the data to be valid should not be equal to the value in `formatMaximum` (`formatMinimum`) keyword. + +```javascript +require('ajv-keywords')(ajv, ['formatMinimum', 'formatMaximum']); + +var schema = { + format: 'date', + formatMinimum: '2016-02-06', + formatMaximum: '2016-12-27', + formatExclusiveMaximum: true +} + +var validDataList = ['2016-02-06', '2016-12-26', 1]; + +var invalidDataList = ['2016-02-05', '2016-12-27', 'abc']; +``` + + +#### `transform` + +This keyword allows a string to be modified before validation. + +These keywords apply only to strings. If the data is not a string, the transform is skipped. + +There are limitation due to how ajv is written: +- a stand alone string cannot be transformed. ie `data = 'a'; ajv.validate(schema, data);` +- currently cannot work with `ajv-pack` + +**Supported options:** +- `trim`: remove whitespace from start and end +- `trimLeft`: remove whitespace from start +- `trimRight`: remove whitespace from end +- `toLowerCase`: case string to all lower case +- `toUpperCase`: case string to all upper case +- `toEnumCase`: case string to match case in schema + +Options are applied in the order they are listed. + +Note: `toEnumCase` requires that all allowed values are unique when case insensitive. + +**Example: multiple options** +```javascript +require('ajv-keywords')(ajv, ['transform']); + +var schema = { + type: 'array', + items: { + type:'string', + transform:['trim','toLowerCase'] + } +}; + +var data = [' MixCase ']; +ajv.validate(schema, data); +console.log(data); // ['mixcase'] + +``` + +**Example: `enumcase`** +```javascript +require('ajv-keywords')(ajv, ['transform']); + +var schema = { + type: 'array', + items: { + type:'string', + transform:['trim','toEnumCase'], + enum:['pH'] + } +}; + +var data = ['ph',' Ph','PH','pH ']; +ajv.validate(schema, data); +console.log(data); // ['pH','pH','pH','pH'] +``` + + +### Keywords for arrays + +#### `uniqueItemProperties` + +The keyword allows to check that some properties in array items are unique. + +This keyword applies only to arrays. If the data is not an array, the validation succeeds. + +The value of this keyword must be an array of strings - property names that should have unique values across all items. + +```javascript +var schema = { uniqueItemProperties: [ "id", "name" ] }; + +var validData = [ + { id: 1 }, + { id: 2 }, + { id: 3 } +]; + +var invalidData1 = [ + { id: 1 }, + { id: 1 }, // duplicate "id" + { id: 3 } +]; + +var invalidData2 = [ + { id: 1, name: "taco" }, + { id: 2, name: "taco" }, // duplicate "name" + { id: 3, name: "salsa" } +]; +``` + +This keyword is contributed by [@blainesch](https://github.com/blainesch). + + +### Keywords for objects + +#### `allRequired` + +This keyword allows to require the presence of all properties used in `properties` keyword in the same schema object. + +This keyword applies only to objects. If the data is not an object, the validation succeeds. + +The value of this keyword must be boolean. + +If the value of the keyword is `false`, the validation succeeds. + +If the value of the keyword is `true`, the validation succeeds if the data contains all properties defined in `properties` keyword (in the same schema object). + +If the `properties` keyword is not present in the same schema object, schema compilation will throw exception. + +```javascript +var schema = { + properties: { + foo: {type: 'number'}, + bar: {type: 'number'} + } + allRequired: true +}; + +var validData = { foo: 1, bar: 2 }; +var alsoValidData = { foo: 1, bar: 2, baz: 3 }; + +var invalidDataList = [ {}, { foo: 1 }, { bar: 2 } ]; +``` + + +#### `anyRequired` + +This keyword allows to require the presence of any (at least one) property from the list. + +This keyword applies only to objects. If the data is not an object, the validation succeeds. + +The value of this keyword must be an array of strings, each string being a property name. For data object to be valid at least one of the properties in this array should be present in the object. + +```javascript +var schema = { + anyRequired: ['foo', 'bar'] +}; + +var validData = { foo: 1 }; +var alsoValidData = { foo: 1, bar: 2 }; + +var invalidDataList = [ {}, { baz: 3 } ]; +``` + + +#### `oneRequired` + +This keyword allows to require the presence of only one property from the list. + +This keyword applies only to objects. If the data is not an object, the validation succeeds. + +The value of this keyword must be an array of strings, each string being a property name. For data object to be valid exactly one of the properties in this array should be present in the object. + +```javascript +var schema = { + oneRequired: ['foo', 'bar'] +}; + +var validData = { foo: 1 }; +var alsoValidData = { bar: 2, baz: 3 }; + +var invalidDataList = [ {}, { baz: 3 }, { foo: 1, bar: 2 } ]; +``` + + +#### `patternRequired` + +This keyword allows to require the presence of properties that match some pattern(s). + +This keyword applies only to objects. If the data is not an object, the validation succeeds. + +The value of this keyword should be an array of strings, each string being a regular expression. For data object to be valid each regular expression in this array should match at least one property name in the data object. + +If the array contains multiple regular expressions, more than one expression can match the same property name. + +```javascript +var schema = { patternRequired: [ 'f.*o', 'b.*r' ] }; + +var validData = { foo: 1, bar: 2 }; +var alsoValidData = { foobar: 3 }; + +var invalidDataList = [ {}, { foo: 1 }, { bar: 2 } ]; +``` + + +#### `prohibited` + +This keyword allows to prohibit that any of the properties in the list is present in the object. + +This keyword applies only to objects. If the data is not an object, the validation succeeds. + +The value of this keyword should be an array of strings, each string being a property name. For data object to be valid none of the properties in this array should be present in the object. + +``` +var schema = { prohibited: ['foo', 'bar']}; + +var validData = { baz: 1 }; +var alsoValidData = {}; + +var invalidDataList = [ + { foo: 1 }, + { bar: 2 }, + { foo: 1, bar: 2} +]; +``` + +__Please note__: `{prohibited: ['foo', 'bar']}` is equivalent to `{not: {anyRequired: ['foo', 'bar']}}` (i.e. it has the same validation result for any data). + + +#### `deepProperties` + +This keyword allows to validate deep properties (identified by JSON pointers). + +This keyword applies only to objects. If the data is not an object, the validation succeeds. + +The value should be an object, where keys are JSON pointers to the data, starting from the current position in data, and the values are JSON schemas. For data object to be valid the value of each JSON pointer should be valid according to the corresponding schema. + +```javascript +var schema = { + type: 'object', + deepProperties: { + "/users/1/role": { "enum": ["admin"] } + } +}; + +var validData = { + users: [ + {}, + { + id: 123, + role: 'admin' + } + ] +}; + +var alsoValidData = { + users: { + "1": { + id: 123, + role: 'admin' + } + } +}; + +var invalidData = { + users: [ + {}, + { + id: 123, + role: 'user' + } + ] +}; + +var alsoInvalidData = { + users: { + "1": { + id: 123, + role: 'user' + } + } +}; +``` + + +#### `deepRequired` + +This keyword allows to check that some deep properties (identified by JSON pointers) are available. + +This keyword applies only to objects. If the data is not an object, the validation succeeds. + +The value should be an array of JSON pointers to the data, starting from the current position in data. For data object to be valid each JSON pointer should be some existing part of the data. + +```javascript +var schema = { + type: 'object', + deepRequired: ["/users/1/role"] +}; + +var validData = { + users: [ + {}, + { + id: 123, + role: 'admin' + } + ] +}; + +var invalidData = { + users: [ + {}, + { + id: 123 + } + ] +}; +``` + +See [json-schema-org/json-schema-spec#203](https://github.com/json-schema-org/json-schema-spec/issues/203#issue-197211916) for an example of the equivalent schema without `deepRequired` keyword. + + +### Compound keywords + +#### `switch` (deprecated) + +__Please note__: this keyword is provided to preserve backward compatibility with previous versions of Ajv. It is strongly recommended to use `if`/`then`/`else` keywords instead, as they have been added to the draft-07 of JSON Schema specification. + +This keyword allows to perform advanced conditional validation. + +The value of the keyword is the array of if/then clauses. Each clause is the object with the following properties: + +- `if` (optional) - the value is JSON-schema +- `then` (required) - the value is JSON-schema or boolean +- `continue` (optional) - the value is boolean + +The validation process is dynamic; all clauses are executed sequentially in the following way: + +1. `if`: + 1. `if` property is JSON-schema according to which the data is: + 1. valid => go to step 2. + 2. invalid => go to the NEXT clause, if this was the last clause the validation of `switch` SUCCEEDS. + 2. `if` property is absent => go to step 2. +2. `then`: + 1. `then` property is `true` or it is JSON-schema according to which the data is valid => go to step 3. + 2. `then` property is `false` or it is JSON-schema according to which the data is invalid => the validation of `switch` FAILS. +3. `continue`: + 1. `continue` property is `true` => go to the NEXT clause, if this was the last clause the validation of `switch` SUCCEEDS. + 2. `continue` property is `false` or absent => validation of `switch` SUCCEEDS. + +```javascript +require('ajv-keywords')(ajv, 'switch'); + +var schema = { + type: 'array', + items: { + type: 'integer', + 'switch': [ + { if: { not: { minimum: 1 } }, then: false }, + { if: { maximum: 10 }, then: true }, + { if: { maximum: 100 }, then: { multipleOf: 10 } }, + { if: { maximum: 1000 }, then: { multipleOf: 100 } }, + { then: false } + ] + } +}; + +var validItems = [1, 5, 10, 20, 50, 100, 200, 500, 1000]; + +var invalidItems = [1, 0, 2000, 11, 57, 123, 'foo']; +``` + +The above schema is equivalent to (for example): + +```javascript +{ + type: 'array', + items: { + type: 'integer', + if: { minimum: 1, maximum: 10 }, + then: true, + else: { + if: { maximum: 100 }, + then: { multipleOf: 10 }, + else: { + if: { maximum: 1000 }, + then: { multipleOf: 100 }, + else: false + } + } + } +} +``` + + +#### `select`/`selectCases`/`selectDefault` + +These keywords allow to choose the schema to validate the data based on the value of some property in the validated data. + +These keywords must be present in the same schema object (`selectDefault` is optional). + +The value of `select` keyword should be a [$data reference](https://github.com/epoberezkin/ajv/tree/5.0.2-beta.0#data-reference) that points to any primitive JSON type (string, number, boolean or null) in the data that is validated. You can also use a constant of primitive type as the value of this keyword (e.g., for debugging purposes). + +The value of `selectCases` keyword must be an object where each property name is a possible string representation of the value of `select` keyword and each property value is a corresponding schema (from draft-06 it can be boolean) that must be used to validate the data. + +The value of `selectDefault` keyword is a schema (from draft-06 it can be boolean) that must be used to validate the data in case `selectCases` has no key equal to the stringified value of `select` keyword. + +The validation succeeds in one of the following cases: +- the validation of data using selected schema succeeds, +- none of the schemas is selected for validation, +- the value of select is undefined (no property in the data that the data reference points to). + +If `select` value (in data) is not a primitive type the validation fails. + +__Please note__: these keywords require Ajv `$data` option to support [$data reference](https://github.com/epoberezkin/ajv/tree/5.0.2-beta.0#data-reference). + + +```javascript +require('ajv-keywords')(ajv, 'select'); + +var schema = { + type: object, + required: ['kind'], + properties: { + kind: { type: 'string' } + }, + select: { $data: '0/kind' }, + selectCases: { + foo: { + required: ['foo'], + properties: { + kind: {}, + foo: { type: 'string' } + }, + additionalProperties: false + }, + bar: { + required: ['bar'], + properties: { + kind: {}, + bar: { type: 'number' } + }, + additionalProperties: false + } + }, + selectDefault: { + propertyNames: { + not: { enum: ['foo', 'bar'] } + } + } +}; + +var validDataList = [ + { kind: 'foo', foo: 'any' }, + { kind: 'bar', bar: 1 }, + { kind: 'anything_else', not_bar_or_foo: 'any value' } +]; + +var invalidDataList = [ + { kind: 'foo' }, // no propery foo + { kind: 'bar' }, // no propery bar + { kind: 'foo', foo: 'any', another: 'any value' }, // additional property + { kind: 'bar', bar: 1, another: 'any value' }, // additional property + { kind: 'anything_else', foo: 'any' } // property foo not allowed + { kind: 'anything_else', bar: 1 } // property bar not allowed +]; +``` + +__Please note__: the current implementation is BETA. It does not allow using relative URIs in $ref keywords in schemas in `selectCases` and `selectDefault` that point outside of these schemas. The workaround is to use absolute URIs (that can point to any (sub-)schema added to Ajv, including those inside the current root schema where `select` is used). See [tests](https://github.com/epoberezkin/ajv-keywords/blob/v2.0.0/spec/tests/select.json#L314). + + +### Keywords for all types + +#### `dynamicDefaults` + +This keyword allows to assign dynamic defaults to properties, such as timestamps, unique IDs etc. + +This keyword only works if `useDefaults` options is used and not inside `anyOf` keywords etc., in the same way as [default keyword treated by Ajv](https://github.com/epoberezkin/ajv#assigning-defaults). + +The keyword should be added on the object level. Its value should be an object with each property corresponding to a property name, in the same way as in standard `properties` keyword. The value of each property can be: + +- an identifier of default function (a string) +- an object with properties `func` (an identifier) and `args` (an object with parameters that will be passed to this function during schema compilation - see examples). + +The properties used in `dynamicDefaults` should not be added to `required` keyword (or validation will fail), because unlike `default` this keyword is processed after validation. + +There are several predefined dynamic default functions: + +- `"timestamp"` - current timestamp in milliseconds +- `"datetime"` - current date and time as string (ISO, valid according to `date-time` format) +- `"date"` - current date as string (ISO, valid according to `date` format) +- `"time"` - current time as string (ISO, valid according to `time` format) +- `"random"` - pseudo-random number in [0, 1) interval +- `"randomint"` - pseudo-random integer number. If string is used as a property value, the function will randomly return 0 or 1. If object `{ func: 'randomint', args: { max: N } }` is used then the default will be an integer number in [0, N) interval. +- `"seq"` - sequential integer number starting from 0. If string is used as a property value, the default sequence will be used. If object `{ func: 'seq', args: { name: 'foo'} }` is used then the sequence with name `"foo"` will be used. Sequences are global, even if different ajv instances are used. + +```javascript +var schema = { + type: 'object', + dynamicDefaults: { + ts: 'datetime', + r: { func: 'randomint', args: { max: 100 } }, + id: { func: 'seq', args: { name: 'id' } } + }, + properties: { + ts: { + type: 'string', + format: 'date-time' + }, + r: { + type: 'integer', + minimum: 0, + exclusiveMaximum: 100 + }, + id: { + type: 'integer', + minimum: 0 + } + } +}; + +var data = {}; +ajv.validate(data); // true +data; // { ts: '2016-12-01T22:07:28.829Z', r: 25, id: 0 } + +var data1 = {}; +ajv.validate(data1); // true +data1; // { ts: '2016-12-01T22:07:29.832Z', r: 68, id: 1 } + +ajv.validate(data1); // true +data1; // didn't change, as all properties were defined +``` + +When using the `useDefaults` option value `"empty"`, properties and items equal to `null` or `""` (empty string) will be considered missing and assigned defaults. Use the `allOf` [compound keyword](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#compound-keywords) to execute `dynamicDefaults` before validation. + +```javascript +var schema = { + allOf: [ + { + dynamicDefaults: { + ts: 'datetime', + r: { func: 'randomint', args: { min: 5, max: 100 } }, + id: { func: 'seq', args: { name: 'id' } } + } + }, + { + type: 'object', + properties: { + ts: { + type: 'string' + }, + r: { + type: 'number', + minimum: 5, + exclusiveMaximum: 100 + }, + id: { + type: 'integer', + minimum: 0 + } + } + } + ] +}; + +var data = { ts: '', r: null }; +ajv.validate(data); // true +data; // { ts: '2016-12-01T22:07:28.829Z', r: 25, id: 0 } +``` + +You can add your own dynamic default function to be recognised by this keyword: + +```javascript +var uuid = require('uuid'); + +function uuidV4() { return uuid.v4(); } + +var definition = require('ajv-keywords').get('dynamicDefaults').definition; +// or require('ajv-keywords/keywords/dynamicDefaults').definition; +definition.DEFAULTS.uuid = uuidV4; + +var schema = { + dynamicDefaults: { id: 'uuid' }, + properties: { id: { type: 'string', format: 'uuid' } } +}; + +var data = {}; +ajv.validate(schema, data); // true +data; // { id: 'a1183fbe-697b-4030-9bcc-cfeb282a9150' }; + +var data1 = {}; +ajv.validate(schema, data1); // true +data1; // { id: '5b008de7-1669-467a-a5c6-70fa244d7209' } +``` + +You also can define dynamic default that accepts parameters, e.g. version of uuid: + +```javascript +var uuid = require('uuid'); + +function getUuid(args) { + var version = 'v' + (arvs && args.v || 4); + return function() { + return uuid[version](); + }; +} + +var definition = require('ajv-keywords').get('dynamicDefaults').definition; +definition.DEFAULTS.uuid = getUuid; + +var schema = { + dynamicDefaults: { + id1: 'uuid', // v4 + id2: { func: 'uuid', v: 4 }, // v4 + id3: { func: 'uuid', v: 1 } // v1 + } +}; +``` + + +## Security contact + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. + +Please do NOT report security vulnerabilities via GitHub issues. + + +## Open-source software support + +Ajv-keywords is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv-keywords?utm_source=npm-ajv-keywords&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers. + + +## License + +[MIT](https://github.com/epoberezkin/ajv-keywords/blob/master/LICENSE) diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/ajv-keywords.d.ts b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/ajv-keywords.d.ts new file mode 100644 index 0000000..2d562ee --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/ajv-keywords.d.ts @@ -0,0 +1,7 @@ +declare module 'ajv-keywords' { + import { Ajv } from 'ajv'; + + function keywords(ajv: Ajv, include?: string | string[]): Ajv; + + export = keywords; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/index.js b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/index.js new file mode 100644 index 0000000..07a8eda --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/index.js @@ -0,0 +1,35 @@ +'use strict'; + +var KEYWORDS = require('./keywords'); + +module.exports = defineKeywords; + + +/** + * Defines one or several keywords in ajv instance + * @param {Ajv} ajv validator instance + * @param {String|Array|undefined} keyword keyword(s) to define + * @return {Ajv} ajv instance (for chaining) + */ +function defineKeywords(ajv, keyword) { + if (Array.isArray(keyword)) { + for (var i=0; i d2) return 1; + if (d1 < d2) return -1; + if (d1 === d2) return 0; +} + + +function compareTime(t1, t2) { + if (!(t1 && t2)) return; + t1 = t1.match(TIME); + t2 = t2.match(TIME); + if (!(t1 && t2)) return; + t1 = t1[1] + t1[2] + t1[3] + (t1[4]||''); + t2 = t2[1] + t2[2] + t2[3] + (t2[4]||''); + if (t1 > t2) return 1; + if (t1 < t2) return -1; + if (t1 === t2) return 0; +} + + +function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return; + dt1 = dt1.split(DATE_TIME_SEPARATOR); + dt2 = dt2.split(DATE_TIME_SEPARATOR); + var res = compareDate(dt1[0], dt2[0]); + if (res === undefined) return; + return res || compareTime(dt1[1], dt2[1]); +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/_util.js b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/_util.js new file mode 100644 index 0000000..dd52df7 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/_util.js @@ -0,0 +1,15 @@ +'use strict'; + +module.exports = { + metaSchemaRef: metaSchemaRef +}; + +var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema'; + +function metaSchemaRef(ajv) { + var defaultMeta = ajv._opts.defaultMeta; + if (typeof defaultMeta == 'string') return { $ref: defaultMeta }; + if (ajv.getSchema(META_SCHEMA_ID)) return { $ref: META_SCHEMA_ID }; + console.warn('meta schema not defined'); + return {}; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/allRequired.js b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/allRequired.js new file mode 100644 index 0000000..afc73eb --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/allRequired.js @@ -0,0 +1,18 @@ +'use strict'; + +module.exports = function defFunc(ajv) { + defFunc.definition = { + type: 'object', + macro: function (schema, parentSchema) { + if (!schema) return true; + var properties = Object.keys(parentSchema.properties); + if (properties.length == 0) return true; + return {required: properties}; + }, + metaSchema: {type: 'boolean'}, + dependencies: ['properties'] + }; + + ajv.addKeyword('allRequired', defFunc.definition); + return ajv; +}; diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/anyRequired.js b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/anyRequired.js new file mode 100644 index 0000000..acc55a9 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/anyRequired.js @@ -0,0 +1,24 @@ +'use strict'; + +module.exports = function defFunc(ajv) { + defFunc.definition = { + type: 'object', + macro: function (schema) { + if (schema.length == 0) return true; + if (schema.length == 1) return {required: schema}; + var schemas = schema.map(function (prop) { + return {required: [prop]}; + }); + return {anyOf: schemas}; + }, + metaSchema: { + type: 'array', + items: { + type: 'string' + } + } + }; + + ajv.addKeyword('anyRequired', defFunc.definition); + return ajv; +}; diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/deepProperties.js b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/deepProperties.js new file mode 100644 index 0000000..e5aff60 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/deepProperties.js @@ -0,0 +1,54 @@ +'use strict'; + +var util = require('./_util'); + +module.exports = function defFunc(ajv) { + defFunc.definition = { + type: 'object', + macro: function (schema) { + var schemas = []; + for (var pointer in schema) + schemas.push(getSchema(pointer, schema[pointer])); + return {'allOf': schemas}; + }, + metaSchema: { + type: 'object', + propertyNames: { + type: 'string', + format: 'json-pointer' + }, + additionalProperties: util.metaSchemaRef(ajv) + } + }; + + ajv.addKeyword('deepProperties', defFunc.definition); + return ajv; +}; + + +function getSchema(jsonPointer, schema) { + var segments = jsonPointer.split('/'); + var rootSchema = {}; + var pointerSchema = rootSchema; + for (var i=1; i' + , $result = 'result' + $lvl; +}} + +{{# def.$data }} + + +{{? $isDataExcl }} + {{ + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr) + , $exclusive = 'exclusive' + $lvl + , $opExpr = 'op' + $lvl + , $opStr = '\' + ' + $opExpr + ' + \''; + }} + var schemaExcl{{=$lvl}} = {{=$schemaValueExcl}}; + {{ $schemaValueExcl = 'schemaExcl' + $lvl; }} + + if (typeof {{=$schemaValueExcl}} != 'boolean' && {{=$schemaValueExcl}} !== undefined) { + {{=$valid}} = false; + {{ var $errorKeyword = $exclusiveKeyword; }} + {{# def.error:'_formatExclusiveLimit' }} + } + + {{# def.elseIfValid }} + + {{# def.compareFormat }} + var {{=$exclusive}} = {{=$schemaValueExcl}} === true; + + if ({{=$valid}} === undefined) { + {{=$valid}} = {{=$exclusive}} + ? {{=$result}} {{=$op}} 0 + : {{=$result}} {{=$op}}= 0; + } + + if (!{{=$valid}}) var op{{=$lvl}} = {{=$exclusive}} ? '{{=$op}}' : '{{=$op}}='; +{{??}} + {{ + var $exclusive = $schemaExcl === true + , $opStr = $op; /*used in error*/ + if (!$exclusive) $opStr += '='; + var $opExpr = '\'' + $opStr + '\''; /*used in error*/ + }} + + {{# def.compareFormat }} + + if ({{=$valid}} === undefined) + {{=$valid}} = {{=$result}} {{=$op}}{{?!$exclusive}}={{?}} 0; +{{?}} + +{{= $closingBraces }} + +if (!{{=$valid}}) { + {{ var $errorKeyword = $keyword; }} + {{# def.error:'_formatLimit' }} +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dot/patternRequired.jst b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dot/patternRequired.jst new file mode 100644 index 0000000..6f82f62 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dot/patternRequired.jst @@ -0,0 +1,33 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} + +{{ + var $key = 'key' + $lvl + , $idx = 'idx' + $lvl + , $matched = 'patternMatched' + $lvl + , $dataProperties = 'dataProperties' + $lvl + , $closingBraces = '' + , $ownProperties = it.opts.ownProperties; +}} + +var {{=$valid}} = true; +{{? $ownProperties }} + var {{=$dataProperties}} = undefined; +{{?}} + +{{~ $schema:$pProperty }} + var {{=$matched}} = false; + {{# def.iterateProperties }} + {{=$matched}} = {{= it.usePattern($pProperty) }}.test({{=$key}}); + if ({{=$matched}}) break; + } + + {{ var $missingPattern = it.util.escapeQuotes($pProperty); }} + if (!{{=$matched}}) { + {{=$valid}} = false; + {{# def.addError:'patternRequired' }} + } {{# def.elseIfValid }} +{{~}} + +{{= $closingBraces }} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dot/switch.jst b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dot/switch.jst new file mode 100644 index 0000000..24d68cf --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dot/switch.jst @@ -0,0 +1,71 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + + +{{## def.validateIf: + {{# def.setCompositeRule }} + {{ $it.createErrors = false; }} + {{# def._validateSwitchRule:if }} + {{ $it.createErrors = true; }} + {{# def.resetCompositeRule }} + {{=$ifPassed}} = {{=$nextValid}}; +#}} + +{{## def.validateThen: + {{? typeof $sch.then == 'boolean' }} + {{? $sch.then === false }} + {{# def.error:'switch' }} + {{?}} + var {{=$nextValid}} = {{= $sch.then }}; + {{??}} + {{# def._validateSwitchRule:then }} + {{?}} +#}} + +{{## def._validateSwitchRule:_clause: + {{ + $it.schema = $sch._clause; + $it.schemaPath = $schemaPath + '[' + $caseIndex + ']._clause'; + $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/_clause'; + }} + {{# def.insertSubschemaCode }} +#}} + +{{## def.switchCase: + {{? $sch.if && {{# def.nonEmptySchema:$sch.if }} }} + var {{=$errs}} = errors; + {{# def.validateIf }} + if ({{=$ifPassed}}) { + {{# def.validateThen }} + } else { + {{# def.resetErrors }} + } + {{??}} + {{=$ifPassed}} = true; + {{# def.validateThen }} + {{?}} +#}} + + +{{ + var $ifPassed = 'ifPassed' + it.level + , $currentBaseId = $it.baseId + , $shouldContinue; +}} +var {{=$ifPassed}}; + +{{~ $schema:$sch:$caseIndex }} + {{? $caseIndex && !$shouldContinue }} + if (!{{=$ifPassed}}) { + {{ $closingBraces+= '}'; }} + {{?}} + + {{# def.switchCase }} + {{ $shouldContinue = $sch.continue }} +{{~}} + +{{= $closingBraces }} + +var {{=$valid}} = {{=$nextValid}}; diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dotjs/README.md b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dotjs/README.md new file mode 100644 index 0000000..e2846c8 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dotjs/README.md @@ -0,0 +1,3 @@ +These files are compiled dot templates from dot folder. + +Do NOT edit them directly, edit the templates and run `npm run build` from main ajv-keywords folder. diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dotjs/_formatLimit.js b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dotjs/_formatLimit.js new file mode 100644 index 0000000..d2af638 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dotjs/_formatLimit.js @@ -0,0 +1,178 @@ +'use strict'; +module.exports = function generate__formatLimit(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + out += 'var ' + ($valid) + ' = undefined;'; + if (it.opts.format === false) { + out += ' ' + ($valid) + ' = true; '; + return out; + } + var $schemaFormat = it.schema.format, + $isDataFormat = it.opts.$data && $schemaFormat.$data, + $closingBraces = ''; + if ($isDataFormat) { + var $schemaValueFormat = it.util.getData($schemaFormat.$data, $dataLvl, it.dataPathArr), + $format = 'format' + $lvl, + $compare = 'compare' + $lvl; + out += ' var ' + ($format) + ' = formats[' + ($schemaValueFormat) + '] , ' + ($compare) + ' = ' + ($format) + ' && ' + ($format) + '.compare;'; + } else { + var $format = it.formats[$schemaFormat]; + if (!($format && $format.compare)) { + out += ' ' + ($valid) + ' = true; '; + return out; + } + var $compare = 'formats' + it.util.getProperty($schemaFormat) + '.compare'; + } + var $isMax = $keyword == 'formatMaximum', + $exclusiveKeyword = 'formatExclusive' + ($isMax ? 'Maximum' : 'Minimum'), + $schemaExcl = it.schema[$exclusiveKeyword], + $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, + $op = $isMax ? '<' : '>', + $result = 'result' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if ($isDataExcl) { + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), + $exclusive = 'exclusive' + $lvl, + $opExpr = 'op' + $lvl, + $opStr = '\' + ' + $opExpr + ' + \''; + out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; + $schemaValueExcl = 'schemaExcl' + $lvl; + out += ' if (typeof ' + ($schemaValueExcl) + ' != \'boolean\' && ' + ($schemaValueExcl) + ' !== undefined) { ' + ($valid) + ' = false; '; + var $errorKeyword = $exclusiveKeyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_formatExclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + if ($isData) { + out += ' if (' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'string\') ' + ($valid) + ' = false; else { '; + $closingBraces += '}'; + } + if ($isDataFormat) { + out += ' if (!' + ($compare) + ') ' + ($valid) + ' = true; else { '; + $closingBraces += '}'; + } + out += ' var ' + ($result) + ' = ' + ($compare) + '(' + ($data) + ', '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' ); if (' + ($result) + ' === undefined) ' + ($valid) + ' = false; var ' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true; if (' + ($valid) + ' === undefined) { ' + ($valid) + ' = ' + ($exclusive) + ' ? ' + ($result) + ' ' + ($op) + ' 0 : ' + ($result) + ' ' + ($op) + '= 0; } if (!' + ($valid) + ') var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\';'; + } else { + var $exclusive = $schemaExcl === true, + $opStr = $op; + if (!$exclusive) $opStr += '='; + var $opExpr = '\'' + $opStr + '\''; + if ($isData) { + out += ' if (' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'string\') ' + ($valid) + ' = false; else { '; + $closingBraces += '}'; + } + if ($isDataFormat) { + out += ' if (!' + ($compare) + ') ' + ($valid) + ' = true; else { '; + $closingBraces += '}'; + } + out += ' var ' + ($result) + ' = ' + ($compare) + '(' + ($data) + ', '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' ); if (' + ($result) + ' === undefined) ' + ($valid) + ' = false; if (' + ($valid) + ' === undefined) ' + ($valid) + ' = ' + ($result) + ' ' + ($op); + if (!$exclusive) { + out += '='; + } + out += ' 0;'; + } + out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_formatLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , exclusive: ' + ($exclusive) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be ' + ($opStr) + ' "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '}'; + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dotjs/patternRequired.js b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dotjs/patternRequired.js new file mode 100644 index 0000000..31bd0b6 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dotjs/patternRequired.js @@ -0,0 +1,58 @@ +'use strict'; +module.exports = function generate_patternRequired(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $matched = 'patternMatched' + $lvl, + $dataProperties = 'dataProperties' + $lvl, + $closingBraces = '', + $ownProperties = it.opts.ownProperties; + out += 'var ' + ($valid) + ' = true;'; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined;'; + } + var arr1 = $schema; + if (arr1) { + var $pProperty, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $pProperty = arr1[i1 += 1]; + out += ' var ' + ($matched) + ' = false; '; + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + out += ' ' + ($matched) + ' = ' + (it.usePattern($pProperty)) + '.test(' + ($key) + '); if (' + ($matched) + ') break; } '; + var $missingPattern = it.util.escapeQuotes($pProperty); + out += ' if (!' + ($matched) + ') { ' + ($valid) + ' = false; var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('patternRequired') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingPattern: \'' + ($missingPattern) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should have property matching pattern \\\'' + ($missingPattern) + '\\\'\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } + } + out += '' + ($closingBraces); + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dotjs/switch.js b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dotjs/switch.js new file mode 100644 index 0000000..0a3fb80 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dotjs/switch.js @@ -0,0 +1,129 @@ +'use strict'; +module.exports = function generate_switch(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $ifPassed = 'ifPassed' + it.level, + $currentBaseId = $it.baseId, + $shouldContinue; + out += 'var ' + ($ifPassed) + ';'; + var arr1 = $schema; + if (arr1) { + var $sch, $caseIndex = -1, + l1 = arr1.length - 1; + while ($caseIndex < l1) { + $sch = arr1[$caseIndex += 1]; + if ($caseIndex && !$shouldContinue) { + out += ' if (!' + ($ifPassed) + ') { '; + $closingBraces += '}'; + } + if ($sch.if && (it.opts.strictKeywords ? typeof $sch.if == 'object' && Object.keys($sch.if).length > 0 : it.util.schemaHasRules($sch.if, it.RULES.all))) { + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.createErrors = false; + $it.schema = $sch.if; + $it.schemaPath = $schemaPath + '[' + $caseIndex + '].if'; + $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/if'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + $it.createErrors = true; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($ifPassed) + ' = ' + ($nextValid) + '; if (' + ($ifPassed) + ') { '; + if (typeof $sch.then == 'boolean') { + if ($sch.then === false) { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('switch') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { caseIndex: ' + ($caseIndex) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "switch" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } + out += ' var ' + ($nextValid) + ' = ' + ($sch.then) + '; '; + } else { + $it.schema = $sch.then; + $it.schemaPath = $schemaPath + '[' + $caseIndex + '].then'; + $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/then'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } } '; + } else { + out += ' ' + ($ifPassed) + ' = true; '; + if (typeof $sch.then == 'boolean') { + if ($sch.then === false) { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('switch') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { caseIndex: ' + ($caseIndex) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "switch" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } + out += ' var ' + ($nextValid) + ' = ' + ($sch.then) + '; '; + } else { + $it.schema = $sch.then; + $it.schemaPath = $schemaPath + '[' + $caseIndex + '].then'; + $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/then'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } + } + $shouldContinue = $sch.continue + } + } + out += '' + ($closingBraces) + 'var ' + ($valid) + ' = ' + ($nextValid) + ';'; + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dynamicDefaults.js b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dynamicDefaults.js new file mode 100644 index 0000000..5323bb8 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/dynamicDefaults.js @@ -0,0 +1,72 @@ +'use strict'; + +var sequences = {}; + +var DEFAULTS = { + timestamp: function() { return Date.now(); }, + datetime: function() { return (new Date).toISOString(); }, + date: function() { return (new Date).toISOString().slice(0, 10); }, + time: function() { return (new Date).toISOString().slice(11); }, + random: function() { return Math.random(); }, + randomint: function (args) { + var limit = args && args.max || 2; + return function() { return Math.floor(Math.random() * limit); }; + }, + seq: function (args) { + var name = args && args.name || ''; + sequences[name] = sequences[name] || 0; + return function() { return sequences[name]++; }; + } +}; + +module.exports = function defFunc(ajv) { + defFunc.definition = { + compile: function (schema, parentSchema, it) { + var funcs = {}; + + for (var key in schema) { + var d = schema[key]; + var func = getDefault(typeof d == 'string' ? d : d.func); + funcs[key] = func.length ? func(d.args) : func; + } + + return it.opts.useDefaults && !it.compositeRule + ? assignDefaults + : noop; + + function assignDefaults(data) { + for (var prop in schema){ + if (data[prop] === undefined + || (it.opts.useDefaults == 'empty' + && (data[prop] === null || data[prop] === ''))) + data[prop] = funcs[prop](); + } + return true; + } + + function noop() { return true; } + }, + DEFAULTS: DEFAULTS, + metaSchema: { + type: 'object', + additionalProperties: { + type: ['string', 'object'], + additionalProperties: false, + required: ['func', 'args'], + properties: { + func: { type: 'string' }, + args: { type: 'object' } + } + } + } + }; + + ajv.addKeyword('dynamicDefaults', defFunc.definition); + return ajv; + + function getDefault(d) { + var def = DEFAULTS[d]; + if (def) return def; + throw new Error('invalid "dynamicDefaults" keyword property value: ' + d); + } +}; diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/formatMaximum.js b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/formatMaximum.js new file mode 100644 index 0000000..e7daabf --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/formatMaximum.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./_formatLimit')('Maximum'); diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/formatMinimum.js b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/formatMinimum.js new file mode 100644 index 0000000..eddd6e4 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/formatMinimum.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./_formatLimit')('Minimum'); diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/index.js b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/index.js new file mode 100644 index 0000000..99534ec --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/index.js @@ -0,0 +1,22 @@ +'use strict'; + +module.exports = { + 'instanceof': require('./instanceof'), + range: require('./range'), + regexp: require('./regexp'), + 'typeof': require('./typeof'), + dynamicDefaults: require('./dynamicDefaults'), + allRequired: require('./allRequired'), + anyRequired: require('./anyRequired'), + oneRequired: require('./oneRequired'), + prohibited: require('./prohibited'), + uniqueItemProperties: require('./uniqueItemProperties'), + deepProperties: require('./deepProperties'), + deepRequired: require('./deepRequired'), + formatMinimum: require('./formatMinimum'), + formatMaximum: require('./formatMaximum'), + patternRequired: require('./patternRequired'), + 'switch': require('./switch'), + select: require('./select'), + transform: require('./transform') +}; diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/instanceof.js b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/instanceof.js new file mode 100644 index 0000000..ea88f5c --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/instanceof.js @@ -0,0 +1,58 @@ +'use strict'; + +var CONSTRUCTORS = { + Object: Object, + Array: Array, + Function: Function, + Number: Number, + String: String, + Date: Date, + RegExp: RegExp +}; + +module.exports = function defFunc(ajv) { + /* istanbul ignore else */ + if (typeof Buffer != 'undefined') + CONSTRUCTORS.Buffer = Buffer; + + /* istanbul ignore else */ + if (typeof Promise != 'undefined') + CONSTRUCTORS.Promise = Promise; + + defFunc.definition = { + compile: function (schema) { + if (typeof schema == 'string') { + var Constructor = getConstructor(schema); + return function (data) { + return data instanceof Constructor; + }; + } + + var constructors = schema.map(getConstructor); + return function (data) { + for (var i=0; i max || (exclusive && min == max)) + throw new Error('There are no numbers in range'); + } +}; diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/regexp.js b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/regexp.js new file mode 100644 index 0000000..973628c --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/regexp.js @@ -0,0 +1,36 @@ +'use strict'; + +module.exports = function defFunc(ajv) { + defFunc.definition = { + type: 'string', + inline: function (it, keyword, schema) { + return getRegExp() + '.test(data' + (it.dataLevel || '') + ')'; + + function getRegExp() { + try { + if (typeof schema == 'object') + return new RegExp(schema.pattern, schema.flags); + + var rx = schema.match(/^\/(.*)\/([gimuy]*)$/); + if (rx) return new RegExp(rx[1], rx[2]); + throw new Error('cannot parse string into RegExp'); + } catch(e) { + console.error('regular expression', schema, 'is invalid'); + throw e; + } + } + }, + metaSchema: { + type: ['string', 'object'], + properties: { + pattern: { type: 'string' }, + flags: { type: 'string' } + }, + required: ['pattern'], + additionalProperties: false + } + }; + + ajv.addKeyword('regexp', defFunc.definition); + return ajv; +}; diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/select.js b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/select.js new file mode 100644 index 0000000..f79c6c7 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/select.js @@ -0,0 +1,79 @@ +'use strict'; + +var util = require('./_util'); + +module.exports = function defFunc(ajv) { + if (!ajv._opts.$data) { + console.warn('keyword select requires $data option'); + return ajv; + } + var metaSchemaRef = util.metaSchemaRef(ajv); + var compiledCaseSchemas = []; + + defFunc.definition = { + validate: function v(schema, data, parentSchema) { + if (parentSchema.selectCases === undefined) + throw new Error('keyword "selectCases" is absent'); + var compiled = getCompiledSchemas(parentSchema, false); + var validate = compiled.cases[schema]; + if (validate === undefined) validate = compiled.default; + if (typeof validate == 'boolean') return validate; + var valid = validate(data); + if (!valid) v.errors = validate.errors; + return valid; + }, + $data: true, + metaSchema: { type: ['string', 'number', 'boolean', 'null'] } + }; + + ajv.addKeyword('select', defFunc.definition); + ajv.addKeyword('selectCases', { + compile: function (schemas, parentSchema) { + var compiled = getCompiledSchemas(parentSchema); + for (var value in schemas) + compiled.cases[value] = compileOrBoolean(schemas[value]); + return function() { return true; }; + }, + valid: true, + metaSchema: { + type: 'object', + additionalProperties: metaSchemaRef + } + }); + ajv.addKeyword('selectDefault', { + compile: function (schema, parentSchema) { + var compiled = getCompiledSchemas(parentSchema); + compiled.default = compileOrBoolean(schema); + return function() { return true; }; + }, + valid: true, + metaSchema: metaSchemaRef + }); + return ajv; + + + function getCompiledSchemas(parentSchema, create) { + var compiled; + compiledCaseSchemas.some(function (c) { + if (c.parentSchema === parentSchema) { + compiled = c; + return true; + } + }); + if (!compiled && create !== false) { + compiled = { + parentSchema: parentSchema, + cases: {}, + default: true + }; + compiledCaseSchemas.push(compiled); + } + return compiled; + } + + function compileOrBoolean(schema) { + return typeof schema == 'boolean' + ? schema + : ajv.compile(schema); + } +}; diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/switch.js b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/switch.js new file mode 100644 index 0000000..5b0f3f8 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/switch.js @@ -0,0 +1,38 @@ +'use strict'; + +var util = require('./_util'); + +module.exports = function defFunc(ajv) { + if (ajv.RULES.keywords.switch && ajv.RULES.keywords.if) return; + + var metaSchemaRef = util.metaSchemaRef(ajv); + + defFunc.definition = { + inline: require('./dotjs/switch'), + statements: true, + errors: 'full', + metaSchema: { + type: 'array', + items: { + required: [ 'then' ], + properties: { + 'if': metaSchemaRef, + 'then': { + anyOf: [ + { type: 'boolean' }, + metaSchemaRef + ] + }, + 'continue': { type: 'boolean' } + }, + additionalProperties: false, + dependencies: { + 'continue': [ 'if' ] + } + } + } + }; + + ajv.addKeyword('switch', defFunc.definition); + return ajv; +}; diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/transform.js b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/transform.js new file mode 100644 index 0000000..d715452 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/transform.js @@ -0,0 +1,80 @@ +'use strict'; + +module.exports = function defFunc (ajv) { + var transform = { + trimLeft: function (value) { + return value.replace(/^[\s]+/, ''); + }, + trimRight: function (value) { + return value.replace(/[\s]+$/, ''); + }, + trim: function (value) { + return value.trim(); + }, + toLowerCase: function (value) { + return value.toLowerCase(); + }, + toUpperCase: function (value) { + return value.toUpperCase(); + }, + toEnumCase: function (value, cfg) { + return cfg.hash[makeHashTableKey(value)] || value; + } + }; + + defFunc.definition = { + type: 'string', + errors: false, + modifying: true, + valid: true, + compile: function (schema, parentSchema) { + var cfg; + + if (schema.indexOf('toEnumCase') !== -1) { + // build hash table to enum values + cfg = {hash: {}}; + + // requires `enum` in schema + if (!parentSchema.enum) + throw new Error('Missing enum. To use `transform:["toEnumCase"]`, `enum:[...]` is required.'); + for (var i = parentSchema.enum.length; i--; i) { + var v = parentSchema.enum[i]; + if (typeof v !== 'string') continue; + var k = makeHashTableKey(v); + // requires all `enum` values have unique keys + if (cfg.hash[k]) + throw new Error('Invalid enum uniqueness. To use `transform:["toEnumCase"]`, all values must be unique when case insensitive.'); + cfg.hash[k] = v; + } + } + + return function (data, dataPath, object, key) { + // skip if value only + if (!object) return; + + // apply transform in order provided + for (var j = 0, l = schema.length; j < l; j++) + data = transform[schema[j]](data, cfg); + + object[key] = data; + }; + }, + metaSchema: { + type: 'array', + items: { + type: 'string', + enum: [ + 'trimLeft', 'trimRight', 'trim', + 'toLowerCase', 'toUpperCase', 'toEnumCase' + ] + } + } + }; + + ajv.addKeyword('transform', defFunc.definition); + return ajv; + + function makeHashTableKey (value) { + return value.toLowerCase(); + } +}; diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/typeof.js b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/typeof.js new file mode 100644 index 0000000..3a3574d --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/typeof.js @@ -0,0 +1,32 @@ +'use strict'; + +var KNOWN_TYPES = ['undefined', 'string', 'number', 'object', 'function', 'boolean', 'symbol']; + +module.exports = function defFunc(ajv) { + defFunc.definition = { + inline: function (it, keyword, schema) { + var data = 'data' + (it.dataLevel || ''); + if (typeof schema == 'string') return 'typeof ' + data + ' == "' + schema + '"'; + schema = 'validate.schema' + it.schemaPath + '.' + keyword; + return schema + '.indexOf(typeof ' + data + ') >= 0'; + }, + metaSchema: { + anyOf: [ + { + type: 'string', + enum: KNOWN_TYPES + }, + { + type: 'array', + items: { + type: 'string', + enum: KNOWN_TYPES + } + } + ] + } + }; + + ajv.addKeyword('typeof', defFunc.definition); + return ajv; +}; diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/uniqueItemProperties.js b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/uniqueItemProperties.js new file mode 100644 index 0000000..cd670da --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/keywords/uniqueItemProperties.js @@ -0,0 +1,59 @@ +'use strict'; + +var SCALAR_TYPES = ['number', 'integer', 'string', 'boolean', 'null']; + +module.exports = function defFunc(ajv) { + defFunc.definition = { + type: 'array', + compile: function(keys, parentSchema, it) { + var equal = it.util.equal; + var scalar = getScalarKeys(keys, parentSchema); + + return function(data) { + if (data.length > 1) { + for (var k=0; k < keys.length; k++) { + var i, key = keys[k]; + if (scalar[k]) { + var hash = {}; + for (i = data.length; i--;) { + if (!data[i] || typeof data[i] != 'object') continue; + var prop = data[i][key]; + if (prop && typeof prop == 'object') continue; + if (typeof prop == 'string') prop = '"' + prop; + if (hash[prop]) return false; + hash[prop] = true; + } + } else { + for (i = data.length; i--;) { + if (!data[i] || typeof data[i] != 'object') continue; + for (var j = i; j--;) { + if (data[j] && typeof data[j] == 'object' && equal(data[i][key], data[j][key])) + return false; + } + } + } + } + } + return true; + }; + }, + metaSchema: { + type: 'array', + items: {type: 'string'} + } + }; + + ajv.addKeyword('uniqueItemProperties', defFunc.definition); + return ajv; +}; + + +function getScalarKeys(keys, schema) { + return keys.map(function(key) { + var properties = schema.items && schema.items.properties; + var propType = properties && properties[key] && properties[key].type; + return Array.isArray(propType) + ? propType.indexOf('object') < 0 && propType.indexOf('array') < 0 + : SCALAR_TYPES.indexOf(propType) >= 0; + }); +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/package.json b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/package.json new file mode 100644 index 0000000..fbd29d0 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv-keywords/package.json @@ -0,0 +1,53 @@ +{ + "name": "ajv-keywords", + "version": "3.5.2", + "description": "Custom JSON-Schema keywords for Ajv validator", + "main": "index.js", + "typings": "ajv-keywords.d.ts", + "scripts": { + "build": "node node_modules/ajv/scripts/compile-dots.js node_modules/ajv/lib keywords", + "prepublish": "npm run build", + "test": "npm run build && npm run eslint && npm run test-cov", + "eslint": "eslint index.js keywords/*.js spec", + "test-spec": "mocha spec/*.spec.js -R spec", + "test-cov": "istanbul cover -x 'spec/**' node_modules/mocha/bin/_mocha -- spec/*.spec.js -R spec" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/epoberezkin/ajv-keywords.git" + }, + "keywords": [ + "JSON-Schema", + "ajv", + "keywords" + ], + "files": [ + "index.js", + "ajv-keywords.d.ts", + "keywords" + ], + "author": "Evgeny Poberezkin", + "license": "MIT", + "bugs": { + "url": "https://github.com/epoberezkin/ajv-keywords/issues" + }, + "homepage": "https://github.com/epoberezkin/ajv-keywords#readme", + "peerDependencies": { + "ajv": "^6.9.1" + }, + "devDependencies": { + "ajv": "^6.9.1", + "ajv-pack": "^0.3.0", + "chai": "^4.2.0", + "coveralls": "^3.0.2", + "dot": "^1.1.1", + "eslint": "^7.2.0", + "glob": "^7.1.3", + "istanbul": "^0.4.3", + "js-beautify": "^1.8.9", + "json-schema-test": "^2.0.0", + "mocha": "^8.0.1", + "pre-commit": "^1.1.3", + "uuid": "^8.1.0" + } +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/.tonic_example.js b/node_modules/terser-webpack-plugin/node_modules/ajv/.tonic_example.js new file mode 100644 index 0000000..aa11812 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/.tonic_example.js @@ -0,0 +1,20 @@ +var Ajv = require('ajv'); +var ajv = new Ajv({allErrors: true}); + +var schema = { + "properties": { + "foo": { "type": "string" }, + "bar": { "type": "number", "maximum": 3 } + } +}; + +var validate = ajv.compile(schema); + +test({"foo": "abc", "bar": 2}); +test({"foo": 2, "bar": 4}); + +function test(data) { + var valid = validate(data); + if (valid) console.log('Valid!'); + else console.log('Invalid: ' + ajv.errorsText(validate.errors)); +} \ No newline at end of file diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/LICENSE b/node_modules/terser-webpack-plugin/node_modules/ajv/LICENSE new file mode 100644 index 0000000..96ee719 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015-2017 Evgeny Poberezkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/README.md b/node_modules/terser-webpack-plugin/node_modules/ajv/README.md new file mode 100644 index 0000000..5aa2078 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/README.md @@ -0,0 +1,1497 @@ +Ajv logo + +# Ajv: Another JSON Schema Validator + +The fastest JSON Schema validator for Node.js and browser. Supports draft-04/06/07. + +[![Build Status](https://travis-ci.org/ajv-validator/ajv.svg?branch=master)](https://travis-ci.org/ajv-validator/ajv) +[![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv) +[![npm (beta)](https://img.shields.io/npm/v/ajv/beta)](https://www.npmjs.com/package/ajv/v/7.0.0-beta.0) +[![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) +[![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv?branch=master) +[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) +[![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin) + + +## Ajv v7 beta is released + +[Ajv version 7.0.0-beta.0](https://github.com/ajv-validator/ajv/tree/v7-beta) is released with these changes: + +- to reduce the mistakes in JSON schemas and unexpected validation results, [strict mode](./docs/strict-mode.md) is added - it prohibits ignored or ambiguous JSON Schema elements. +- to make code injection from untrusted schemas impossible, [code generation](./docs/codegen.md) is fully re-written to be safe. +- to simplify Ajv extensions, the new keyword API that is used by pre-defined keywords is available to user-defined keywords - it is much easier to define any keywords now, especially with subschemas. +- schemas are compiled to ES6 code (ES5 code generation is supported with an option). +- to improve reliability and maintainability the code is migrated to TypeScript. + +**Please note**: + +- the support for JSON-Schema draft-04 is removed - if you have schemas using "id" attributes you have to replace them with "\$id" (or continue using version 6 that will be supported until 02/28/2021). +- all formats are separated to ajv-formats package - they have to be explicitely added if you use them. + +See [release notes](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0-beta.0) for the details. + +To install the new version: + +```bash +npm install ajv@beta +``` + +See [Getting started with v7](https://github.com/ajv-validator/ajv/tree/v7-beta#usage) for code example. + + +## Mozilla MOSS grant and OpenJS Foundation + +[](https://www.mozilla.org/en-US/moss/)     [](https://openjsf.org/blog/2020/08/14/ajv-joins-openjs-foundation-as-an-incubation-project/) + +Ajv has been awarded a grant from Mozilla’s [Open Source Support (MOSS) program](https://www.mozilla.org/en-US/moss/) in the “Foundational Technology” track! It will sponsor the development of Ajv support of [JSON Schema version 2019-09](https://tools.ietf.org/html/draft-handrews-json-schema-02) and of [JSON Type Definition](https://tools.ietf.org/html/draft-ucarion-json-type-definition-04). + +Ajv also joined [OpenJS Foundation](https://openjsf.org/) – having this support will help ensure the longevity and stability of Ajv for all its users. + +This [blog post](https://www.poberezkin.com/posts/2020-08-14-ajv-json-validator-mozilla-open-source-grant-openjs-foundation.html) has more details. + +I am looking for the long term maintainers of Ajv – working with [ReadySet](https://www.thereadyset.co/), also sponsored by Mozilla, to establish clear guidelines for the role of a "maintainer" and the contribution standards, and to encourage a wider, more inclusive, contribution from the community. + + +## Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin) + +Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant! + +Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released. + +Please sponsor Ajv via: +- [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it) +- [Ajv Open Collective️](https://opencollective.com/ajv) + +Thank you. + + +#### Open Collective sponsors + + + + + + + + + + + + + + + +## Using version 6 + +[JSON Schema draft-07](http://json-schema.org/latest/json-schema-validation.html) is published. + +[Ajv version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0) that supports draft-07 is released. It may require either migrating your schemas or updating your code (to continue using draft-04 and v5 schemas, draft-06 schemas will be supported without changes). + +__Please note__: To use Ajv with draft-06 schemas you need to explicitly add the meta-schema to the validator instance: + +```javascript +ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json')); +``` + +To use Ajv with draft-04 schemas in addition to explicitly adding meta-schema you also need to use option schemaId: + +```javascript +var ajv = new Ajv({schemaId: 'id'}); +// If you want to use both draft-04 and draft-06/07 schemas: +// var ajv = new Ajv({schemaId: 'auto'}); +ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json')); +``` + + +## Contents + +- [Performance](#performance) +- [Features](#features) +- [Getting started](#getting-started) +- [Frequently Asked Questions](https://github.com/ajv-validator/ajv/blob/master/FAQ.md) +- [Using in browser](#using-in-browser) + - [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp) +- [Command line interface](#command-line-interface) +- Validation + - [Keywords](#validation-keywords) + - [Annotation keywords](#annotation-keywords) + - [Formats](#formats) + - [Combining schemas with $ref](#ref) + - [$data reference](#data-reference) + - NEW: [$merge and $patch keywords](#merge-and-patch-keywords) + - [Defining custom keywords](#defining-custom-keywords) + - [Asynchronous schema compilation](#asynchronous-schema-compilation) + - [Asynchronous validation](#asynchronous-validation) +- [Security considerations](#security-considerations) + - [Security contact](#security-contact) + - [Untrusted schemas](#untrusted-schemas) + - [Circular references in objects](#circular-references-in-javascript-objects) + - [Trusted schemas](#security-risks-of-trusted-schemas) + - [ReDoS attack](#redos-attack) +- Modifying data during validation + - [Filtering data](#filtering-data) + - [Assigning defaults](#assigning-defaults) + - [Coercing data types](#coercing-data-types) +- API + - [Methods](#api) + - [Options](#options) + - [Validation errors](#validation-errors) +- [Plugins](#plugins) +- [Related packages](#related-packages) +- [Some packages using Ajv](#some-packages-using-ajv) +- [Tests, Contributing, Changes history](#tests) +- [Support, Code of conduct, License](#open-source-software-support) + + +## Performance + +Ajv generates code using [doT templates](https://github.com/olado/doT) to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization. + +Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: + +- [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place +- [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster +- [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) +- [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html) + + +Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark): + +[![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=32,4,1&chs=600x416&chxl=-1:|djv|ajv|json-schema-validator-generator|jsen|is-my-json-valid|themis|z-schema|jsck|skeemas|json-schema-library|tv4&chd=t:100,98,72.1,66.8,50.1,15.1,6.1,3.8,1.2,0.7,0.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance) + + +## Features + +- Ajv implements full JSON Schema [draft-06/07](http://json-schema.org/) and draft-04 standards: + - all validation keywords (see [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md)) + - full support of remote refs (remote schemas have to be added with `addSchema` or compiled to be available) + - support of circular references between schemas + - correct string lengths for strings with unicode pairs (can be turned off) + - [formats](#formats) defined by JSON Schema draft-07 standard and custom formats (can be turned off) + - [validates schemas against meta-schema](#api-validateschema) +- supports [browsers](#using-in-browser) and Node.js 0.10-14.x +- [asynchronous loading](#asynchronous-schema-compilation) of referenced schemas during compilation +- "All errors" validation mode with [option allErrors](#options) +- [error messages with parameters](#validation-errors) describing error reasons to allow creating custom error messages +- i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package +- [filtering data](#filtering-data) from additional properties +- [assigning defaults](#assigning-defaults) to missing properties and items +- [coercing data](#coercing-data-types) to the types specified in `type` keywords +- [custom keywords](#defining-custom-keywords) +- draft-06/07 keywords `const`, `contains`, `propertyNames` and `if/then/else` +- draft-06 boolean schemas (`true`/`false` as a schema to always pass/fail). +- keywords `switch`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package +- [$data reference](#data-reference) to use values from the validated data as values for the schema keywords +- [asynchronous validation](#asynchronous-validation) of custom formats and keywords + + +## Install + +``` +npm install ajv +``` + + +## Getting started + +Try it in the Node.js REPL: https://tonicdev.com/npm/ajv + + +The fastest validation call: + +```javascript +// Node.js require: +var Ajv = require('ajv'); +// or ESM/TypeScript import +import Ajv from 'ajv'; + +var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true} +var validate = ajv.compile(schema); +var valid = validate(data); +if (!valid) console.log(validate.errors); +``` + +or with less code + +```javascript +// ... +var valid = ajv.validate(schema, data); +if (!valid) console.log(ajv.errors); +// ... +``` + +or + +```javascript +// ... +var valid = ajv.addSchema(schema, 'mySchema') + .validate('mySchema', data); +if (!valid) console.log(ajv.errorsText()); +// ... +``` + +See [API](#api) and [Options](#options) for more details. + +Ajv compiles schemas to functions and caches them in all cases (using schema serialized with [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) or a custom function as a key), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again. + +The best performance is achieved when using compiled functions returned by `compile` or `getSchema` methods (there is no additional function call). + +__Please note__: every time a validation function or `ajv.validate` are called `errors` property is overwritten. You need to copy `errors` array reference to another variable if you want to use it later (e.g., in the callback). See [Validation errors](#validation-errors) + +__Note for TypeScript users__: `ajv` provides its own TypeScript declarations +out of the box, so you don't need to install the deprecated `@types/ajv` +module. + + +## Using in browser + +You can require Ajv directly from the code you browserify - in this case Ajv will be a part of your bundle. + +If you need to use Ajv in several bundles you can create a separate UMD bundle using `npm run bundle` script (thanks to [siddo420](https://github.com/siddo420)). + +Then you need to load Ajv in the browser: +```html + +``` + +This bundle can be used with different module systems; it creates global `Ajv` if no module system is found. + +The browser bundle is available on [cdnjs](https://cdnjs.com/libraries/ajv). + +Ajv is tested with these browsers: + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/epoberezkin.svg)](https://saucelabs.com/u/epoberezkin) + +__Please note__: some frameworks, e.g. Dojo, may redefine global require in such way that is not compatible with CommonJS module format. In such case Ajv bundle has to be loaded before the framework and then you can use global Ajv (see issue [#234](https://github.com/ajv-validator/ajv/issues/234)). + + +### Ajv and Content Security Policies (CSP) + +If you're using Ajv to compile a schema (the typical use) in a browser document that is loaded with a Content Security Policy (CSP), that policy will require a `script-src` directive that includes the value `'unsafe-eval'`. +:warning: NOTE, however, that `unsafe-eval` is NOT recommended in a secure CSP[[1]](https://developer.chrome.com/extensions/contentSecurityPolicy#relaxing-eval), as it has the potential to open the document to cross-site scripting (XSS) attacks. + +In order to make use of Ajv without easing your CSP, you can [pre-compile a schema using the CLI](https://github.com/ajv-validator/ajv-cli#compile-schemas). This will transpile the schema JSON into a JavaScript file that exports a `validate` function that works simlarly to a schema compiled at runtime. + +Note that pre-compilation of schemas is performed using [ajv-pack](https://github.com/ajv-validator/ajv-pack) and there are [some limitations to the schema features it can compile](https://github.com/ajv-validator/ajv-pack#limitations). A successfully pre-compiled schema is equivalent to the same schema compiled at runtime. + + +## Command line interface + +CLI is available as a separate npm package [ajv-cli](https://github.com/ajv-validator/ajv-cli). It supports: + +- compiling JSON Schemas to test their validity +- BETA: generating standalone module exporting a validation function to be used without Ajv (using [ajv-pack](https://github.com/ajv-validator/ajv-pack)) +- migrate schemas to draft-07 (using [json-schema-migrate](https://github.com/epoberezkin/json-schema-migrate)) +- validating data file(s) against JSON Schema +- testing expected validity of data against JSON Schema +- referenced schemas +- custom meta-schemas +- files in JSON, JSON5, YAML, and JavaScript format +- all Ajv options +- reporting changes in data after validation in [JSON-patch](https://tools.ietf.org/html/rfc6902) format + + +## Validation keywords + +Ajv supports all validation keywords from draft-07 of JSON Schema standard: + +- [type](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#type) +- [for numbers](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-numbers) - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf +- [for strings](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-strings) - maxLength, minLength, pattern, format +- [for arrays](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-arrays) - maxItems, minItems, uniqueItems, items, additionalItems, [contains](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#contains) +- [for objects](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-objects) - maxProperties, minProperties, required, properties, patternProperties, additionalProperties, dependencies, [propertyNames](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#propertynames) +- [for all types](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-all-types) - enum, [const](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#const) +- [compound keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#compound-keywords) - not, oneOf, anyOf, allOf, [if/then/else](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#ifthenelse) + +With [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package Ajv also supports validation keywords from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) for JSON Schema standard: + +- [patternRequired](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#patternrequired-proposed) - like `required` but with patterns that some property should match. +- [formatMaximum, formatMinimum, formatExclusiveMaximum, formatExclusiveMinimum](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#formatmaximum--formatminimum-and-exclusiveformatmaximum--exclusiveformatminimum-proposed) - setting limits for date, time, etc. + +See [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md) for more details. + + +## Annotation keywords + +JSON Schema specification defines several annotation keywords that describe schema itself but do not perform any validation. + +- `title` and `description`: information about the data represented by that schema +- `$comment` (NEW in draft-07): information for developers. With option `$comment` Ajv logs or passes the comment string to the user-supplied function. See [Options](#options). +- `default`: a default value of the data instance, see [Assigning defaults](#assigning-defaults). +- `examples` (NEW in draft-06): an array of data instances. Ajv does not check the validity of these instances against the schema. +- `readOnly` and `writeOnly` (NEW in draft-07): marks data-instance as read-only or write-only in relation to the source of the data (database, api, etc.). +- `contentEncoding`: [RFC 2045](https://tools.ietf.org/html/rfc2045#section-6.1 ), e.g., "base64". +- `contentMediaType`: [RFC 2046](https://tools.ietf.org/html/rfc2046), e.g., "image/png". + +__Please note__: Ajv does not implement validation of the keywords `examples`, `contentEncoding` and `contentMediaType` but it reserves them. If you want to create a plugin that implements some of them, it should remove these keywords from the instance. + + +## Formats + +Ajv implements formats defined by JSON Schema specification and several other formats. It is recommended NOT to use "format" keyword implementations with untrusted data, as they use potentially unsafe regular expressions - see [ReDoS attack](#redos-attack). + +__Please note__: if you need to use "format" keyword to validate untrusted data, you MUST assess their suitability and safety for your validation scenarios. + +The following formats are implemented for string validation with "format" keyword: + +- _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6). +- _time_: time with optional time-zone. +- _date-time_: date-time from the same source (time-zone is mandatory). `date`, `time` and `date-time` validate ranges in `full` mode and only regexp in `fast` mode (see [options](#options)). +- _uri_: full URI. +- _uri-reference_: URI reference, including full and relative URIs. +- _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570) +- _url_ (deprecated): [URL record](https://url.spec.whatwg.org/#concept-url). +- _email_: email address. +- _hostname_: host name according to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5). +- _ipv4_: IP address v4. +- _ipv6_: IP address v6. +- _regex_: tests whether a string is a valid regular expression by passing it to RegExp constructor. +- _uuid_: Universally Unique IDentifier according to [RFC4122](http://tools.ietf.org/html/rfc4122). +- _json-pointer_: JSON-pointer according to [RFC6901](https://tools.ietf.org/html/rfc6901). +- _relative-json-pointer_: relative JSON-pointer according to [this draft](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00). + +__Please note__: JSON Schema draft-07 also defines formats `iri`, `iri-reference`, `idn-hostname` and `idn-email` for URLs, hostnames and emails with international characters. Ajv does not implement these formats. If you create Ajv plugin that implements them please make a PR to mention this plugin here. + +There are two modes of format validation: `fast` and `full`. This mode affects formats `date`, `time`, `date-time`, `uri`, `uri-reference`, and `email`. See [Options](#options) for details. + +You can add additional formats and replace any of the formats above using [addFormat](#api-addformat) method. + +The option `unknownFormats` allows changing the default behaviour when an unknown format is encountered. In this case Ajv can either fail schema compilation (default) or ignore it (default in versions before 5.0.0). You also can allow specific format(s) that will be ignored. See [Options](#options) for details. + +You can find regular expressions used for format validation and the sources that were used in [formats.js](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js). + + +## Combining schemas with $ref + +You can structure your validation logic across multiple schema files and have schemas reference each other using `$ref` keyword. + +Example: + +```javascript +var schema = { + "$id": "http://example.com/schemas/schema.json", + "type": "object", + "properties": { + "foo": { "$ref": "defs.json#/definitions/int" }, + "bar": { "$ref": "defs.json#/definitions/str" } + } +}; + +var defsSchema = { + "$id": "http://example.com/schemas/defs.json", + "definitions": { + "int": { "type": "integer" }, + "str": { "type": "string" } + } +}; +``` + +Now to compile your schema you can either pass all schemas to Ajv instance: + +```javascript +var ajv = new Ajv({schemas: [schema, defsSchema]}); +var validate = ajv.getSchema('http://example.com/schemas/schema.json'); +``` + +or use `addSchema` method: + +```javascript +var ajv = new Ajv; +var validate = ajv.addSchema(defsSchema) + .compile(schema); +``` + +See [Options](#options) and [addSchema](#api) method. + +__Please note__: +- `$ref` is resolved as the uri-reference using schema $id as the base URI (see the example). +- References can be recursive (and mutually recursive) to implement the schemas for different data structures (such as linked lists, trees, graphs, etc.). +- You don't have to host your schema files at the URIs that you use as schema $id. These URIs are only used to identify the schemas, and according to JSON Schema specification validators should not expect to be able to download the schemas from these URIs. +- The actual location of the schema file in the file system is not used. +- You can pass the identifier of the schema as the second parameter of `addSchema` method or as a property name in `schemas` option. This identifier can be used instead of (or in addition to) schema $id. +- You cannot have the same $id (or the schema identifier) used for more than one schema - the exception will be thrown. +- You can implement dynamic resolution of the referenced schemas using `compileAsync` method. In this way you can store schemas in any system (files, web, database, etc.) and reference them without explicitly adding to Ajv instance. See [Asynchronous schema compilation](#asynchronous-schema-compilation). + + +## $data reference + +With `$data` option you can use values from the validated data as the values for the schema keywords. See [proposal](https://github.com/json-schema-org/json-schema-spec/issues/51) for more information about how it works. + +`$data` reference is supported in the keywords: const, enum, format, maximum/minimum, exclusiveMaximum / exclusiveMinimum, maxLength / minLength, maxItems / minItems, maxProperties / minProperties, formatMaximum / formatMinimum, formatExclusiveMaximum / formatExclusiveMinimum, multipleOf, pattern, required, uniqueItems. + +The value of "$data" should be a [JSON-pointer](https://tools.ietf.org/html/rfc6901) to the data (the root is always the top level data object, even if the $data reference is inside a referenced subschema) or a [relative JSON-pointer](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00) (it is relative to the current point in data; if the $data reference is inside a referenced subschema it cannot point to the data outside of the root level for this subschema). + +Examples. + +This schema requires that the value in property `smaller` is less or equal than the value in the property larger: + +```javascript +var ajv = new Ajv({$data: true}); + +var schema = { + "properties": { + "smaller": { + "type": "number", + "maximum": { "$data": "1/larger" } + }, + "larger": { "type": "number" } + } +}; + +var validData = { + smaller: 5, + larger: 7 +}; + +ajv.validate(schema, validData); // true +``` + +This schema requires that the properties have the same format as their field names: + +```javascript +var schema = { + "additionalProperties": { + "type": "string", + "format": { "$data": "0#" } + } +}; + +var validData = { + 'date-time': '1963-06-19T08:30:06.283185Z', + email: 'joe.bloggs@example.com' +} +``` + +`$data` reference is resolved safely - it won't throw even if some property is undefined. If `$data` resolves to `undefined` the validation succeeds (with the exclusion of `const` keyword). If `$data` resolves to incorrect type (e.g. not "number" for maximum keyword) the validation fails. + + +## $merge and $patch keywords + +With the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) you can use the keywords `$merge` and `$patch` that allow extending JSON Schemas with patches using formats [JSON Merge Patch (RFC 7396)](https://tools.ietf.org/html/rfc7396) and [JSON Patch (RFC 6902)](https://tools.ietf.org/html/rfc6902). + +To add keywords `$merge` and `$patch` to Ajv instance use this code: + +```javascript +require('ajv-merge-patch')(ajv); +``` + +Examples. + +Using `$merge`: + +```json +{ + "$merge": { + "source": { + "type": "object", + "properties": { "p": { "type": "string" } }, + "additionalProperties": false + }, + "with": { + "properties": { "q": { "type": "number" } } + } + } +} +``` + +Using `$patch`: + +```json +{ + "$patch": { + "source": { + "type": "object", + "properties": { "p": { "type": "string" } }, + "additionalProperties": false + }, + "with": [ + { "op": "add", "path": "/properties/q", "value": { "type": "number" } } + ] + } +} +``` + +The schemas above are equivalent to this schema: + +```json +{ + "type": "object", + "properties": { + "p": { "type": "string" }, + "q": { "type": "number" } + }, + "additionalProperties": false +} +``` + +The properties `source` and `with` in the keywords `$merge` and `$patch` can use absolute or relative `$ref` to point to other schemas previously added to the Ajv instance or to the fragments of the current schema. + +See the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) for more information. + + +## Defining custom keywords + +The advantages of using custom keywords are: + +- allow creating validation scenarios that cannot be expressed using JSON Schema +- simplify your schemas +- help bringing a bigger part of the validation logic to your schemas +- make your schemas more expressive, less verbose and closer to your application domain +- implement custom data processors that modify your data (`modifying` option MUST be used in keyword definition) and/or create side effects while the data is being validated + +If a keyword is used only for side-effects and its validation result is pre-defined, use option `valid: true/false` in keyword definition to simplify both generated code (no error handling in case of `valid: true`) and your keyword functions (no need to return any validation result). + +The concerns you have to be aware of when extending JSON Schema standard with custom keywords are the portability and understanding of your schemas. You will have to support these custom keywords on other platforms and to properly document these keywords so that everybody can understand them in your schemas. + +You can define custom keywords with [addKeyword](#api-addkeyword) method. Keywords are defined on the `ajv` instance level - new instances will not have previously defined keywords. + +Ajv allows defining keywords with: +- validation function +- compilation function +- macro function +- inline compilation function that should return code (as string) that will be inlined in the currently compiled schema. + +Example. `range` and `exclusiveRange` keywords using compiled schema: + +```javascript +ajv.addKeyword('range', { + type: 'number', + compile: function (sch, parentSchema) { + var min = sch[0]; + var max = sch[1]; + + return parentSchema.exclusiveRange === true + ? function (data) { return data > min && data < max; } + : function (data) { return data >= min && data <= max; } + } +}); + +var schema = { "range": [2, 4], "exclusiveRange": true }; +var validate = ajv.compile(schema); +console.log(validate(2.01)); // true +console.log(validate(3.99)); // true +console.log(validate(2)); // false +console.log(validate(4)); // false +``` + +Several custom keywords (typeof, instanceof, range and propertyNames) are defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - they can be used for your schemas and as a starting point for your own custom keywords. + +See [Defining custom keywords](https://github.com/ajv-validator/ajv/blob/master/CUSTOM.md) for more details. + + +## Asynchronous schema compilation + +During asynchronous compilation remote references are loaded using supplied function. See `compileAsync` [method](#api-compileAsync) and `loadSchema` [option](#options). + +Example: + +```javascript +var ajv = new Ajv({ loadSchema: loadSchema }); + +ajv.compileAsync(schema).then(function (validate) { + var valid = validate(data); + // ... +}); + +function loadSchema(uri) { + return request.json(uri).then(function (res) { + if (res.statusCode >= 400) + throw new Error('Loading error: ' + res.statusCode); + return res.body; + }); +} +``` + +__Please note__: [Option](#options) `missingRefs` should NOT be set to `"ignore"` or `"fail"` for asynchronous compilation to work. + + +## Asynchronous validation + +Example in Node.js REPL: https://tonicdev.com/esp/ajv-asynchronous-validation + +You can define custom formats and keywords that perform validation asynchronously by accessing database or some other service. You should add `async: true` in the keyword or format definition (see [addFormat](#api-addformat), [addKeyword](#api-addkeyword) and [Defining custom keywords](#defining-custom-keywords)). + +If your schema uses asynchronous formats/keywords or refers to some schema that contains them it should have `"$async": true` keyword so that Ajv can compile it correctly. If asynchronous format/keyword or reference to asynchronous schema is used in the schema without `$async` keyword Ajv will throw an exception during schema compilation. + +__Please note__: all asynchronous subschemas that are referenced from the current or other schemas should have `"$async": true` keyword as well, otherwise the schema compilation will fail. + +Validation function for an asynchronous custom format/keyword should return a promise that resolves with `true` or `false` (or rejects with `new Ajv.ValidationError(errors)` if you want to return custom errors from the keyword function). + +Ajv compiles asynchronous schemas to [es7 async functions](http://tc39.github.io/ecmascript-asyncawait/) that can optionally be transpiled with [nodent](https://github.com/MatAtBread/nodent). Async functions are supported in Node.js 7+ and all modern browsers. You can also supply any other transpiler as a function via `processCode` option. See [Options](#options). + +The compiled validation function has `$async: true` property (if the schema is asynchronous), so you can differentiate these functions if you are using both synchronous and asynchronous schemas. + +Validation result will be a promise that resolves with validated data or rejects with an exception `Ajv.ValidationError` that contains the array of validation errors in `errors` property. + + +Example: + +```javascript +var ajv = new Ajv; +// require('ajv-async')(ajv); + +ajv.addKeyword('idExists', { + async: true, + type: 'number', + validate: checkIdExists +}); + + +function checkIdExists(schema, data) { + return knex(schema.table) + .select('id') + .where('id', data) + .then(function (rows) { + return !!rows.length; // true if record is found + }); +} + +var schema = { + "$async": true, + "properties": { + "userId": { + "type": "integer", + "idExists": { "table": "users" } + }, + "postId": { + "type": "integer", + "idExists": { "table": "posts" } + } + } +}; + +var validate = ajv.compile(schema); + +validate({ userId: 1, postId: 19 }) +.then(function (data) { + console.log('Data is valid', data); // { userId: 1, postId: 19 } +}) +.catch(function (err) { + if (!(err instanceof Ajv.ValidationError)) throw err; + // data is invalid + console.log('Validation errors:', err.errors); +}); +``` + +### Using transpilers with asynchronous validation functions. + +[ajv-async](https://github.com/ajv-validator/ajv-async) uses [nodent](https://github.com/MatAtBread/nodent) to transpile async functions. To use another transpiler you should separately install it (or load its bundle in the browser). + + +#### Using nodent + +```javascript +var ajv = new Ajv; +require('ajv-async')(ajv); +// in the browser if you want to load ajv-async bundle separately you can: +// window.ajvAsync(ajv); +var validate = ajv.compile(schema); // transpiled es7 async function +validate(data).then(successFunc).catch(errorFunc); +``` + + +#### Using other transpilers + +```javascript +var ajv = new Ajv({ processCode: transpileFunc }); +var validate = ajv.compile(schema); // transpiled es7 async function +validate(data).then(successFunc).catch(errorFunc); +``` + +See [Options](#options). + + +## Security considerations + +JSON Schema, if properly used, can replace data sanitisation. It doesn't replace other API security considerations. It also introduces additional security aspects to consider. + + +##### Security contact + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues. + + +##### Untrusted schemas + +Ajv treats JSON schemas as trusted as your application code. This security model is based on the most common use case, when the schemas are static and bundled together with the application. + +If your schemas are received from untrusted sources (or generated from untrusted data) there are several scenarios you need to prevent: +- compiling schemas can cause stack overflow (if they are too deep) +- compiling schemas can be slow (e.g. [#557](https://github.com/ajv-validator/ajv/issues/557)) +- validating certain data can be slow + +It is difficult to predict all the scenarios, but at the very least it may help to limit the size of untrusted schemas (e.g. limit JSON string length) and also the maximum schema object depth (that can be high for relatively small JSON strings). You also may want to mitigate slow regular expressions in `pattern` and `patternProperties` keywords. + +Regardless the measures you take, using untrusted schemas increases security risks. + + +##### Circular references in JavaScript objects + +Ajv does not support schemas and validated data that have circular references in objects. See [issue #802](https://github.com/ajv-validator/ajv/issues/802). + +An attempt to compile such schemas or validate such data would cause stack overflow (or will not complete in case of asynchronous validation). Depending on the parser you use, untrusted data can lead to circular references. + + +##### Security risks of trusted schemas + +Some keywords in JSON Schemas can lead to very slow validation for certain data. These keywords include (but may be not limited to): + +- `pattern` and `format` for large strings - in some cases using `maxLength` can help mitigate it, but certain regular expressions can lead to exponential validation time even with relatively short strings (see [ReDoS attack](#redos-attack)). +- `patternProperties` for large property names - use `propertyNames` to mitigate, but some regular expressions can have exponential evaluation time as well. +- `uniqueItems` for large non-scalar arrays - use `maxItems` to mitigate + +__Please note__: The suggestions above to prevent slow validation would only work if you do NOT use `allErrors: true` in production code (using it would continue validation after validation errors). + +You can validate your JSON schemas against [this meta-schema](https://github.com/ajv-validator/ajv/blob/master/lib/refs/json-schema-secure.json) to check that these recommendations are followed: + +```javascript +const isSchemaSecure = ajv.compile(require('ajv/lib/refs/json-schema-secure.json')); + +const schema1 = {format: 'email'}; +isSchemaSecure(schema1); // false + +const schema2 = {format: 'email', maxLength: MAX_LENGTH}; +isSchemaSecure(schema2); // true +``` + +__Please note__: following all these recommendation is not a guarantee that validation of untrusted data is safe - it can still lead to some undesirable results. + + +##### Content Security Policies (CSP) +See [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp) + + +## ReDoS attack + +Certain regular expressions can lead to the exponential evaluation time even with relatively short strings. + +Please assess the regular expressions you use in the schemas on their vulnerability to this attack - see [safe-regex](https://github.com/substack/safe-regex), for example. + +__Please note__: some formats that Ajv implements use [regular expressions](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js) that can be vulnerable to ReDoS attack, so if you use Ajv to validate data from untrusted sources __it is strongly recommended__ to consider the following: + +- making assessment of "format" implementations in Ajv. +- using `format: 'fast'` option that simplifies some of the regular expressions (although it does not guarantee that they are safe). +- replacing format implementations provided by Ajv with your own implementations of "format" keyword that either uses different regular expressions or another approach to format validation. Please see [addFormat](#api-addformat) method. +- disabling format validation by ignoring "format" keyword with option `format: false` + +Whatever mitigation you choose, please assume all formats provided by Ajv as potentially unsafe and make your own assessment of their suitability for your validation scenarios. + + +## Filtering data + +With [option `removeAdditional`](#options) (added by [andyscott](https://github.com/andyscott)) you can filter data during the validation. + +This option modifies original data. + +Example: + +```javascript +var ajv = new Ajv({ removeAdditional: true }); +var schema = { + "additionalProperties": false, + "properties": { + "foo": { "type": "number" }, + "bar": { + "additionalProperties": { "type": "number" }, + "properties": { + "baz": { "type": "string" } + } + } + } +} + +var data = { + "foo": 0, + "additional1": 1, // will be removed; `additionalProperties` == false + "bar": { + "baz": "abc", + "additional2": 2 // will NOT be removed; `additionalProperties` != false + }, +} + +var validate = ajv.compile(schema); + +console.log(validate(data)); // true +console.log(data); // { "foo": 0, "bar": { "baz": "abc", "additional2": 2 } +``` + +If `removeAdditional` option in the example above were `"all"` then both `additional1` and `additional2` properties would have been removed. + +If the option were `"failing"` then property `additional1` would have been removed regardless of its value and property `additional2` would have been removed only if its value were failing the schema in the inner `additionalProperties` (so in the example above it would have stayed because it passes the schema, but any non-number would have been removed). + +__Please note__: If you use `removeAdditional` option with `additionalProperties` keyword inside `anyOf`/`oneOf` keywords your validation can fail with this schema, for example: + +```json +{ + "type": "object", + "oneOf": [ + { + "properties": { + "foo": { "type": "string" } + }, + "required": [ "foo" ], + "additionalProperties": false + }, + { + "properties": { + "bar": { "type": "integer" } + }, + "required": [ "bar" ], + "additionalProperties": false + } + ] +} +``` + +The intention of the schema above is to allow objects with either the string property "foo" or the integer property "bar", but not with both and not with any other properties. + +With the option `removeAdditional: true` the validation will pass for the object `{ "foo": "abc"}` but will fail for the object `{"bar": 1}`. It happens because while the first subschema in `oneOf` is validated, the property `bar` is removed because it is an additional property according to the standard (because it is not included in `properties` keyword in the same schema). + +While this behaviour is unexpected (issues [#129](https://github.com/ajv-validator/ajv/issues/129), [#134](https://github.com/ajv-validator/ajv/issues/134)), it is correct. To have the expected behaviour (both objects are allowed and additional properties are removed) the schema has to be refactored in this way: + +```json +{ + "type": "object", + "properties": { + "foo": { "type": "string" }, + "bar": { "type": "integer" } + }, + "additionalProperties": false, + "oneOf": [ + { "required": [ "foo" ] }, + { "required": [ "bar" ] } + ] +} +``` + +The schema above is also more efficient - it will compile into a faster function. + + +## Assigning defaults + +With [option `useDefaults`](#options) Ajv will assign values from `default` keyword in the schemas of `properties` and `items` (when it is the array of schemas) to the missing properties and items. + +With the option value `"empty"` properties and items equal to `null` or `""` (empty string) will be considered missing and assigned defaults. + +This option modifies original data. + +__Please note__: the default value is inserted in the generated validation code as a literal, so the value inserted in the data will be the deep clone of the default in the schema. + + +Example 1 (`default` in `properties`): + +```javascript +var ajv = new Ajv({ useDefaults: true }); +var schema = { + "type": "object", + "properties": { + "foo": { "type": "number" }, + "bar": { "type": "string", "default": "baz" } + }, + "required": [ "foo", "bar" ] +}; + +var data = { "foo": 1 }; + +var validate = ajv.compile(schema); + +console.log(validate(data)); // true +console.log(data); // { "foo": 1, "bar": "baz" } +``` + +Example 2 (`default` in `items`): + +```javascript +var schema = { + "type": "array", + "items": [ + { "type": "number" }, + { "type": "string", "default": "foo" } + ] +} + +var data = [ 1 ]; + +var validate = ajv.compile(schema); + +console.log(validate(data)); // true +console.log(data); // [ 1, "foo" ] +``` + +`default` keywords in other cases are ignored: + +- not in `properties` or `items` subschemas +- in schemas inside `anyOf`, `oneOf` and `not` (see [#42](https://github.com/ajv-validator/ajv/issues/42)) +- in `if` subschema of `switch` keyword +- in schemas generated by custom macro keywords + +The [`strictDefaults` option](#options) customizes Ajv's behavior for the defaults that Ajv ignores (`true` raises an error, and `"log"` outputs a warning). + + +## Coercing data types + +When you are validating user inputs all your data properties are usually strings. The option `coerceTypes` allows you to have your data types coerced to the types specified in your schema `type` keywords, both to pass the validation and to use the correctly typed data afterwards. + +This option modifies original data. + +__Please note__: if you pass a scalar value to the validating function its type will be coerced and it will pass the validation, but the value of the variable you pass won't be updated because scalars are passed by value. + + +Example 1: + +```javascript +var ajv = new Ajv({ coerceTypes: true }); +var schema = { + "type": "object", + "properties": { + "foo": { "type": "number" }, + "bar": { "type": "boolean" } + }, + "required": [ "foo", "bar" ] +}; + +var data = { "foo": "1", "bar": "false" }; + +var validate = ajv.compile(schema); + +console.log(validate(data)); // true +console.log(data); // { "foo": 1, "bar": false } +``` + +Example 2 (array coercions): + +```javascript +var ajv = new Ajv({ coerceTypes: 'array' }); +var schema = { + "properties": { + "foo": { "type": "array", "items": { "type": "number" } }, + "bar": { "type": "boolean" } + } +}; + +var data = { "foo": "1", "bar": ["false"] }; + +var validate = ajv.compile(schema); + +console.log(validate(data)); // true +console.log(data); // { "foo": [1], "bar": false } +``` + +The coercion rules, as you can see from the example, are different from JavaScript both to validate user input as expected and to have the coercion reversible (to correctly validate cases where different types are defined in subschemas of "anyOf" and other compound keywords). + +See [Coercion rules](https://github.com/ajv-validator/ajv/blob/master/COERCION.md) for details. + + +## API + +##### new Ajv(Object options) -> Object + +Create Ajv instance. + + +##### .compile(Object schema) -> Function<Object data> + +Generate validating function and cache the compiled schema for future use. + +Validating function returns a boolean value. This function has properties `errors` and `schema`. Errors encountered during the last validation are assigned to `errors` property (it is assigned `null` if there was no errors). `schema` property contains the reference to the original schema. + +The schema passed to this method will be validated against meta-schema unless `validateSchema` option is false. If schema is invalid, an error will be thrown. See [options](#options). + + +##### .compileAsync(Object schema [, Boolean meta] [, Function callback]) -> Promise + +Asynchronous version of `compile` method that loads missing remote schemas using asynchronous function in `options.loadSchema`. This function returns a Promise that resolves to a validation function. An optional callback passed to `compileAsync` will be called with 2 parameters: error (or null) and validating function. The returned promise will reject (and the callback will be called with an error) when: + +- missing schema can't be loaded (`loadSchema` returns a Promise that rejects). +- a schema containing a missing reference is loaded, but the reference cannot be resolved. +- schema (or some loaded/referenced schema) is invalid. + +The function compiles schema and loads the first missing schema (or meta-schema) until all missing schemas are loaded. + +You can asynchronously compile meta-schema by passing `true` as the second parameter. + +See example in [Asynchronous compilation](#asynchronous-schema-compilation). + + +##### .validate(Object schema|String key|String ref, data) -> Boolean + +Validate data using passed schema (it will be compiled and cached). + +Instead of the schema you can use the key that was previously passed to `addSchema`, the schema id if it was present in the schema or any previously resolved reference. + +Validation errors will be available in the `errors` property of Ajv instance (`null` if there were no errors). + +__Please note__: every time this method is called the errors are overwritten so you need to copy them to another variable if you want to use them later. + +If the schema is asynchronous (has `$async` keyword on the top level) this method returns a Promise. See [Asynchronous validation](#asynchronous-validation). + + +##### .addSchema(Array<Object>|Object schema [, String key]) -> Ajv + +Add schema(s) to validator instance. This method does not compile schemas (but it still validates them). Because of that dependencies can be added in any order and circular dependencies are supported. It also prevents unnecessary compilation of schemas that are containers for other schemas but not used as a whole. + +Array of schemas can be passed (schemas should have ids), the second parameter will be ignored. + +Key can be passed that can be used to reference the schema and will be used as the schema id if there is no id inside the schema. If the key is not passed, the schema id will be used as the key. + + +Once the schema is added, it (and all the references inside it) can be referenced in other schemas and used to validate data. + +Although `addSchema` does not compile schemas, explicit compilation is not required - the schema will be compiled when it is used first time. + +By default the schema is validated against meta-schema before it is added, and if the schema does not pass validation the exception is thrown. This behaviour is controlled by `validateSchema` option. + +__Please note__: Ajv uses the [method chaining syntax](https://en.wikipedia.org/wiki/Method_chaining) for all methods with the prefix `add*` and `remove*`. +This allows you to do nice things like the following. + +```javascript +var validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri); +``` + +##### .addMetaSchema(Array<Object>|Object schema [, String key]) -> Ajv + +Adds meta schema(s) that can be used to validate other schemas. That function should be used instead of `addSchema` because there may be instance options that would compile a meta schema incorrectly (at the moment it is `removeAdditional` option). + +There is no need to explicitly add draft-07 meta schema (http://json-schema.org/draft-07/schema) - it is added by default, unless option `meta` is set to `false`. You only need to use it if you have a changed meta-schema that you want to use to validate your schemas. See `validateSchema`. + + +##### .validateSchema(Object schema) -> Boolean + +Validates schema. This method should be used to validate schemas rather than `validate` due to the inconsistency of `uri` format in JSON Schema standard. + +By default this method is called automatically when the schema is added, so you rarely need to use it directly. + +If schema doesn't have `$schema` property, it is validated against draft 6 meta-schema (option `meta` should not be false). + +If schema has `$schema` property, then the schema with this id (that should be previously added) is used to validate passed schema. + +Errors will be available at `ajv.errors`. + + +##### .getSchema(String key) -> Function<Object data> + +Retrieve compiled schema previously added with `addSchema` by the key passed to `addSchema` or by its full reference (id). The returned validating function has `schema` property with the reference to the original schema. + + +##### .removeSchema([Object schema|String key|String ref|RegExp pattern]) -> Ajv + +Remove added/cached schema. Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references. + +Schema can be removed using: +- key passed to `addSchema` +- it's full reference (id) +- RegExp that should match schema id or key (meta-schemas won't be removed) +- actual schema object that will be stable-stringified to remove schema from cache + +If no parameter is passed all schemas but meta-schemas will be removed and the cache will be cleared. + + +##### .addFormat(String name, String|RegExp|Function|Object format) -> Ajv + +Add custom format to validate strings or numbers. It can also be used to replace pre-defined formats for Ajv instance. + +Strings are converted to RegExp. + +Function should return validation result as `true` or `false`. + +If object is passed it should have properties `validate`, `compare` and `async`: + +- _validate_: a string, RegExp or a function as described above. +- _compare_: an optional comparison function that accepts two strings and compares them according to the format meaning. This function is used with keywords `formatMaximum`/`formatMinimum` (defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package). It should return `1` if the first value is bigger than the second value, `-1` if it is smaller and `0` if it is equal. +- _async_: an optional `true` value if `validate` is an asynchronous function; in this case it should return a promise that resolves with a value `true` or `false`. +- _type_: an optional type of data that the format applies to. It can be `"string"` (default) or `"number"` (see https://github.com/ajv-validator/ajv/issues/291#issuecomment-259923858). If the type of data is different, the validation will pass. + +Custom formats can be also added via `formats` option. + + +##### .addKeyword(String keyword, Object definition) -> Ajv + +Add custom validation keyword to Ajv instance. + +Keyword should be different from all standard JSON Schema keywords and different from previously defined keywords. There is no way to redefine keywords or to remove keyword definition from the instance. + +Keyword must start with a letter, `_` or `$`, and may continue with letters, numbers, `_`, `$`, or `-`. +It is recommended to use an application-specific prefix for keywords to avoid current and future name collisions. + +Example Keywords: +- `"xyz-example"`: valid, and uses prefix for the xyz project to avoid name collisions. +- `"example"`: valid, but not recommended as it could collide with future versions of JSON Schema etc. +- `"3-example"`: invalid as numbers are not allowed to be the first character in a keyword + +Keyword definition is an object with the following properties: + +- _type_: optional string or array of strings with data type(s) that the keyword applies to. If not present, the keyword will apply to all types. +- _validate_: validating function +- _compile_: compiling function +- _macro_: macro function +- _inline_: compiling function that returns code (as string) +- _schema_: an optional `false` value used with "validate" keyword to not pass schema +- _metaSchema_: an optional meta-schema for keyword schema +- _dependencies_: an optional list of properties that must be present in the parent schema - it will be checked during schema compilation +- _modifying_: `true` MUST be passed if keyword modifies data +- _statements_: `true` can be passed in case inline keyword generates statements (as opposed to expression) +- _valid_: pass `true`/`false` to pre-define validation result, the result returned from validation function will be ignored. This option cannot be used with macro keywords. +- _$data_: an optional `true` value to support [$data reference](#data-reference) as the value of custom keyword. The reference will be resolved at validation time. If the keyword has meta-schema it would be extended to allow $data and it will be used to validate the resolved value. Supporting $data reference requires that keyword has validating function (as the only option or in addition to compile, macro or inline function). +- _async_: an optional `true` value if the validation function is asynchronous (whether it is compiled or passed in _validate_ property); in this case it should return a promise that resolves with a value `true` or `false`. This option is ignored in case of "macro" and "inline" keywords. +- _errors_: an optional boolean or string `"full"` indicating whether keyword returns errors. If this property is not set Ajv will determine if the errors were set in case of failed validation. + +_compile_, _macro_ and _inline_ are mutually exclusive, only one should be used at a time. _validate_ can be used separately or in addition to them to support $data reference. + +__Please note__: If the keyword is validating data type that is different from the type(s) in its definition, the validation function will not be called (and expanded macro will not be used), so there is no need to check for data type inside validation function or inside schema returned by macro function (unless you want to enforce a specific type and for some reason do not want to use a separate `type` keyword for that). In the same way as standard keywords work, if the keyword does not apply to the data type being validated, the validation of this keyword will succeed. + +See [Defining custom keywords](#defining-custom-keywords) for more details. + + +##### .getKeyword(String keyword) -> Object|Boolean + +Returns custom keyword definition, `true` for pre-defined keywords and `false` if the keyword is unknown. + + +##### .removeKeyword(String keyword) -> Ajv + +Removes custom or pre-defined keyword so you can redefine them. + +While this method can be used to extend pre-defined keywords, it can also be used to completely change their meaning - it may lead to unexpected results. + +__Please note__: schemas compiled before the keyword is removed will continue to work without changes. To recompile schemas use `removeSchema` method and compile them again. + + +##### .errorsText([Array<Object> errors [, Object options]]) -> String + +Returns the text with all errors in a String. + +Options can have properties `separator` (string used to separate errors, ", " by default) and `dataVar` (the variable name that dataPaths are prefixed with, "data" by default). + + +## Options + +Defaults: + +```javascript +{ + // validation and reporting options: + $data: false, + allErrors: false, + verbose: false, + $comment: false, // NEW in Ajv version 6.0 + jsonPointers: false, + uniqueItems: true, + unicode: true, + nullable: false, + format: 'fast', + formats: {}, + unknownFormats: true, + schemas: {}, + logger: undefined, + // referenced schema options: + schemaId: '$id', + missingRefs: true, + extendRefs: 'ignore', // recommended 'fail' + loadSchema: undefined, // function(uri: string): Promise {} + // options to modify validated data: + removeAdditional: false, + useDefaults: false, + coerceTypes: false, + // strict mode options + strictDefaults: false, + strictKeywords: false, + strictNumbers: false, + // asynchronous validation options: + transpile: undefined, // requires ajv-async package + // advanced options: + meta: true, + validateSchema: true, + addUsedSchema: true, + inlineRefs: true, + passContext: false, + loopRequired: Infinity, + ownProperties: false, + multipleOfPrecision: false, + errorDataPath: 'object', // deprecated + messages: true, + sourceCode: false, + processCode: undefined, // function (str: string, schema: object): string {} + cache: new Cache, + serialize: undefined +} +``` + +##### Validation and reporting options + +- _$data_: support [$data references](#data-reference). Draft 6 meta-schema that is added by default will be extended to allow them. If you want to use another meta-schema you need to use $dataMetaSchema method to add support for $data reference. See [API](#api). +- _allErrors_: check all rules collecting all errors. Default is to return after the first error. +- _verbose_: include the reference to the part of the schema (`schema` and `parentSchema`) and validated data in errors (false by default). +- _$comment_ (NEW in Ajv version 6.0): log or pass the value of `$comment` keyword to a function. Option values: + - `false` (default): ignore $comment keyword. + - `true`: log the keyword value to console. + - function: pass the keyword value, its schema path and root schema to the specified function +- _jsonPointers_: set `dataPath` property of errors using [JSON Pointers](https://tools.ietf.org/html/rfc6901) instead of JavaScript property access notation. +- _uniqueItems_: validate `uniqueItems` keyword (true by default). +- _unicode_: calculate correct length of strings with unicode pairs (true by default). Pass `false` to use `.length` of strings that is faster, but gives "incorrect" lengths of strings with unicode pairs - each unicode pair is counted as two characters. +- _nullable_: support keyword "nullable" from [Open API 3 specification](https://swagger.io/docs/specification/data-models/data-types/). +- _format_: formats validation mode. Option values: + - `"fast"` (default) - simplified and fast validation (see [Formats](#formats) for details of which formats are available and affected by this option). + - `"full"` - more restrictive and slow validation. E.g., 25:00:00 and 2015/14/33 will be invalid time and date in 'full' mode but it will be valid in 'fast' mode. + - `false` - ignore all format keywords. +- _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method. +- _keywords_: an object with custom keywords. Keys and values will be passed to `addKeyword` method. +- _unknownFormats_: handling of unknown formats. Option values: + - `true` (default) - if an unknown format is encountered the exception is thrown during schema compilation. If `format` keyword value is [$data reference](#data-reference) and it is unknown the validation will fail. + - `[String]` - an array of unknown format names that will be ignored. This option can be used to allow usage of third party schemas with format(s) for which you don't have definitions, but still fail if another unknown format is used. If `format` keyword value is [$data reference](#data-reference) and it is not in this array the validation will fail. + - `"ignore"` - to log warning during schema compilation and always pass validation (the default behaviour in versions before 5.0.0). This option is not recommended, as it allows to mistype format name and it won't be validated without any error message. This behaviour is required by JSON Schema specification. +- _schemas_: an array or object of schemas that will be added to the instance. In case you pass the array the schemas must have IDs in them. When the object is passed the method `addSchema(value, key)` will be called for each schema in this object. +- _logger_: sets the logging method. Default is the global `console` object that should have methods `log`, `warn` and `error`. See [Error logging](#error-logging). Option values: + - custom logger - it should have methods `log`, `warn` and `error`. If any of these methods is missing an exception will be thrown. + - `false` - logging is disabled. + + +##### Referenced schema options + +- _schemaId_: this option defines which keywords are used as schema URI. Option value: + - `"$id"` (default) - only use `$id` keyword as schema URI (as specified in JSON Schema draft-06/07), ignore `id` keyword (if it is present a warning will be logged). + - `"id"` - only use `id` keyword as schema URI (as specified in JSON Schema draft-04), ignore `$id` keyword (if it is present a warning will be logged). + - `"auto"` - use both `$id` and `id` keywords as schema URI. If both are present (in the same schema object) and different the exception will be thrown during schema compilation. +- _missingRefs_: handling of missing referenced schemas. Option values: + - `true` (default) - if the reference cannot be resolved during compilation the exception is thrown. The thrown error has properties `missingRef` (with hash fragment) and `missingSchema` (without it). Both properties are resolved relative to the current base id (usually schema id, unless it was substituted). + - `"ignore"` - to log error during compilation and always pass validation. + - `"fail"` - to log error and successfully compile schema but fail validation if this rule is checked. +- _extendRefs_: validation of other keywords when `$ref` is present in the schema. Option values: + - `"ignore"` (default) - when `$ref` is used other keywords are ignored (as per [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03#section-3) standard). A warning will be logged during the schema compilation. + - `"fail"` (recommended) - if other validation keywords are used together with `$ref` the exception will be thrown when the schema is compiled. This option is recommended to make sure schema has no keywords that are ignored, which can be confusing. + - `true` - validate all keywords in the schemas with `$ref` (the default behaviour in versions before 5.0.0). +- _loadSchema_: asynchronous function that will be used to load remote schemas when `compileAsync` [method](#api-compileAsync) is used and some reference is missing (option `missingRefs` should NOT be 'fail' or 'ignore'). This function should accept remote schema uri as a parameter and return a Promise that resolves to a schema. See example in [Asynchronous compilation](#asynchronous-schema-compilation). + + +##### Options to modify validated data + +- _removeAdditional_: remove additional properties - see example in [Filtering data](#filtering-data). This option is not used if schema is added with `addMetaSchema` method. Option values: + - `false` (default) - not to remove additional properties + - `"all"` - all additional properties are removed, regardless of `additionalProperties` keyword in schema (and no validation is made for them). + - `true` - only additional properties with `additionalProperties` keyword equal to `false` are removed. + - `"failing"` - additional properties that fail schema validation will be removed (where `additionalProperties` keyword is `false` or schema). +- _useDefaults_: replace missing or undefined properties and items with the values from corresponding `default` keywords. Default behaviour is to ignore `default` keywords. This option is not used if schema is added with `addMetaSchema` method. See examples in [Assigning defaults](#assigning-defaults). Option values: + - `false` (default) - do not use defaults + - `true` - insert defaults by value (object literal is used). + - `"empty"` - in addition to missing or undefined, use defaults for properties and items that are equal to `null` or `""` (an empty string). + - `"shared"` (deprecated) - insert defaults by reference. If the default is an object, it will be shared by all instances of validated data. If you modify the inserted default in the validated data, it will be modified in the schema as well. +- _coerceTypes_: change data type of data to match `type` keyword. See the example in [Coercing data types](#coercing-data-types) and [coercion rules](https://github.com/ajv-validator/ajv/blob/master/COERCION.md). Option values: + - `false` (default) - no type coercion. + - `true` - coerce scalar data types. + - `"array"` - in addition to coercions between scalar types, coerce scalar data to an array with one element and vice versa (as required by the schema). + + +##### Strict mode options + +- _strictDefaults_: report ignored `default` keywords in schemas. Option values: + - `false` (default) - ignored defaults are not reported + - `true` - if an ignored default is present, throw an error + - `"log"` - if an ignored default is present, log warning +- _strictKeywords_: report unknown keywords in schemas. Option values: + - `false` (default) - unknown keywords are not reported + - `true` - if an unknown keyword is present, throw an error + - `"log"` - if an unknown keyword is present, log warning +- _strictNumbers_: validate numbers strictly, failing validation for NaN and Infinity. Option values: + - `false` (default) - NaN or Infinity will pass validation for numeric types + - `true` - NaN or Infinity will not pass validation for numeric types + +##### Asynchronous validation options + +- _transpile_: Requires [ajv-async](https://github.com/ajv-validator/ajv-async) package. It determines whether Ajv transpiles compiled asynchronous validation function. Option values: + - `undefined` (default) - transpile with [nodent](https://github.com/MatAtBread/nodent) if async functions are not supported. + - `true` - always transpile with nodent. + - `false` - do not transpile; if async functions are not supported an exception will be thrown. + + +##### Advanced options + +- _meta_: add [meta-schema](http://json-schema.org/documentation.html) so it can be used by other schemas (true by default). If an object is passed, it will be used as the default meta-schema for schemas that have no `$schema` keyword. This default meta-schema MUST have `$schema` keyword. +- _validateSchema_: validate added/compiled schemas against meta-schema (true by default). `$schema` property in the schema can be http://json-schema.org/draft-07/schema or absent (draft-07 meta-schema will be used) or can be a reference to the schema previously added with `addMetaSchema` method. Option values: + - `true` (default) - if the validation fails, throw the exception. + - `"log"` - if the validation fails, log error. + - `false` - skip schema validation. +- _addUsedSchema_: by default methods `compile` and `validate` add schemas to the instance if they have `$id` (or `id`) property that doesn't start with "#". If `$id` is present and it is not unique the exception will be thrown. Set this option to `false` to skip adding schemas to the instance and the `$id` uniqueness check when these methods are used. This option does not affect `addSchema` method. +- _inlineRefs_: Affects compilation of referenced schemas. Option values: + - `true` (default) - the referenced schemas that don't have refs in them are inlined, regardless of their size - that substantially improves performance at the cost of the bigger size of compiled schema functions. + - `false` - to not inline referenced schemas (they will be compiled as separate functions). + - integer number - to limit the maximum number of keywords of the schema that will be inlined. +- _passContext_: pass validation context to custom keyword functions. If this option is `true` and you pass some context to the compiled validation function with `validate.call(context, data)`, the `context` will be available as `this` in your custom keywords. By default `this` is Ajv instance. +- _loopRequired_: by default `required` keyword is compiled into a single expression (or a sequence of statements in `allErrors` mode). In case of a very large number of properties in this keyword it may result in a very big validation function. Pass integer to set the number of properties above which `required` keyword will be validated in a loop - smaller validation function size but also worse performance. +- _ownProperties_: by default Ajv iterates over all enumerable object properties; when this option is `true` only own enumerable object properties (i.e. found directly on the object rather than on its prototype) are iterated. Contributed by @mbroadst. +- _multipleOfPrecision_: by default `multipleOf` keyword is validated by comparing the result of division with parseInt() of that result. It works for dividers that are bigger than 1. For small dividers such as 0.01 the result of the division is usually not integer (even when it should be integer, see issue [#84](https://github.com/ajv-validator/ajv/issues/84)). If you need to use fractional dividers set this option to some positive integer N to have `multipleOf` validated using this formula: `Math.abs(Math.round(division) - division) < 1e-N` (it is slower but allows for float arithmetics deviations). +- _errorDataPath_ (deprecated): set `dataPath` to point to 'object' (default) or to 'property' when validating keywords `required`, `additionalProperties` and `dependencies`. +- _messages_: Include human-readable messages in errors. `true` by default. `false` can be passed when custom messages are used (e.g. with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n)). +- _sourceCode_: add `sourceCode` property to validating function (for debugging; this code can be different from the result of toString call). +- _processCode_: an optional function to process generated code before it is passed to Function constructor. It can be used to either beautify (the validating function is generated without line-breaks) or to transpile code. Starting from version 5.0.0 this option replaced options: + - `beautify` that formatted the generated function using [js-beautify](https://github.com/beautify-web/js-beautify). If you want to beautify the generated code pass a function calling `require('js-beautify').js_beautify` as `processCode: code => js_beautify(code)`. + - `transpile` that transpiled asynchronous validation function. You can still use `transpile` option with [ajv-async](https://github.com/ajv-validator/ajv-async) package. See [Asynchronous validation](#asynchronous-validation) for more information. +- _cache_: an optional instance of cache to store compiled schemas using stable-stringified schema as a key. For example, set-associative cache [sacjs](https://github.com/epoberezkin/sacjs) can be used. If not passed then a simple hash is used which is good enough for the common use case (a limited number of statically defined schemas). Cache should have methods `put(key, value)`, `get(key)`, `del(key)` and `clear()`. +- _serialize_: an optional function to serialize schema to cache key. Pass `false` to use schema itself as a key (e.g., if WeakMap used as a cache). By default [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used. + + +## Validation errors + +In case of validation failure, Ajv assigns the array of errors to `errors` property of validation function (or to `errors` property of Ajv instance when `validate` or `validateSchema` methods were called). In case of [asynchronous validation](#asynchronous-validation), the returned promise is rejected with exception `Ajv.ValidationError` that has `errors` property. + + +### Error objects + +Each error is an object with the following properties: + +- _keyword_: validation keyword. +- _dataPath_: the path to the part of the data that was validated. By default `dataPath` uses JavaScript property access notation (e.g., `".prop[1].subProp"`). When the option `jsonPointers` is true (see [Options](#options)) `dataPath` will be set using JSON pointer standard (e.g., `"/prop/1/subProp"`). +- _schemaPath_: the path (JSON-pointer as a URI fragment) to the schema of the keyword that failed validation. +- _params_: the object with the additional information about error that can be used to create custom error messages (e.g., using [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package). See below for parameters set by all keywords. +- _message_: the standard error message (can be excluded with option `messages` set to false). +- _schema_: the schema of the keyword (added with `verbose` option). +- _parentSchema_: the schema containing the keyword (added with `verbose` option) +- _data_: the data validated by the keyword (added with `verbose` option). + +__Please note__: `propertyNames` keyword schema validation errors have an additional property `propertyName`, `dataPath` points to the object. After schema validation for each property name, if it is invalid an additional error is added with the property `keyword` equal to `"propertyNames"`. + + +### Error parameters + +Properties of `params` object in errors depend on the keyword that failed validation. + +- `maxItems`, `minItems`, `maxLength`, `minLength`, `maxProperties`, `minProperties` - property `limit` (number, the schema of the keyword). +- `additionalItems` - property `limit` (the maximum number of allowed items in case when `items` keyword is an array of schemas and `additionalItems` is false). +- `additionalProperties` - property `additionalProperty` (the property not used in `properties` and `patternProperties` keywords). +- `dependencies` - properties: + - `property` (dependent property), + - `missingProperty` (required missing dependency - only the first one is reported currently) + - `deps` (required dependencies, comma separated list as a string), + - `depsCount` (the number of required dependencies). +- `format` - property `format` (the schema of the keyword). +- `maximum`, `minimum` - properties: + - `limit` (number, the schema of the keyword), + - `exclusive` (boolean, the schema of `exclusiveMaximum` or `exclusiveMinimum`), + - `comparison` (string, comparison operation to compare the data to the limit, with the data on the left and the limit on the right; can be "<", "<=", ">", ">=") +- `multipleOf` - property `multipleOf` (the schema of the keyword) +- `pattern` - property `pattern` (the schema of the keyword) +- `required` - property `missingProperty` (required property that is missing). +- `propertyNames` - property `propertyName` (an invalid property name). +- `patternRequired` (in ajv-keywords) - property `missingPattern` (required pattern that did not match any property). +- `type` - property `type` (required type(s), a string, can be a comma-separated list) +- `uniqueItems` - properties `i` and `j` (indices of duplicate items). +- `const` - property `allowedValue` pointing to the value (the schema of the keyword). +- `enum` - property `allowedValues` pointing to the array of values (the schema of the keyword). +- `$ref` - property `ref` with the referenced schema URI. +- `oneOf` - property `passingSchemas` (array of indices of passing schemas, null if no schema passes). +- custom keywords (in case keyword definition doesn't create errors) - property `keyword` (the keyword name). + + +### Error logging + +Using the `logger` option when initiallizing Ajv will allow you to define custom logging. Here you can build upon the exisiting logging. The use of other logging packages is supported as long as the package or its associated wrapper exposes the required methods. If any of the required methods are missing an exception will be thrown. +- **Required Methods**: `log`, `warn`, `error` + +```javascript +var otherLogger = new OtherLogger(); +var ajv = new Ajv({ + logger: { + log: console.log.bind(console), + warn: function warn() { + otherLogger.logWarn.apply(otherLogger, arguments); + }, + error: function error() { + otherLogger.logError.apply(otherLogger, arguments); + console.error.apply(console, arguments); + } + } +}); +``` + + +## Plugins + +Ajv can be extended with plugins that add custom keywords, formats or functions to process generated code. When such plugin is published as npm package it is recommended that it follows these conventions: + +- it exports a function +- this function accepts ajv instance as the first parameter and returns the same instance to allow chaining +- this function can accept an optional configuration as the second parameter + +If you have published a useful plugin please submit a PR to add it to the next section. + + +## Related packages + +- [ajv-async](https://github.com/ajv-validator/ajv-async) - plugin to configure async validation mode +- [ajv-bsontype](https://github.com/BoLaMN/ajv-bsontype) - plugin to validate mongodb's bsonType formats +- [ajv-cli](https://github.com/jessedc/ajv-cli) - command line interface +- [ajv-errors](https://github.com/ajv-validator/ajv-errors) - plugin for custom error messages +- [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) - internationalised error messages +- [ajv-istanbul](https://github.com/ajv-validator/ajv-istanbul) - plugin to instrument generated validation code to measure test coverage of your schemas +- [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) - plugin with custom validation keywords (select, typeof, etc.) +- [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) - plugin with keywords $merge and $patch +- [ajv-pack](https://github.com/ajv-validator/ajv-pack) - produces a compact module exporting validation functions +- [ajv-formats-draft2019](https://github.com/luzlab/ajv-formats-draft2019) - format validators for draft2019 that aren't already included in ajv (ie. `idn-hostname`, `idn-email`, `iri`, `iri-reference` and `duration`). + +## Some packages using Ajv + +- [webpack](https://github.com/webpack/webpack) - a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser +- [jsonscript-js](https://github.com/JSONScript/jsonscript-js) - the interpreter for [JSONScript](http://www.jsonscript.org) - scripted processing of existing endpoints and services +- [osprey-method-handler](https://github.com/mulesoft-labs/osprey-method-handler) - Express middleware for validating requests and responses based on a RAML method object, used in [osprey](https://github.com/mulesoft/osprey) - validating API proxy generated from a RAML definition +- [har-validator](https://github.com/ahmadnassri/har-validator) - HTTP Archive (HAR) validator +- [jsoneditor](https://github.com/josdejong/jsoneditor) - a web-based tool to view, edit, format, and validate JSON http://jsoneditoronline.org +- [JSON Schema Lint](https://github.com/nickcmaynard/jsonschemalint) - a web tool to validate JSON/YAML document against a single JSON Schema http://jsonschemalint.com +- [objection](https://github.com/vincit/objection.js) - SQL-friendly ORM for Node.js +- [table](https://github.com/gajus/table) - formats data into a string table +- [ripple-lib](https://github.com/ripple/ripple-lib) - a JavaScript API for interacting with [Ripple](https://ripple.com) in Node.js and the browser +- [restbase](https://github.com/wikimedia/restbase) - distributed storage with REST API & dispatcher for backend services built to provide a low-latency & high-throughput API for Wikipedia / Wikimedia content +- [hippie-swagger](https://github.com/CacheControl/hippie-swagger) - [Hippie](https://github.com/vesln/hippie) wrapper that provides end to end API testing with swagger validation +- [react-form-controlled](https://github.com/seeden/react-form-controlled) - React controlled form components with validation +- [rabbitmq-schema](https://github.com/tjmehta/rabbitmq-schema) - a schema definition module for RabbitMQ graphs and messages +- [@query/schema](https://www.npmjs.com/package/@query/schema) - stream filtering with a URI-safe query syntax parsing to JSON Schema +- [chai-ajv-json-schema](https://github.com/peon374/chai-ajv-json-schema) - chai plugin to us JSON Schema with expect in mocha tests +- [grunt-jsonschema-ajv](https://github.com/SignpostMarv/grunt-jsonschema-ajv) - Grunt plugin for validating files against JSON Schema +- [extract-text-webpack-plugin](https://github.com/webpack-contrib/extract-text-webpack-plugin) - extract text from bundle into a file +- [electron-builder](https://github.com/electron-userland/electron-builder) - a solution to package and build a ready for distribution Electron app +- [addons-linter](https://github.com/mozilla/addons-linter) - Mozilla Add-ons Linter +- [gh-pages-generator](https://github.com/epoberezkin/gh-pages-generator) - multi-page site generator converting markdown files to GitHub pages +- [ESLint](https://github.com/eslint/eslint) - the pluggable linting utility for JavaScript and JSX + + +## Tests + +``` +npm install +git submodule update --init +npm test +``` + +## Contributing + +All validation functions are generated using doT templates in [dot](https://github.com/ajv-validator/ajv/tree/master/lib/dot) folder. Templates are precompiled so doT is not a run-time dependency. + +`npm run build` - compiles templates to [dotjs](https://github.com/ajv-validator/ajv/tree/master/lib/dotjs) folder. + +`npm run watch` - automatically compiles templates when files in dot folder change + +Please see [Contributing guidelines](https://github.com/ajv-validator/ajv/blob/master/CONTRIBUTING.md) + + +## Changes history + +See https://github.com/ajv-validator/ajv/releases + +__Please note__: [Changes in version 7.0.0-beta](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0-beta.0) + +[Version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0). + +## Code of conduct + +Please review and follow the [Code of conduct](https://github.com/ajv-validator/ajv/blob/master/CODE_OF_CONDUCT.md). + +Please report any unacceptable behaviour to ajv.validator@gmail.com - it will be reviewed by the project team. + + +## Open-source software support + +Ajv is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers. + + +## License + +[MIT](https://github.com/ajv-validator/ajv/blob/master/LICENSE) diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/dist/ajv.bundle.js b/node_modules/terser-webpack-plugin/node_modules/ajv/dist/ajv.bundle.js new file mode 100644 index 0000000..e4d9d15 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/dist/ajv.bundle.js @@ -0,0 +1,7189 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Ajv = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; +// For the source: https://gist.github.com/dperini/729294 +// For test cases: https://mathiasbynens.be/demo/url-regex +// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983. +// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; +var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i; +var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; +var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; +var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; +var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; + + +module.exports = formats; + +function formats(mode) { + mode = mode == 'full' ? 'full' : 'fast'; + return util.copy(formats[mode]); +} + + +formats.fast = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, + 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + 'uri-reference': /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + 'uri-template': URITEMPLATE, + url: URL, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation') + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, + hostname: HOSTNAME, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a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?:%.+)?\s*$/i, + regex: regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: UUID, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + 'json-pointer': JSON_POINTER, + 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; + + +formats.full = { + date: date, + time: time, + 'date-time': date_time, + uri: uri, + 'uri-reference': URIREF, + 'uri-template': URITEMPLATE, + url: URL, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: HOSTNAME, + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, + regex: regex, + uuid: UUID, + 'json-pointer': JSON_POINTER, + 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; + + +function isLeapYear(year) { + // https://tools.ietf.org/html/rfc3339#appendix-C + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} + + +function date(str) { + // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 + var matches = str.match(DATE); + if (!matches) return false; + + var year = +matches[1]; + var month = +matches[2]; + var day = +matches[3]; + + return month >= 1 && month <= 12 && day >= 1 && + day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); +} + + +function time(str, full) { + var matches = str.match(TIME); + if (!matches) return false; + + var hour = matches[1]; + var minute = matches[2]; + var second = matches[3]; + var timeZone = matches[5]; + return ((hour <= 23 && minute <= 59 && second <= 59) || + (hour == 23 && minute == 59 && second == 60)) && + (!full || timeZone); +} + + +var DATE_TIME_SEPARATOR = /t|\s/i; +function date_time(str) { + // http://tools.ietf.org/html/rfc3339#section-5.6 + var dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); +} + + +var NOT_URI_FRAGMENT = /\/|:/; +function uri(str) { + // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." + return NOT_URI_FRAGMENT.test(str) && URI.test(str); +} + + +var Z_ANCHOR = /[^\\]\\Z/; +function regex(str) { + if (Z_ANCHOR.test(str)) return false; + try { + new RegExp(str); + return true; + } catch(e) { + return false; + } +} + +},{"./util":10}],5:[function(require,module,exports){ +'use strict'; + +var resolve = require('./resolve') + , util = require('./util') + , errorClasses = require('./error_classes') + , stableStringify = require('fast-json-stable-stringify'); + +var validateGenerator = require('../dotjs/validate'); + +/** + * Functions below are used inside compiled validations function + */ + +var ucs2length = util.ucs2length; +var equal = require('fast-deep-equal'); + +// this error is thrown by async schemas to return validation errors via exception +var ValidationError = errorClasses.Validation; + +module.exports = compile; + + +/** + * Compiles schema to validation function + * @this Ajv + * @param {Object} schema schema object + * @param {Object} root object with information about the root schema for this schema + * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution + * @param {String} baseId base ID for IDs in the schema + * @return {Function} validation function + */ +function compile(schema, root, localRefs, baseId) { + /* jshint validthis: true, evil: true */ + /* eslint no-shadow: 0 */ + var self = this + , opts = this._opts + , refVal = [ undefined ] + , refs = {} + , patterns = [] + , patternsHash = {} + , defaults = [] + , defaultsHash = {} + , customRules = []; + + root = root || { schema: schema, refVal: refVal, refs: refs }; + + var c = checkCompiling.call(this, schema, root, baseId); + var compilation = this._compilations[c.index]; + if (c.compiling) return (compilation.callValidate = callValidate); + + var formats = this._formats; + var RULES = this.RULES; + + try { + var v = localCompile(schema, root, localRefs, baseId); + compilation.validate = v; + var cv = compilation.callValidate; + if (cv) { + cv.schema = v.schema; + cv.errors = null; + cv.refs = v.refs; + cv.refVal = v.refVal; + cv.root = v.root; + cv.$async = v.$async; + if (opts.sourceCode) cv.source = v.source; + } + return v; + } finally { + endCompiling.call(this, schema, root, baseId); + } + + /* @this {*} - custom context, see passContext option */ + function callValidate() { + /* jshint validthis: true */ + var validate = compilation.validate; + var result = validate.apply(this, arguments); + callValidate.errors = validate.errors; + return result; + } + + function localCompile(_schema, _root, localRefs, baseId) { + var isRoot = !_root || (_root && _root.schema == _schema); + if (_root.schema != root.schema) + return compile.call(self, _schema, _root, localRefs, baseId); + + var $async = _schema.$async === true; + + var sourceCode = validateGenerator({ + isTop: true, + schema: _schema, + isRoot: isRoot, + baseId: baseId, + root: _root, + schemaPath: '', + errSchemaPath: '#', + errorPath: '""', + MissingRefError: errorClasses.MissingRef, + RULES: RULES, + validate: validateGenerator, + util: util, + resolve: resolve, + resolveRef: resolveRef, + usePattern: usePattern, + useDefault: useDefault, + useCustomRule: useCustomRule, + opts: opts, + formats: formats, + logger: self.logger, + self: self + }); + + sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + + sourceCode; + + if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema); + // console.log('\n\n\n *** \n', JSON.stringify(sourceCode)); + var validate; + try { + var makeValidate = new Function( + 'self', + 'RULES', + 'formats', + 'root', + 'refVal', + 'defaults', + 'customRules', + 'equal', + 'ucs2length', + 'ValidationError', + sourceCode + ); + + validate = makeValidate( + self, + RULES, + formats, + root, + refVal, + defaults, + customRules, + equal, + ucs2length, + ValidationError + ); + + refVal[0] = validate; + } catch(e) { + self.logger.error('Error compiling schema, function code:', sourceCode); + throw e; + } + + validate.schema = _schema; + validate.errors = null; + validate.refs = refs; + validate.refVal = refVal; + validate.root = isRoot ? validate : _root; + if ($async) validate.$async = true; + if (opts.sourceCode === true) { + validate.source = { + code: sourceCode, + patterns: patterns, + defaults: defaults + }; + } + + return validate; + } + + function resolveRef(baseId, ref, isRoot) { + ref = resolve.url(baseId, ref); + var refIndex = refs[ref]; + var _refVal, refCode; + if (refIndex !== undefined) { + _refVal = refVal[refIndex]; + refCode = 'refVal[' + refIndex + ']'; + return resolvedRef(_refVal, refCode); + } + if (!isRoot && root.refs) { + var rootRefId = root.refs[ref]; + if (rootRefId !== undefined) { + _refVal = root.refVal[rootRefId]; + refCode = addLocalRef(ref, _refVal); + return resolvedRef(_refVal, refCode); + } + } + + refCode = addLocalRef(ref); + var v = resolve.call(self, localCompile, root, ref); + if (v === undefined) { + var localSchema = localRefs && localRefs[ref]; + if (localSchema) { + v = resolve.inlineRef(localSchema, opts.inlineRefs) + ? localSchema + : compile.call(self, localSchema, root, localRefs, baseId); + } + } + + if (v === undefined) { + removeLocalRef(ref); + } else { + replaceLocalRef(ref, v); + return resolvedRef(v, refCode); + } + } + + function addLocalRef(ref, v) { + var refId = refVal.length; + refVal[refId] = v; + refs[ref] = refId; + return 'refVal' + refId; + } + + function removeLocalRef(ref) { + delete refs[ref]; + } + + function replaceLocalRef(ref, v) { + var refId = refs[ref]; + refVal[refId] = v; + } + + function resolvedRef(refVal, code) { + return typeof refVal == 'object' || typeof refVal == 'boolean' + ? { code: code, schema: refVal, inline: true } + : { code: code, $async: refVal && !!refVal.$async }; + } + + function usePattern(regexStr) { + var index = patternsHash[regexStr]; + if (index === undefined) { + index = patternsHash[regexStr] = patterns.length; + patterns[index] = regexStr; + } + return 'pattern' + index; + } + + function useDefault(value) { + switch (typeof value) { + case 'boolean': + case 'number': + return '' + value; + case 'string': + return util.toQuotedString(value); + case 'object': + if (value === null) return 'null'; + var valueStr = stableStringify(value); + var index = defaultsHash[valueStr]; + if (index === undefined) { + index = defaultsHash[valueStr] = defaults.length; + defaults[index] = value; + } + return 'default' + index; + } + } + + function useCustomRule(rule, schema, parentSchema, it) { + if (self._opts.validateSchema !== false) { + var deps = rule.definition.dependencies; + if (deps && !deps.every(function(keyword) { + return Object.prototype.hasOwnProperty.call(parentSchema, keyword); + })) + throw new Error('parent schema must have all required keywords: ' + deps.join(',')); + + var validateSchema = rule.definition.validateSchema; + if (validateSchema) { + var valid = validateSchema(schema); + if (!valid) { + var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors); + if (self._opts.validateSchema == 'log') self.logger.error(message); + else throw new Error(message); + } + } + } + + var compile = rule.definition.compile + , inline = rule.definition.inline + , macro = rule.definition.macro; + + var validate; + if (compile) { + validate = compile.call(self, schema, parentSchema, it); + } else if (macro) { + validate = macro.call(self, schema, parentSchema, it); + if (opts.validateSchema !== false) self.validateSchema(validate, true); + } else if (inline) { + validate = inline.call(self, it, rule.keyword, schema, parentSchema); + } else { + validate = rule.definition.validate; + if (!validate) return; + } + + if (validate === undefined) + throw new Error('custom keyword "' + rule.keyword + '"failed to compile'); + + var index = customRules.length; + customRules[index] = validate; + + return { + code: 'customRule' + index, + validate: validate + }; + } +} + + +/** + * Checks if the schema is currently compiled + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean) + */ +function checkCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var index = compIndex.call(this, schema, root, baseId); + if (index >= 0) return { index: index, compiling: true }; + index = this._compilations.length; + this._compilations[index] = { + schema: schema, + root: root, + baseId: baseId + }; + return { index: index, compiling: false }; +} + + +/** + * Removes the schema from the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + */ +function endCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var i = compIndex.call(this, schema, root, baseId); + if (i >= 0) this._compilations.splice(i, 1); +} + + +/** + * Index of schema compilation in the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Integer} compilation index + */ +function compIndex(schema, root, baseId) { + /* jshint validthis: true */ + for (var i=0; i= 0xD800 && value <= 0xDBFF && pos < len) { + // high surrogate, and there is a next character + value = str.charCodeAt(pos); + if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate + } + } + return length; +}; + +},{}],10:[function(require,module,exports){ +'use strict'; + + +module.exports = { + copy: copy, + checkDataType: checkDataType, + checkDataTypes: checkDataTypes, + coerceToTypes: coerceToTypes, + toHash: toHash, + getProperty: getProperty, + escapeQuotes: escapeQuotes, + equal: require('fast-deep-equal'), + ucs2length: require('./ucs2length'), + varOccurences: varOccurences, + varReplace: varReplace, + schemaHasRules: schemaHasRules, + schemaHasRulesExcept: schemaHasRulesExcept, + schemaUnknownRules: schemaUnknownRules, + toQuotedString: toQuotedString, + getPathExpr: getPathExpr, + getPath: getPath, + getData: getData, + unescapeFragment: unescapeFragment, + unescapeJsonPointer: unescapeJsonPointer, + escapeFragment: escapeFragment, + escapeJsonPointer: escapeJsonPointer +}; + + +function copy(o, to) { + to = to || {}; + for (var key in o) to[key] = o[key]; + return to; +} + + +function checkDataType(dataType, data, strictNumbers, negate) { + var EQUAL = negate ? ' !== ' : ' === ' + , AND = negate ? ' || ' : ' && ' + , OK = negate ? '!' : '' + , NOT = negate ? '' : '!'; + switch (dataType) { + case 'null': return data + EQUAL + 'null'; + case 'array': return OK + 'Array.isArray(' + data + ')'; + case 'object': return '(' + OK + data + AND + + 'typeof ' + data + EQUAL + '"object"' + AND + + NOT + 'Array.isArray(' + data + '))'; + case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND + + NOT + '(' + data + ' % 1)' + + AND + data + EQUAL + data + + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; + case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' + + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; + default: return 'typeof ' + data + EQUAL + '"' + dataType + '"'; + } +} + + +function checkDataTypes(dataTypes, data, strictNumbers) { + switch (dataTypes.length) { + case 1: return checkDataType(dataTypes[0], data, strictNumbers, true); + default: + var code = ''; + var types = toHash(dataTypes); + if (types.array && types.object) { + code = types.null ? '(': '(!' + data + ' || '; + code += 'typeof ' + data + ' !== "object")'; + delete types.null; + delete types.array; + delete types.object; + } + if (types.number) delete types.integer; + for (var t in types) + code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true); + + return code; + } +} + + +var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]); +function coerceToTypes(optionCoerceTypes, dataTypes) { + if (Array.isArray(dataTypes)) { + var types = []; + for (var i=0; i= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); + return paths[lvl - up]; + } + + if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); + data = 'data' + ((lvl - up) || ''); + if (!jsonPointer) return data; + } + + var expr = data; + var segments = jsonPointer.split('/'); + for (var i=0; i', + $notOp = $isMax ? '>' : '<', + $errorKeyword = undefined; + if (!($isData || typeof $schema == 'number' || $schema === undefined)) { + throw new Error($keyword + ' must be number'); + } + if (!($isDataExcl || $schemaExcl === undefined || typeof $schemaExcl == 'number' || typeof $schemaExcl == 'boolean')) { + throw new Error($exclusiveKeyword + ' must be number or boolean'); + } + if ($isDataExcl) { + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), + $exclusive = 'exclusive' + $lvl, + $exclType = 'exclType' + $lvl, + $exclIsNumber = 'exclIsNumber' + $lvl, + $opExpr = 'op' + $lvl, + $opStr = '\' + ' + $opExpr + ' + \''; + out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; + $schemaValueExcl = 'schemaExcl' + $lvl; + out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { '; + var $errorKeyword = $exclusiveKeyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; '; + if ($schema === undefined) { + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaValueExcl; + $isData = $isDataExcl; + } + } else { + var $exclIsNumber = typeof $schemaExcl == 'number', + $opStr = $op; + if ($exclIsNumber && $isData) { + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { '; + } else { + if ($exclIsNumber && $schema === undefined) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaExcl; + $notOp += '='; + } else { + if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema); + if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $notOp += '='; + } else { + $exclusive = false; + $opStr += '='; + } + } + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { '; + } + } + $errorKeyword = $errorKeyword || $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be ' + ($opStr) + ' '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schemaValue) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],14:[function(require,module,exports){ +'use strict'; +module.exports = function generate__limitItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxItems' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxItems') { + out += 'more'; + } else { + out += 'fewer'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],15:[function(require,module,exports){ +'use strict'; +module.exports = function generate__limitLength(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxLength' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + if (it.opts.unicode === false) { + out += ' ' + ($data) + '.length '; + } else { + out += ' ucs2length(' + ($data) + ') '; + } + out += ' ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be '; + if ($keyword == 'maxLength') { + out += 'longer'; + } else { + out += 'shorter'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' characters\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],16:[function(require,module,exports){ +'use strict'; +module.exports = function generate__limitProperties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxProperties' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxProperties') { + out += 'more'; + } else { + out += 'fewer'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' properties\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],17:[function(require,module,exports){ +'use strict'; +module.exports = function generate_allOf(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $allSchemasEmpty = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $allSchemasEmpty = false; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if ($breakOnError) { + if ($allSchemasEmpty) { + out += ' if (true) { '; + } else { + out += ' ' + ($closingBraces.slice(0, -1)) + ' '; + } + } + return out; +} + +},{}],18:[function(require,module,exports){ +'use strict'; +module.exports = function generate_anyOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $noEmptySchema = $schema.every(function($sch) { + return (it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)); + }); + if ($noEmptySchema) { + var $currentBaseId = $it.baseId; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { '; + $closingBraces += '}'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should match some schema in anyOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} + +},{}],19:[function(require,module,exports){ +'use strict'; +module.exports = function generate_comment(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $comment = it.util.toQuotedString($schema); + if (it.opts.$comment === true) { + out += ' console.log(' + ($comment) + ');'; + } else if (typeof it.opts.$comment == 'function') { + out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);'; + } + return out; +} + +},{}],20:[function(require,module,exports){ +'use strict'; +module.exports = function generate_const(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!$isData) { + out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to constant\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],21:[function(require,module,exports){ +'use strict'; +module.exports = function generate_contains(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId, + $nonEmptySchema = (it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all)); + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($nonEmptySchema) { + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' if (' + ($nextValid) + ') break; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {'; + } else { + out += ' if (' + ($data) + '.length == 0) {'; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should contain a valid item\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + if ($nonEmptySchema) { + out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + } + if (it.opts.allErrors) { + out += ' } '; + } + return out; +} + +},{}],22:[function(require,module,exports){ +'use strict'; +module.exports = function generate_custom(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $rule = this, + $definition = 'definition' + $lvl, + $rDef = $rule.definition, + $closingBraces = ''; + var $compile, $inline, $macro, $ruleValidate, $validateCode; + if ($isData && $rDef.$data) { + $validateCode = 'keywordValidate' + $lvl; + var $validateSchema = $rDef.validateSchema; + out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;'; + } else { + $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); + if (!$ruleValidate) return; + $schemaValue = 'validate.schema' + $schemaPath; + $validateCode = $ruleValidate.code; + $compile = $rDef.compile; + $inline = $rDef.inline; + $macro = $rDef.macro; + } + var $ruleErrs = $validateCode + '.errors', + $i = 'i' + $lvl, + $ruleErr = 'ruleErr' + $lvl, + $asyncKeyword = $rDef.async; + if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema'); + if (!($inline || $macro)) { + out += '' + ($ruleErrs) + ' = null;'; + } + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($isData && $rDef.$data) { + $closingBraces += '}'; + out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { '; + if ($validateSchema) { + $closingBraces += '}'; + out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { '; + } + } + if ($inline) { + if ($rDef.statements) { + out += ' ' + ($ruleValidate.validate) + ' '; + } else { + out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; '; + } + } else if ($macro) { + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $ruleValidate.validate; + $it.schemaPath = ''; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($code); + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + out += ' ' + ($validateCode) + '.call( '; + if (it.opts.passContext) { + out += 'this'; + } else { + out += 'self'; + } + if ($compile || $rDef.schema === false) { + out += ' , ' + ($data) + ' '; + } else { + out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' '; + } + out += ' , (dataPath || \'\')'; + if (it.errorPath != '""') { + out += ' + ' + (it.errorPath); + } + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) '; + var def_callRuleValidate = out; + out = $$outStack.pop(); + if ($rDef.errors === false) { + out += ' ' + ($valid) + ' = '; + if ($asyncKeyword) { + out += 'await '; + } + out += '' + (def_callRuleValidate) + '; '; + } else { + if ($asyncKeyword) { + $ruleErrs = 'customErrors' + $lvl; + out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } '; + } else { + out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; '; + } + } + } + if ($rDef.modifying) { + out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];'; + } + out += '' + ($closingBraces); + if ($rDef.valid) { + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + out += ' if ( '; + if ($rDef.valid === undefined) { + out += ' !'; + if ($macro) { + out += '' + ($nextValid); + } else { + out += '' + ($valid); + } + } else { + out += ' ' + (!$rDef.valid) + ' '; + } + out += ') { '; + $errorKeyword = $rule.keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + var def_customError = out; + out = $$outStack.pop(); + if ($inline) { + if ($rDef.errors) { + if ($rDef.errors != 'full') { + out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + ' 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; + } + out += ') { '; + $it.schema = $sch; + $it.schemaPath = $schemaPath + it.util.getProperty($property); + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property); + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} + +},{}],24:[function(require,module,exports){ +'use strict'; +module.exports = function generate_enum(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $i = 'i' + $lvl, + $vSchema = 'schema' + $lvl; + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ';'; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }'; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to one of the allowed values\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],25:[function(require,module,exports){ +'use strict'; +module.exports = function generate_format(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + if (it.opts.format === false) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $unknownFormats = it.opts.unknownFormats, + $allowUnknown = Array.isArray($unknownFormats); + if ($isData) { + var $format = 'format' + $lvl, + $isObject = 'isObject' + $lvl, + $formatType = 'formatType' + $lvl; + out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { '; + if (it.async) { + out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; '; + } + out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' ('; + if ($unknownFormats != 'ignore') { + out += ' (' + ($schemaValue) + ' && !' + ($format) + ' '; + if ($allowUnknown) { + out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 '; + } + out += ') || '; + } + out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? '; + if (it.async) { + out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) '; + } else { + out += ' ' + ($format) + '(' + ($data) + ') '; + } + out += ' : ' + ($format) + '.test(' + ($data) + '))))) {'; + } else { + var $format = it.formats[$schema]; + if (!$format) { + if ($unknownFormats == 'ignore') { + it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } else { + throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); + } + } + var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate; + var $formatType = $isObject && $format.type || 'string'; + if ($isObject) { + var $async = $format.async === true; + $format = $format.validate; + } + if ($formatType != $ruleType) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } + if ($async) { + if (!it.async) throw new Error('async format in sync schema'); + var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; + out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { '; + } else { + out += ' if (! '; + var $formatRef = 'formats' + it.util.getProperty($schema); + if ($isObject) $formatRef += '.validate'; + if (typeof $format == 'function') { + out += ' ' + ($formatRef) + '(' + ($data) + ') '; + } else { + out += ' ' + ($formatRef) + '.test(' + ($data) + ') '; + } + out += ') { '; + } + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match format "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],26:[function(require,module,exports){ +'use strict'; +module.exports = function generate_if(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + var $thenSch = it.schema['then'], + $elseSch = it.schema['else'], + $thenPresent = $thenSch !== undefined && (it.opts.strictKeywords ? (typeof $thenSch == 'object' && Object.keys($thenSch).length > 0) || $thenSch === false : it.util.schemaHasRules($thenSch, it.RULES.all)), + $elsePresent = $elseSch !== undefined && (it.opts.strictKeywords ? (typeof $elseSch == 'object' && Object.keys($elseSch).length > 0) || $elseSch === false : it.util.schemaHasRules($elseSch, it.RULES.all)), + $currentBaseId = $it.baseId; + if ($thenPresent || $elsePresent) { + var $ifClause; + $it.createErrors = false; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + $it.createErrors = true; + out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + if ($thenPresent) { + out += ' if (' + ($nextValid) + ') { '; + $it.schema = it.schema['then']; + $it.schemaPath = it.schemaPath + '.then'; + $it.errSchemaPath = it.errSchemaPath + '/then'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; + if ($thenPresent && $elsePresent) { + $ifClause = 'ifClause' + $lvl; + out += ' var ' + ($ifClause) + ' = \'then\'; '; + } else { + $ifClause = '\'then\''; + } + out += ' } '; + if ($elsePresent) { + out += ' else { '; + } + } else { + out += ' if (!' + ($nextValid) + ') { '; + } + if ($elsePresent) { + $it.schema = it.schema['else']; + $it.schemaPath = it.schemaPath + '.else'; + $it.errSchemaPath = it.errSchemaPath + '/else'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; + if ($thenPresent && $elsePresent) { + $ifClause = 'ifClause' + $lvl; + out += ' var ' + ($ifClause) + ' = \'else\'; '; + } else { + $ifClause = '\'else\''; + } + out += ' } '; + } + out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} + +},{}],27:[function(require,module,exports){ +'use strict'; + +//all requires must be explicit because browserify won't work with dynamic requires +module.exports = { + '$ref': require('./ref'), + allOf: require('./allOf'), + anyOf: require('./anyOf'), + '$comment': require('./comment'), + const: require('./const'), + contains: require('./contains'), + dependencies: require('./dependencies'), + 'enum': require('./enum'), + format: require('./format'), + 'if': require('./if'), + items: require('./items'), + maximum: require('./_limit'), + minimum: require('./_limit'), + maxItems: require('./_limitItems'), + minItems: require('./_limitItems'), + maxLength: require('./_limitLength'), + minLength: require('./_limitLength'), + maxProperties: require('./_limitProperties'), + minProperties: require('./_limitProperties'), + multipleOf: require('./multipleOf'), + not: require('./not'), + oneOf: require('./oneOf'), + pattern: require('./pattern'), + properties: require('./properties'), + propertyNames: require('./propertyNames'), + required: require('./required'), + uniqueItems: require('./uniqueItems'), + validate: require('./validate') +}; + +},{"./_limit":13,"./_limitItems":14,"./_limitLength":15,"./_limitProperties":16,"./allOf":17,"./anyOf":18,"./comment":19,"./const":20,"./contains":21,"./dependencies":23,"./enum":24,"./format":25,"./if":26,"./items":28,"./multipleOf":29,"./not":30,"./oneOf":31,"./pattern":32,"./properties":33,"./propertyNames":34,"./ref":35,"./required":36,"./uniqueItems":37,"./validate":38}],28:[function(require,module,exports){ +'use strict'; +module.exports = function generate_items(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId; + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if (Array.isArray($schema)) { + var $additionalItems = it.schema.additionalItems; + if ($additionalItems === false) { + out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { '; + var $passData = $data + '[' + $i + ']'; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); + $it.dataPathArr[$dataNxt] = $i; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if (typeof $additionalItems == 'object' && (it.opts.strictKeywords ? (typeof $additionalItems == 'object' && Object.keys($additionalItems).length > 0) || $additionalItems === false : it.util.schemaHasRules($additionalItems, it.RULES.all))) { + $it.schema = $additionalItems; + $it.schemaPath = it.schemaPath + '.additionalItems'; + $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } else if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' }'; + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} + +},{}],29:[function(require,module,exports){ +'use strict'; +module.exports = function generate_multipleOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + out += 'var division' + ($lvl) + ';if ('; + if ($isData) { + out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || '; + } + out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', '; + if (it.opts.multipleOfPrecision) { + out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' '; + } else { + out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') '; + } + out += ' ) '; + if ($isData) { + out += ' ) '; + } + out += ' ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be multiple of '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schemaValue) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],30:[function(require,module,exports){ +'use strict'; +module.exports = function generate_not(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.createErrors = false; + var $allErrorsOption; + if ($it.opts.allErrors) { + $allErrorsOption = $it.opts.allErrors; + $it.opts.allErrors = false; + } + out += ' ' + (it.validate($it)) + ' '; + $it.createErrors = true; + if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (' + ($nextValid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + out += ' var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if ($breakOnError) { + out += ' if (false) { '; + } + } + return out; +} + +},{}],31:[function(require,module,exports){ +'use strict'; +module.exports = function generate_oneOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $prevValid = 'prevValid' + $lvl, + $passingSchemas = 'passingSchemas' + $lvl; + out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } else { + out += ' var ' + ($nextValid) + ' = true; '; + } + if ($i) { + out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { '; + $closingBraces += '}'; + } + out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match exactly one schema in oneOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }'; + if (it.opts.allErrors) { + out += ' } '; + } + return out; +} + +},{}],32:[function(require,module,exports){ +'use strict'; +module.exports = function generate_pattern(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema); + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match pattern "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],33:[function(require,module,exports){ +'use strict'; +module.exports = function generate_properties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl; + var $schemaKeys = Object.keys($schema || {}).filter(notProto), + $pProperties = it.schema.patternProperties || {}, + $pPropertyKeys = Object.keys($pProperties).filter(notProto), + $aProperties = it.schema.additionalProperties, + $someProperties = $schemaKeys.length || $pPropertyKeys.length, + $noAdditional = $aProperties === false, + $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length, + $removeAdditional = it.opts.removeAdditional, + $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + var $required = it.schema.required; + if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) { + var $requiredHash = it.util.toHash($required); + } + + function notProto(p) { + return p !== '__proto__'; + } + out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;'; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined;'; + } + if ($checkAdditional) { + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + if ($someProperties) { + out += ' var isAdditional' + ($lvl) + ' = !(false '; + if ($schemaKeys.length) { + if ($schemaKeys.length > 8) { + out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') '; + } else { + var arr1 = $schemaKeys; + if (arr1) { + var $propertyKey, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $propertyKey = arr1[i1 += 1]; + out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' '; + } + } + } + } + if ($pPropertyKeys.length) { + var arr2 = $pPropertyKeys; + if (arr2) { + var $pProperty, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $pProperty = arr2[$i += 1]; + out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') '; + } + } + } + out += ' ); if (isAdditional' + ($lvl) + ') { '; + } + if ($removeAdditional == 'all') { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + var $currentErrorPath = it.errorPath; + var $additionalProperty = '\' + ' + $key + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + } + if ($noAdditional) { + if ($removeAdditional) { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + out += ' ' + ($nextValid) + ' = false; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalProperties'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is an invalid additional property'; + } else { + out += 'should NOT have additional properties'; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + out += ' break; '; + } + } + } else if ($additionalIsSchema) { + if ($removeAdditional == 'failing') { + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + } else { + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + } + } + it.errorPath = $currentErrorPath; + } + if ($someProperties) { + out += ' } '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + var $useDefaults = it.opts.useDefaults && !it.compositeRule; + if ($schemaKeys.length) { + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + var $prop = it.util.getProperty($propertyKey), + $passData = $data + $prop, + $hasDefault = $useDefaults && $sch.default !== undefined; + $it.schema = $sch; + $it.schemaPath = $schemaPath + $prop; + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); + $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); + $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + $code = it.util.varReplace($code, $nextData, $passData); + var $useData = $passData; + } else { + var $useData = $nextData; + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; '; + } + if ($hasDefault) { + out += ' ' + ($code) + ' '; + } else { + if ($requiredHash && $requiredHash[$propertyKey]) { + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { ' + ($nextValid) + ' = false; '; + var $currentErrorPath = it.errorPath, + $currErrSchemaPath = $errSchemaPath, + $missingProperty = it.util.escapeQuotes($propertyKey); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + $errSchemaPath = it.errSchemaPath + '/required'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + it.errorPath = $currentErrorPath; + out += ' } else { '; + } else { + if ($breakOnError) { + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { ' + ($nextValid) + ' = true; } else { '; + } else { + out += ' if (' + ($useData) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ' ) { '; + } + } + out += ' ' + ($code) + ' } '; + } + } + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if ($pPropertyKeys.length) { + var arr4 = $pPropertyKeys; + if (arr4) { + var $pProperty, i4 = -1, + l4 = arr4.length - 1; + while (i4 < l4) { + $pProperty = arr4[i4 += 1]; + var $sch = $pProperties[$pProperty]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); + $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty); + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else ' + ($nextValid) + ' = true; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} + +},{}],34:[function(require,module,exports){ +'use strict'; +module.exports = function generate_propertyNames(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + out += 'var ' + ($errs) + ' = errors;'; + if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $i = 'i' + $lvl, + $invalidName = '\' + ' + $key + ' + \'', + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined; '; + } + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + out += ' var startErrs' + ($lvl) + ' = errors; '; + var $passData = $key; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + ' 0) || $propertySch === false : it.util.schemaHasRules($propertySch, it.RULES.all)))) { + $required[$required.length] = $property; + } + } + } + } else { + var $required = $schema; + } + } + if ($isData || $required.length) { + var $currentErrorPath = it.errorPath, + $loopRequired = $isData || $required.length >= it.opts.loopRequired, + $ownProperties = it.opts.ownProperties; + if ($breakOnError) { + out += ' var missing' + ($lvl) + '; '; + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + out += ' var ' + ($valid) + ' = true; '; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; + } + out += '; if (!' + ($valid) + ') break; } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } else { + out += ' if ( '; + var arr2 = $required; + if (arr2) { + var $propertyKey, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $propertyKey = arr2[$i += 1]; + if ($i) { + out += ' || '; + } + var $prop = it.util.getProperty($propertyKey), + $useData = $data + $prop; + out += ' ( ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; + } + } + out += ') { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } + } else { + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + if ($isData) { + out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { '; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } '; + if ($isData) { + out += ' } '; + } + } else { + var arr3 = $required; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $prop = it.util.getProperty($propertyKey), + $missingProperty = it.util.escapeQuotes($propertyKey), + $useData = $data + $prop; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } + } + } + } + it.errorPath = $currentErrorPath; + } else if ($breakOnError) { + out += ' if (true) {'; + } + return out; +} + +},{}],37:[function(require,module,exports){ +'use strict'; +module.exports = function generate_uniqueItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (($schema || $isData) && it.opts.uniqueItems !== false) { + if ($isData) { + out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { '; + } + out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { '; + var $itemType = it.schema.items && it.schema.items.type, + $typeIsArray = Array.isArray($itemType); + if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) { + out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } '; + } else { + out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; '; + var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); + out += ' if (' + (it.util[$method]($itemType, 'item', it.opts.strictNumbers, true)) + ') continue; '; + if ($typeIsArray) { + out += ' if (typeof item == \'string\') item = \'"\' + item; '; + } + out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } '; + } + out += ' } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} + +},{}],38:[function(require,module,exports){ +'use strict'; +module.exports = function generate_validate(it, $keyword, $ruleType) { + var out = ''; + var $async = it.schema.$async === true, + $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'), + $id = it.self._getId(it.schema); + if (it.opts.strictKeywords) { + var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords); + if ($unknownKwd) { + var $keywordsMsg = 'unknown keyword: ' + $unknownKwd; + if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg); + else throw new Error($keywordsMsg); + } + } + if (it.isTop) { + out += ' var validate = '; + if ($async) { + it.async = true; + out += 'async '; + } + out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; '; + if ($id && (it.opts.sourceCode || it.opts.processCode)) { + out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' '; + } + } + if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) { + var $keyword = 'false schema'; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + if (it.schema === false) { + if (it.isTop) { + $breakOnError = true; + } else { + out += ' var ' + ($valid) + ' = false; '; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'boolean schema is false\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } else { + if (it.isTop) { + if ($async) { + out += ' return data; '; + } else { + out += ' validate.errors = null; return true; '; + } + } else { + out += ' var ' + ($valid) + ' = true; '; + } + } + if (it.isTop) { + out += ' }; return validate; '; + } + return out; + } + if (it.isTop) { + var $top = it.isTop, + $lvl = it.level = 0, + $dataLvl = it.dataLevel = 0, + $data = 'data'; + it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema)); + it.baseId = it.baseId || it.rootId; + delete it.isTop; + it.dataPathArr = [""]; + if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored in the schema root'; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + out += ' var vErrors = null; '; + out += ' var errors = 0; '; + out += ' if (rootData === undefined) rootData = data; '; + } else { + var $lvl = it.level, + $dataLvl = it.dataLevel, + $data = 'data' + ($dataLvl || ''); + if ($id) it.baseId = it.resolve.url(it.baseId, $id); + if ($async && !it.async) throw new Error('async schema in sync schema'); + out += ' var errs_' + ($lvl) + ' = errors;'; + } + var $valid = 'valid' + $lvl, + $breakOnError = !it.opts.allErrors, + $closingBraces1 = '', + $closingBraces2 = ''; + var $errorKeyword; + var $typeSchema = it.schema.type, + $typeIsArray = Array.isArray($typeSchema); + if ($typeSchema && it.opts.nullable && it.schema.nullable === true) { + if ($typeIsArray) { + if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null'); + } else if ($typeSchema != 'null') { + $typeSchema = [$typeSchema, 'null']; + $typeIsArray = true; + } + } + if ($typeIsArray && $typeSchema.length == 1) { + $typeSchema = $typeSchema[0]; + $typeIsArray = false; + } + if (it.schema.$ref && $refKeywords) { + if (it.opts.extendRefs == 'fail') { + throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); + } else if (it.opts.extendRefs !== true) { + $refKeywords = false; + it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); + } + } + if (it.schema.$comment && it.opts.$comment) { + out += ' ' + (it.RULES.all.$comment.code(it, '$comment')); + } + if ($typeSchema) { + if (it.opts.coerceTypes) { + var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); + } + var $rulesGroup = it.RULES.types[$typeSchema]; + if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) { + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type', + $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; + out += ' if (' + (it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true)) + ') { '; + if ($coerceToTypes) { + var $dataType = 'dataType' + $lvl, + $coerced = 'coerced' + $lvl; + out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; var ' + ($coerced) + ' = undefined; '; + if (it.opts.coerceTypes == 'array') { + out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ') && ' + ($data) + '.length == 1) { ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; if (' + (it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)) + ') ' + ($coerced) + ' = ' + ($data) + '; } '; + } + out += ' if (' + ($coerced) + ' !== undefined) ; '; + var arr1 = $coerceToTypes; + if (arr1) { + var $type, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $type = arr1[$i += 1]; + if ($type == 'string') { + out += ' else if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; '; + } else if ($type == 'number' || $type == 'integer') { + out += ' else if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' '; + if ($type == 'integer') { + out += ' && !(' + ($data) + ' % 1)'; + } + out += ')) ' + ($coerced) + ' = +' + ($data) + '; '; + } else if ($type == 'boolean') { + out += ' else if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; '; + } else if ($type == 'null') { + out += ' else if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; '; + } else if (it.opts.coerceTypes == 'array' && $type == 'array') { + out += ' else if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; '; + } + } + } + out += ' else { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } if (' + ($coerced) + ' !== undefined) { '; + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' ' + ($data) + ' = ' + ($coerced) + '; '; + if (!$dataLvl) { + out += 'if (' + ($parentData) + ' !== undefined)'; + } + out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } '; + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } + out += ' } '; + } + } + if (it.schema.$ref && !$refKeywords) { + out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' '; + if ($breakOnError) { + out += ' } if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } + } else { + var arr2 = it.RULES; + if (arr2) { + var $rulesGroup, i2 = -1, + l2 = arr2.length - 1; + while (i2 < l2) { + $rulesGroup = arr2[i2 += 1]; + if ($shouldUseGroup($rulesGroup)) { + if ($rulesGroup.type) { + out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers)) + ') { '; + } + if (it.opts.useDefaults) { + if ($rulesGroup.type == 'object' && it.schema.properties) { + var $schema = it.schema.properties, + $schemaKeys = Object.keys($schema); + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if ($sch.default !== undefined) { + var $passData = $data + it.util.getProperty($propertyKey); + if (it.compositeRule) { + if (it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored for: ' + $passData; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + } else { + out += ' if (' + ($passData) + ' === undefined '; + if (it.opts.useDefaults == 'empty') { + out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; + } + out += ' ) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } + } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) { + var arr4 = it.schema.items; + if (arr4) { + var $sch, $i = -1, + l4 = arr4.length - 1; + while ($i < l4) { + $sch = arr4[$i += 1]; + if ($sch.default !== undefined) { + var $passData = $data + '[' + $i + ']'; + if (it.compositeRule) { + if (it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored for: ' + $passData; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + } else { + out += ' if (' + ($passData) + ' === undefined '; + if (it.opts.useDefaults == 'empty') { + out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; + } + out += ' ) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } + } + } + var arr5 = $rulesGroup.rules; + if (arr5) { + var $rule, i5 = -1, + l5 = arr5.length - 1; + while (i5 < l5) { + $rule = arr5[i5 += 1]; + if ($shouldUseRule($rule)) { + var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); + if ($code) { + out += ' ' + ($code) + ' '; + if ($breakOnError) { + $closingBraces1 += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces1) + ' '; + $closingBraces1 = ''; + } + if ($rulesGroup.type) { + out += ' } '; + if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) { + out += ' else { '; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + } + } + if ($breakOnError) { + out += ' if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces2) + ' '; + } + if ($top) { + if ($async) { + out += ' if (errors === 0) return data; '; + out += ' else throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; '; + out += ' return errors === 0; '; + } + out += ' }; return validate;'; + } else { + out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';'; + } + + function $shouldUseGroup($rulesGroup) { + var rules = $rulesGroup.rules; + for (var i = 0; i < rules.length; i++) + if ($shouldUseRule(rules[i])) return true; + } + + function $shouldUseRule($rule) { + return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule)); + } + + function $ruleImplementsSomeKeyword($rule) { + var impl = $rule.implements; + for (var i = 0; i < impl.length; i++) + if (it.schema[impl[i]] !== undefined) return true; + } + return out; +} + +},{}],39:[function(require,module,exports){ +'use strict'; + +var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i; +var customRuleCode = require('./dotjs/custom'); +var definitionSchema = require('./definition_schema'); + +module.exports = { + add: addKeyword, + get: getKeyword, + remove: removeKeyword, + validate: validateKeyword +}; + + +/** + * Define custom keyword + * @this Ajv + * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords). + * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. + * @return {Ajv} this for method chaining + */ +function addKeyword(keyword, definition) { + /* jshint validthis: true */ + /* eslint no-shadow: 0 */ + var RULES = this.RULES; + if (RULES.keywords[keyword]) + throw new Error('Keyword ' + keyword + ' is already defined'); + + if (!IDENTIFIER.test(keyword)) + throw new Error('Keyword ' + keyword + ' is not a valid identifier'); + + if (definition) { + this.validateKeyword(definition, true); + + var dataType = definition.type; + if (Array.isArray(dataType)) { + for (var i=0; i 1) { + sets[0] = sets[0].slice(0, -1); + var xl = sets.length - 1; + for (var x = 1; x < xl; ++x) { + sets[x] = sets[x].slice(1, -1); + } + sets[xl] = sets[xl].slice(1); + return sets.join(''); + } else { + return sets[0]; + } +} +function subexp(str) { + return "(?:" + str + ")"; +} +function typeOf(o) { + return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase(); +} +function toUpperCase(str) { + return str.toUpperCase(); +} +function toArray(obj) { + return obj !== undefined && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : []; +} +function assign(target, source) { + var obj = target; + if (source) { + for (var key in source) { + obj[key] = source[key]; + } + } + return obj; +} + +function buildExps(isIRI) { + var ALPHA$$ = "[A-Za-z]", + CR$ = "[\\x0D]", + DIGIT$$ = "[0-9]", + DQUOTE$$ = "[\\x22]", + HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"), + //case-insensitive + LF$$ = "[\\x0A]", + SP$$ = "[\\x20]", + PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)), + //expanded + GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", + SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", + RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), + UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", + //subset, excludes bidi control characters + IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", + //subset + UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$), + SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"), + USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"), + DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$), + DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), + //relaxed parsing rules + IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), + H16$ = subexp(HEXDIG$$ + "{1,4}"), + LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), + IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), + // 6( h16 ":" ) ls32 + IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), + // "::" 5( h16 ":" ) ls32 + IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), + //[ h16 ] "::" 4( h16 ":" ) ls32 + IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), + //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), + //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), + //[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), + //[ *4( h16 ":" ) h16 ] "::" ls32 + IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), + //[ *5( h16 ":" ) h16 ] "::" h16 + IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), + //[ *6( h16 ":" ) h16 ] "::" + IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), + ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"), + //RFC 6874 + IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$), + //RFC 6874 + IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$), + //RFC 6874, with relaxed parsing rules + IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"), + IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"), + //RFC 6874 + REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"), + HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")" + "|" + REG_NAME$), + PORT$ = subexp(DIGIT$$ + "*"), + AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"), + PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")), + SEGMENT$ = subexp(PCHAR$ + "*"), + SEGMENT_NZ$ = subexp(PCHAR$ + "+"), + SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"), + PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"), + PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"), + //simplified + PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), + //simplified + PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), + //simplified + PATH_EMPTY$ = "(?!" + PCHAR$ + ")", + PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), + QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"), + FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"), + HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), + URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), + RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$), + RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), + URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$), + ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"), + GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$", + SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$"; + return { + NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"), + NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"), + NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"), + ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"), + UNRESERVED: new RegExp(UNRESERVED$$, "g"), + OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"), + PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"), + IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"), + IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules + }; +} +var URI_PROTOCOL = buildExps(false); + +var IRI_PROTOCOL = buildExps(true); + +var slicedToArray = function () { + function sliceIterator(arr, i) { + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"]) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; + } + + return function (arr, i) { + if (Array.isArray(arr)) { + return arr; + } else if (Symbol.iterator in Object(arr)) { + return sliceIterator(arr, i); + } else { + throw new TypeError("Invalid attempt to destructure non-iterable instance"); + } + }; +}(); + + + + + + + + + + + + + +var toConsumableArray = function (arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } else { + return Array.from(arr); + } +}; + +/** Highest positive signed 32-bit float value */ + +var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +var base = 36; +var tMin = 1; +var tMax = 26; +var skew = 38; +var damp = 700; +var initialBias = 72; +var initialN = 128; // 0x80 +var delimiter = '-'; // '\x2D' + +/** Regular expressions */ +var regexPunycode = /^xn--/; +var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars +var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +var errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +var baseMinusTMin = base - tMin; +var floor = Math.floor; +var stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error$1(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, fn) { + var result = []; + var length = array.length; + while (length--) { + result[length] = fn(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ +function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + var output = []; + var counter = 0; + var length = string.length; + while (counter < length) { + var value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + var extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { + // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +var ucs2encode = function ucs2encode(array) { + return String.fromCodePoint.apply(String, toConsumableArray(array)); +}; + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +var basicToDigit = function basicToDigit(codePoint) { + if (codePoint - 0x30 < 0x0A) { + return codePoint - 0x16; + } + if (codePoint - 0x41 < 0x1A) { + return codePoint - 0x41; + } + if (codePoint - 0x61 < 0x1A) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +var digitToBasic = function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +var adapt = function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +var decode = function decode(input) { + // Don't use UCS-2. + var output = []; + var inputLength = input.length; + var i = 0; + var n = initialN; + var bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + var basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (var j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error$1('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{ + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + var oldi = i; + for (var w = 1, k = base;; /* no condition */k += base) { + + if (index >= inputLength) { + error$1('invalid-input'); + } + + var digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error$1('overflow'); + } + + i += digit * w; + var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + + if (digit < t) { + break; + } + + var baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error$1('overflow'); + } + + w *= baseMinusT; + } + + var out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error$1('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + } + + return String.fromCodePoint.apply(String, output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +var encode = function encode(input) { + var output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + var inputLength = input.length; + + // Initialize the state. + var n = initialN; + var delta = 0; + var bias = initialBias; + + // Handle the basic code points. + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _currentValue2 = _step.value; + + if (_currentValue2 < 0x80) { + output.push(stringFromCharCode(_currentValue2)); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var basicLength = output.length; + var handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + var m = maxInt; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var currentValue = _step2.value; + + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + var handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error$1('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _currentValue = _step3.value; + + if (_currentValue < n && ++delta > maxInt) { + error$1('overflow'); + } + if (_currentValue == n) { + // Represent delta as a generalized variable-length integer. + var q = delta; + for (var k = base;; /* no condition */k += base) { + var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (q < t) { + break; + } + var qMinusT = q - t; + var baseMinusT = base - t; + output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + ++delta; + ++n; + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +var toUnicode = function toUnicode(input) { + return mapDomain(input, function (string) { + return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +var toASCII = function toASCII(input) { + return mapDomain(input, function (string) { + return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +var punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.1.0', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +/** + * URI.js + * + * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript. + * @author Gary Court + * @see http://github.com/garycourt/uri-js + */ +/** + * Copyright 2011 Gary Court. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of Gary Court. + */ +var SCHEMES = {}; +function pctEncChar(chr) { + var c = chr.charCodeAt(0); + var e = void 0; + if (c < 16) e = "%0" + c.toString(16).toUpperCase();else if (c < 128) e = "%" + c.toString(16).toUpperCase();else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase(); + return e; +} +function pctDecChars(str) { + var newStr = ""; + var i = 0; + var il = str.length; + while (i < il) { + var c = parseInt(str.substr(i + 1, 2), 16); + if (c < 128) { + newStr += String.fromCharCode(c); + i += 3; + } else if (c >= 194 && c < 224) { + if (il - i >= 6) { + var c2 = parseInt(str.substr(i + 4, 2), 16); + newStr += String.fromCharCode((c & 31) << 6 | c2 & 63); + } else { + newStr += str.substr(i, 6); + } + i += 6; + } else if (c >= 224) { + if (il - i >= 9) { + var _c = parseInt(str.substr(i + 4, 2), 16); + var c3 = parseInt(str.substr(i + 7, 2), 16); + newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63); + } else { + newStr += str.substr(i, 9); + } + i += 9; + } else { + newStr += str.substr(i, 3); + i += 3; + } + } + return newStr; +} +function _normalizeComponentEncoding(components, protocol) { + function decodeUnreserved(str) { + var decStr = pctDecChars(str); + return !decStr.match(protocol.UNRESERVED) ? str : decStr; + } + if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, ""); + if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + return components; +} + +function _stripLeadingZeros(str) { + return str.replace(/^0*(.*)/, "$1") || "0"; +} +function _normalizeIPv4(host, protocol) { + var matches = host.match(protocol.IPV4ADDRESS) || []; + + var _matches = slicedToArray(matches, 2), + address = _matches[1]; + + if (address) { + return address.split(".").map(_stripLeadingZeros).join("."); + } else { + return host; + } +} +function _normalizeIPv6(host, protocol) { + var matches = host.match(protocol.IPV6ADDRESS) || []; + + var _matches2 = slicedToArray(matches, 3), + address = _matches2[1], + zone = _matches2[2]; + + if (address) { + var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(), + _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), + last = _address$toLowerCase$2[0], + first = _address$toLowerCase$2[1]; + + var firstFields = first ? first.split(":").map(_stripLeadingZeros) : []; + var lastFields = last.split(":").map(_stripLeadingZeros); + var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]); + var fieldCount = isLastFieldIPv4Address ? 7 : 8; + var lastFieldsStart = lastFields.length - fieldCount; + var fields = Array(fieldCount); + for (var x = 0; x < fieldCount; ++x) { + fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || ''; + } + if (isLastFieldIPv4Address) { + fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol); + } + var allZeroFields = fields.reduce(function (acc, field, index) { + if (!field || field === "0") { + var lastLongest = acc[acc.length - 1]; + if (lastLongest && lastLongest.index + lastLongest.length === index) { + lastLongest.length++; + } else { + acc.push({ index: index, length: 1 }); + } + } + return acc; + }, []); + var longestZeroFields = allZeroFields.sort(function (a, b) { + return b.length - a.length; + })[0]; + var newHost = void 0; + if (longestZeroFields && longestZeroFields.length > 1) { + var newFirst = fields.slice(0, longestZeroFields.index); + var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length); + newHost = newFirst.join(":") + "::" + newLast.join(":"); + } else { + newHost = fields.join(":"); + } + if (zone) { + newHost += "%" + zone; + } + return newHost; + } else { + return host; + } +} +var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i; +var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined; +function parse(uriString) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var components = {}; + var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; + if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString; + var matches = uriString.match(URI_PARSE); + if (matches) { + if (NO_MATCH_IS_UNDEFINED) { + //store each component + components.scheme = matches[1]; + components.userinfo = matches[3]; + components.host = matches[4]; + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = matches[7]; + components.fragment = matches[8]; + //fix port number + if (isNaN(components.port)) { + components.port = matches[5]; + } + } else { + //IE FIX for improper RegExp matching + //store each component + components.scheme = matches[1] || undefined; + components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined; + components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined; + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined; + components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined; + //fix port number + if (isNaN(components.port)) { + components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined; + } + } + if (components.host) { + //normalize IP hosts + components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol); + } + //determine reference type + if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) { + components.reference = "same-document"; + } else if (components.scheme === undefined) { + components.reference = "relative"; + } else if (components.fragment === undefined) { + components.reference = "absolute"; + } else { + components.reference = "uri"; + } + //check for reference errors + if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) { + components.error = components.error || "URI is not a " + options.reference + " reference."; + } + //find scheme handler + var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //check if scheme can't handle IRIs + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + //if host component is a domain name + if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) { + //convert Unicode IDN -> ASCII IDN + try { + components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()); + } catch (e) { + components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e; + } + } + //convert IRI -> URI + _normalizeComponentEncoding(components, URI_PROTOCOL); + } else { + //normalize encodings + _normalizeComponentEncoding(components, protocol); + } + //perform scheme specific parsing + if (schemeHandler && schemeHandler.parse) { + schemeHandler.parse(components, options); + } + } else { + components.error = components.error || "URI can not be parsed."; + } + return components; +} + +function _recomposeAuthority(components, options) { + var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; + var uriTokens = []; + if (components.userinfo !== undefined) { + uriTokens.push(components.userinfo); + uriTokens.push("@"); + } + if (components.host !== undefined) { + //normalize IP hosts, add brackets and escape zone separator for IPv6 + uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) { + return "[" + $1 + ($2 ? "%25" + $2 : "") + "]"; + })); + } + if (typeof components.port === "number" || typeof components.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(components.port)); + } + return uriTokens.length ? uriTokens.join("") : undefined; +} + +var RDS1 = /^\.\.?\//; +var RDS2 = /^\/\.(\/|$)/; +var RDS3 = /^\/\.\.(\/|$)/; +var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/; +function removeDotSegments(input) { + var output = []; + while (input.length) { + if (input.match(RDS1)) { + input = input.replace(RDS1, ""); + } else if (input.match(RDS2)) { + input = input.replace(RDS2, "/"); + } else if (input.match(RDS3)) { + input = input.replace(RDS3, "/"); + output.pop(); + } else if (input === "." || input === "..") { + input = ""; + } else { + var im = input.match(RDS5); + if (im) { + var s = im[0]; + input = input.slice(s.length); + output.push(s); + } else { + throw new Error("Unexpected dot segment condition"); + } + } + } + return output.join(""); +} + +function serialize(components) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL; + var uriTokens = []; + //find scheme handler + var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //perform scheme specific serialization + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options); + if (components.host) { + //if host component is an IPv6 address + if (protocol.IPV6ADDRESS.test(components.host)) {} + //TODO: normalize IPv6 address as per RFC 5952 + + //if host component is a domain name + else if (options.domainHost || schemeHandler && schemeHandler.domainHost) { + //convert IDN via punycode + try { + components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host); + } catch (e) { + components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + } + } + //normalize encoding + _normalizeComponentEncoding(components, protocol); + if (options.reference !== "suffix" && components.scheme) { + uriTokens.push(components.scheme); + uriTokens.push(":"); + } + var authority = _recomposeAuthority(components, options); + if (authority !== undefined) { + if (options.reference !== "suffix") { + uriTokens.push("//"); + } + uriTokens.push(authority); + if (components.path && components.path.charAt(0) !== "/") { + uriTokens.push("/"); + } + } + if (components.path !== undefined) { + var s = components.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { + s = removeDotSegments(s); + } + if (authority === undefined) { + s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//" + } + uriTokens.push(s); + } + if (components.query !== undefined) { + uriTokens.push("?"); + uriTokens.push(components.query); + } + if (components.fragment !== undefined) { + uriTokens.push("#"); + uriTokens.push(components.fragment); + } + return uriTokens.join(""); //merge tokens into a string +} + +function resolveComponents(base, relative) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var skipNormalization = arguments[3]; + + var target = {}; + if (!skipNormalization) { + base = parse(serialize(base, options), options); //normalize base components + relative = parse(serialize(relative, options), options); //normalize relative components + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== undefined) { + target.query = relative.query; + } else { + target.query = base.query; + } + } else { + if (relative.path.charAt(0) === "/") { + target.path = removeDotSegments(relative.path); + } else { + if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) { + target.path = "/" + relative.path; + } else if (!base.path) { + target.path = relative.path; + } else { + target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + } + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + //target.authority = base.authority; + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; +} + +function resolve(baseURI, relativeURI, options) { + var schemelessOptions = assign({ scheme: 'null' }, options); + return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions); +} + +function normalize(uri, options) { + if (typeof uri === "string") { + uri = serialize(parse(uri, options), options); + } else if (typeOf(uri) === "object") { + uri = parse(serialize(uri, options), options); + } + return uri; +} + +function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = serialize(parse(uriA, options), options); + } else if (typeOf(uriA) === "object") { + uriA = serialize(uriA, options); + } + if (typeof uriB === "string") { + uriB = serialize(parse(uriB, options), options); + } else if (typeOf(uriB) === "object") { + uriB = serialize(uriB, options); + } + return uriA === uriB; +} + +function escapeComponent(str, options) { + return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar); +} + +function unescapeComponent(str, options) { + return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars); +} + +var handler = { + scheme: "http", + domainHost: true, + parse: function parse(components, options) { + //report missing host + if (!components.host) { + components.error = components.error || "HTTP URIs must have a host."; + } + return components; + }, + serialize: function serialize(components, options) { + var secure = String(components.scheme).toLowerCase() === "https"; + //normalize the default port + if (components.port === (secure ? 443 : 80) || components.port === "") { + components.port = undefined; + } + //normalize the empty path + if (!components.path) { + components.path = "/"; + } + //NOTE: We do not parse query strings for HTTP URIs + //as WWW Form Url Encoded query strings are part of the HTML4+ spec, + //and not the HTTP spec. + return components; + } +}; + +var handler$1 = { + scheme: "https", + domainHost: handler.domainHost, + parse: handler.parse, + serialize: handler.serialize +}; + +function isSecure(wsComponents) { + return typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss"; +} +//RFC 6455 +var handler$2 = { + scheme: "ws", + domainHost: true, + parse: function parse(components, options) { + var wsComponents = components; + //indicate if the secure flag is set + wsComponents.secure = isSecure(wsComponents); + //construct resouce name + wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : ''); + wsComponents.path = undefined; + wsComponents.query = undefined; + return wsComponents; + }, + serialize: function serialize(wsComponents, options) { + //normalize the default port + if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") { + wsComponents.port = undefined; + } + //ensure scheme matches secure flag + if (typeof wsComponents.secure === 'boolean') { + wsComponents.scheme = wsComponents.secure ? 'wss' : 'ws'; + wsComponents.secure = undefined; + } + //reconstruct path from resource name + if (wsComponents.resourceName) { + var _wsComponents$resourc = wsComponents.resourceName.split('?'), + _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), + path = _wsComponents$resourc2[0], + query = _wsComponents$resourc2[1]; + + wsComponents.path = path && path !== '/' ? path : undefined; + wsComponents.query = query; + wsComponents.resourceName = undefined; + } + //forbid fragment component + wsComponents.fragment = undefined; + return wsComponents; + } +}; + +var handler$3 = { + scheme: "wss", + domainHost: handler$2.domainHost, + parse: handler$2.parse, + serialize: handler$2.serialize +}; + +var O = {}; +var isIRI = true; +//RFC 3986 +var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]"; +var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive +var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded +//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; = +//const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]"; +//const WSP$$ = "[\\x20\\x09]"; +//const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127) +//const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext +//const VCHAR$$ = "[\\x21-\\x7E]"; +//const WSP$$ = "[\\x20\\x09]"; +//const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext +//const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+"); +//const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$); +//const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"'); +var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]"; +var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]"; +var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]"); +var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"; +var UNRESERVED = new RegExp(UNRESERVED$$, "g"); +var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g"); +var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g"); +var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g"); +var NOT_HFVALUE = NOT_HFNAME; +function decodeUnreserved(str) { + var decStr = pctDecChars(str); + return !decStr.match(UNRESERVED) ? str : decStr; +} +var handler$4 = { + scheme: "mailto", + parse: function parse$$1(components, options) { + var mailtoComponents = components; + var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : []; + mailtoComponents.path = undefined; + if (mailtoComponents.query) { + var unknownHeaders = false; + var headers = {}; + var hfields = mailtoComponents.query.split("&"); + for (var x = 0, xl = hfields.length; x < xl; ++x) { + var hfield = hfields[x].split("="); + switch (hfield[0]) { + case "to": + var toAddrs = hfield[1].split(","); + for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) { + to.push(toAddrs[_x]); + } + break; + case "subject": + mailtoComponents.subject = unescapeComponent(hfield[1], options); + break; + case "body": + mailtoComponents.body = unescapeComponent(hfield[1], options); + break; + default: + unknownHeaders = true; + headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options); + break; + } + } + if (unknownHeaders) mailtoComponents.headers = headers; + } + mailtoComponents.query = undefined; + for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) { + var addr = to[_x2].split("@"); + addr[0] = unescapeComponent(addr[0]); + if (!options.unicodeSupport) { + //convert Unicode IDN -> ASCII IDN + try { + addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase()); + } catch (e) { + mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e; + } + } else { + addr[1] = unescapeComponent(addr[1], options).toLowerCase(); + } + to[_x2] = addr.join("@"); + } + return mailtoComponents; + }, + serialize: function serialize$$1(mailtoComponents, options) { + var components = mailtoComponents; + var to = toArray(mailtoComponents.to); + if (to) { + for (var x = 0, xl = to.length; x < xl; ++x) { + var toAddr = String(to[x]); + var atIdx = toAddr.lastIndexOf("@"); + var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar); + var domain = toAddr.slice(atIdx + 1); + //convert IDN via punycode + try { + domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain); + } catch (e) { + components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + to[x] = localPart + "@" + domain; + } + components.path = to.join(","); + } + var headers = mailtoComponents.headers = mailtoComponents.headers || {}; + if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject; + if (mailtoComponents.body) headers["body"] = mailtoComponents.body; + var fields = []; + for (var name in headers) { + if (headers[name] !== O[name]) { + fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)); + } + } + if (fields.length) { + components.query = fields.join("&"); + } + return components; + } +}; + +var URN_PARSE = /^([^\:]+)\:(.*)/; +//RFC 2141 +var handler$5 = { + scheme: "urn", + parse: function parse$$1(components, options) { + var matches = components.path && components.path.match(URN_PARSE); + var urnComponents = components; + if (matches) { + var scheme = options.scheme || urnComponents.scheme || "urn"; + var nid = matches[1].toLowerCase(); + var nss = matches[2]; + var urnScheme = scheme + ":" + (options.nid || nid); + var schemeHandler = SCHEMES[urnScheme]; + urnComponents.nid = nid; + urnComponents.nss = nss; + urnComponents.path = undefined; + if (schemeHandler) { + urnComponents = schemeHandler.parse(urnComponents, options); + } + } else { + urnComponents.error = urnComponents.error || "URN can not be parsed."; + } + return urnComponents; + }, + serialize: function serialize$$1(urnComponents, options) { + var scheme = options.scheme || urnComponents.scheme || "urn"; + var nid = urnComponents.nid; + var urnScheme = scheme + ":" + (options.nid || nid); + var schemeHandler = SCHEMES[urnScheme]; + if (schemeHandler) { + urnComponents = schemeHandler.serialize(urnComponents, options); + } + var uriComponents = urnComponents; + var nss = urnComponents.nss; + uriComponents.path = (nid || options.nid) + ":" + nss; + return uriComponents; + } +}; + +var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/; +//RFC 4122 +var handler$6 = { + scheme: "urn:uuid", + parse: function parse(urnComponents, options) { + var uuidComponents = urnComponents; + uuidComponents.uuid = uuidComponents.nss; + uuidComponents.nss = undefined; + if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) { + uuidComponents.error = uuidComponents.error || "UUID is not valid."; + } + return uuidComponents; + }, + serialize: function serialize(uuidComponents, options) { + var urnComponents = uuidComponents; + //normalize UUID + urnComponents.nss = (uuidComponents.uuid || "").toLowerCase(); + return urnComponents; + } +}; + +SCHEMES[handler.scheme] = handler; +SCHEMES[handler$1.scheme] = handler$1; +SCHEMES[handler$2.scheme] = handler$2; +SCHEMES[handler$3.scheme] = handler$3; +SCHEMES[handler$4.scheme] = handler$4; +SCHEMES[handler$5.scheme] = handler$5; +SCHEMES[handler$6.scheme] = handler$6; + +exports.SCHEMES = SCHEMES; +exports.pctEncChar = pctEncChar; +exports.pctDecChars = pctDecChars; +exports.parse = parse; +exports.removeDotSegments = removeDotSegments; +exports.serialize = serialize; +exports.resolveComponents = resolveComponents; +exports.resolve = resolve; +exports.normalize = normalize; +exports.equal = equal; +exports.escapeComponent = escapeComponent; +exports.unescapeComponent = unescapeComponent; + +Object.defineProperty(exports, '__esModule', { value: true }); + +}))); + + +},{}],"ajv":[function(require,module,exports){ +'use strict'; + +var compileSchema = require('./compile') + , resolve = require('./compile/resolve') + , Cache = require('./cache') + , SchemaObject = require('./compile/schema_obj') + , stableStringify = require('fast-json-stable-stringify') + , formats = require('./compile/formats') + , rules = require('./compile/rules') + , $dataMetaSchema = require('./data') + , util = require('./compile/util'); + +module.exports = Ajv; + +Ajv.prototype.validate = validate; +Ajv.prototype.compile = compile; +Ajv.prototype.addSchema = addSchema; +Ajv.prototype.addMetaSchema = addMetaSchema; +Ajv.prototype.validateSchema = validateSchema; +Ajv.prototype.getSchema = getSchema; +Ajv.prototype.removeSchema = removeSchema; +Ajv.prototype.addFormat = addFormat; +Ajv.prototype.errorsText = errorsText; + +Ajv.prototype._addSchema = _addSchema; +Ajv.prototype._compile = _compile; + +Ajv.prototype.compileAsync = require('./compile/async'); +var customKeyword = require('./keyword'); +Ajv.prototype.addKeyword = customKeyword.add; +Ajv.prototype.getKeyword = customKeyword.get; +Ajv.prototype.removeKeyword = customKeyword.remove; +Ajv.prototype.validateKeyword = customKeyword.validate; + +var errorClasses = require('./compile/error_classes'); +Ajv.ValidationError = errorClasses.Validation; +Ajv.MissingRefError = errorClasses.MissingRef; +Ajv.$dataMetaSchema = $dataMetaSchema; + +var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema'; + +var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ]; +var META_SUPPORT_DATA = ['/properties']; + +/** + * Creates validator instance. + * Usage: `Ajv(opts)` + * @param {Object} opts optional options + * @return {Object} ajv instance + */ +function Ajv(opts) { + if (!(this instanceof Ajv)) return new Ajv(opts); + opts = this._opts = util.copy(opts) || {}; + setLogger(this); + this._schemas = {}; + this._refs = {}; + this._fragments = {}; + this._formats = formats(opts.format); + + this._cache = opts.cache || new Cache; + this._loadingSchemas = {}; + this._compilations = []; + this.RULES = rules(); + this._getId = chooseGetId(opts); + + opts.loopRequired = opts.loopRequired || Infinity; + if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; + if (opts.serialize === undefined) opts.serialize = stableStringify; + this._metaOpts = getMetaSchemaOptions(this); + + if (opts.formats) addInitialFormats(this); + if (opts.keywords) addInitialKeywords(this); + addDefaultMetaSchema(this); + if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta); + if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}}); + addInitialSchemas(this); +} + + + +/** + * Validate data using schema + * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize. + * @this Ajv + * @param {String|Object} schemaKeyRef key, ref or schema object + * @param {Any} data to be validated + * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). + */ +function validate(schemaKeyRef, data) { + var v; + if (typeof schemaKeyRef == 'string') { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); + } else { + var schemaObj = this._addSchema(schemaKeyRef); + v = schemaObj.validate || this._compile(schemaObj); + } + + var valid = v(data); + if (v.$async !== true) this.errors = v.errors; + return valid; +} + + +/** + * Create validating function for passed schema. + * @this Ajv + * @param {Object} schema schema object + * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. + * @return {Function} validating function + */ +function compile(schema, _meta) { + var schemaObj = this._addSchema(schema, undefined, _meta); + return schemaObj.validate || this._compile(schemaObj); +} + + +/** + * Adds schema to the instance. + * @this Ajv + * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. + * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. + * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. + * @return {Ajv} this for method chaining + */ +function addSchema(schema, key, _skipValidation, _meta) { + if (Array.isArray(schema)){ + for (var i=0; i} errors optional array of validation errors, if not passed errors from the instance are used. + * @param {Object} options optional options with properties `separator` and `dataVar`. + * @return {String} human readable string with all errors descriptions + */ +function errorsText(errors, options) { + errors = errors || this.errors; + if (!errors) return 'No errors'; + options = options || {}; + var separator = options.separator === undefined ? ', ' : options.separator; + var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; + + var text = ''; + for (var i=0; i%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,u=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,h=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,d=/^(?:\/(?:[^~/]|~0|~1)*)*$/,p=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,f=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function m(e){return a.copy(m[e="full"==e?"full":"fast"])}function v(e){var r=e.match(o);if(!r)return!1;var t,a=+r[2],s=+r[3];return 1<=a&&a<=12&&1<=s&&s<=(2!=a||((t=+r[1])%4!=0||t%100==0&&t%400!=0)?i[a]:29)}function y(e,r){var t=e.match(n);if(!t)return!1;var a=t[1],s=t[2],o=t[3];return(a<=23&&s<=59&&o<=59||23==a&&59==s&&60==o)&&(!r||t[5])}(r.exports=m).fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":c,url:u,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,hostname:s,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:w,uuid:h,"json-pointer":d,"json-pointer-uri-fragment":p,"relative-json-pointer":f},m.full={date:v,time:y,"date-time":function(e){var r=e.split(g);return 2==r.length&&v(r[0])&&y(r[1],!0)},uri:function(e){return P.test(e)&&l.test(e)},"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(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::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:w,uuid:h,"json-pointer":d,"json-pointer-uri-fragment":p,"relative-json-pointer":f};var g=/t|\s/i;var P=/\/|:/;var E=/[^\\]\\Z/;function w(e){if(E.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}}},{"./util":10}],5:[function(e,r,t){"use strict";var R=e("./resolve"),$=e("./util"),j=e("./error_classes"),D=e("fast-json-stable-stringify"),O=e("../dotjs/validate"),I=$.ucs2length,A=e("fast-deep-equal"),k=j.Validation;function C(e,c,u,r){var d=this,p=this._opts,h=[void 0],f={},l=[],t={},m=[],a={},v=[],s=function(e,r,t){var a=L.call(this,e,r,t);return 0<=a?{index:a,compiling:!0}:{index:a=this._compilations.length,compiling:!(this._compilations[a]={schema:e,root:r,baseId:t})}}.call(this,e,c=c||{schema:e,refVal:h,refs:f},r),o=this._compilations[s.index];if(s.compiling)return o.callValidate=P;var y=this._formats,g=this.RULES;try{var i=E(e,c,u,r);o.validate=i;var n=o.callValidate;return n&&(n.schema=i.schema,n.errors=null,n.refs=i.refs,n.refVal=i.refVal,n.root=i.root,n.$async=i.$async,p.sourceCode&&(n.source=i.source)),i}finally{(function(e,r,t){var a=L.call(this,e,r,t);0<=a&&this._compilations.splice(a,1)}).call(this,e,c,r)}function P(){var e=o.validate,r=e.apply(this,arguments);return P.errors=e.errors,r}function E(e,r,t,a){var s=!r||r&&r.schema==e;if(r.schema!=c.schema)return C.call(d,e,r,t,a);var o=!0===e.$async,i=O({isTop:!0,schema:e,isRoot:s,baseId:a,root:r,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:j.MissingRef,RULES:g,validate:O,util:$,resolve:R,resolveRef:w,usePattern:_,useDefault:F,useCustomRule:x,opts:p,formats:y,logger:d.logger,self:d}),i=Q(h,z)+Q(l,N)+Q(m,q)+Q(v,T)+i;p.processCode&&(i=p.processCode(i,e));try{var n=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",i)(d,g,y,c,h,m,v,A,I,k);h[0]=n}catch(e){throw d.logger.error("Error compiling schema, function code:",i),e}return n.schema=e,n.errors=null,n.refs=f,n.refVal=h,n.root=s?n:r,o&&(n.$async=!0),!0===p.sourceCode&&(n.source={code:i,patterns:l,defaults:m}),n}function w(e,r,t){r=R.url(e,r);var a,s,o=f[r];if(void 0!==o)return S(a=h[o],s="refVal["+o+"]");if(!t&&c.refs){var i=c.refs[r];if(void 0!==i)return S(a=c.refVal[i],s=b(r,a))}s=b(r);var n,l=R.call(d,E,c,r);if(void 0!==l||(n=u&&u[r])&&(l=R.inlineRef(n,p.inlineRefs)?n:C.call(d,n,c,u,e)),void 0!==l)return S(h[f[r]]=l,s);delete f[r]}function b(e,r){var t=h.length;return h[t]=r,"refVal"+(f[e]=t)}function S(e,r){return"object"==typeof e||"boolean"==typeof e?{code:r,schema:e,inline:!0}:{code:r,$async:e&&!!e.$async}}function _(e){var r=t[e];return void 0===r&&(r=t[e]=l.length,l[r]=e),"pattern"+r}function F(e){switch(typeof e){case"boolean":case"number":return""+e;case"string":return $.toQuotedString(e);case"object":if(null===e)return"null";var r=D(e),t=a[r];return void 0===t&&(t=a[r]=m.length,m[t]=e),"default"+t}}function x(e,r,t,a){if(!1!==d._opts.validateSchema){var s=e.definition.dependencies;if(s&&!s.every(function(e){return Object.prototype.hasOwnProperty.call(t,e)}))throw new Error("parent schema must have all required keywords: "+s.join(","));var o=e.definition.validateSchema;if(o)if(!o(r)){var i="keyword schema is invalid: "+d.errorsText(o.errors);if("log"!=d._opts.validateSchema)throw new Error(i);d.logger.error(i)}}var n,l=e.definition.compile,c=e.definition.inline,u=e.definition.macro;if(l)n=l.call(d,r,t,a);else if(u)n=u.call(d,r,t,a),!1!==p.validateSchema&&d.validateSchema(n,!0);else if(c)n=c.call(d,a,e.keyword,r,t);else if(!(n=e.definition.validate))return;if(void 0===n)throw new Error('custom keyword "'+e.keyword+'"failed to compile');var h=v.length;return{code:"customRule"+h,validate:v[h]=n}}}function L(e,r,t){for(var a=0;a",_=P?">":"<",F=void 0;if(!y&&"number"!=typeof d&&void 0!==d)throw new Error(r+" must be number");if(!b&&void 0!==w&&"number"!=typeof w&&"boolean"!=typeof w)throw new Error(E+" must be number or boolean");b?(o="exclIsNumber"+u,i="' + "+(n="op"+u)+" + '",c+=" var schemaExcl"+u+" = "+(t=e.util.getData(w.$data,h,e.dataPathArr))+"; ",F=E,(l=l||[]).push(c+=" var "+(a="exclusive"+u)+"; var "+(s="exclType"+u)+" = typeof "+(t="schemaExcl"+u)+"; if ("+s+" != 'boolean' && "+s+" != 'undefined' && "+s+" != 'number') { "),c="",!1!==e.createErrors?(c+=" { keyword: '"+(F||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(f)+" , params: {} ",!1!==e.opts.messages&&(c+=" , message: '"+E+" should be boolean' "),e.opts.verbose&&(c+=" , schema: validate.schema"+p+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),c+=" } "):c+=" {} ",x=c,c=l.pop(),c+=!e.compositeRule&&m?e.async?" throw new ValidationError(["+x+"]); ":" validate.errors = ["+x+"]; return false; ":" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c+=" } else if ( ",y&&(c+=" ("+g+" !== undefined && typeof "+g+" != 'number') || "),c+=" "+s+" == 'number' ? ( ("+a+" = "+g+" === undefined || "+t+" "+S+"= "+g+") ? "+v+" "+_+"= "+t+" : "+v+" "+_+" "+g+" ) : ( ("+a+" = "+t+" === true) ? "+v+" "+_+"= "+g+" : "+v+" "+_+" "+g+" ) || "+v+" !== "+v+") { var op"+u+" = "+a+" ? '"+S+"' : '"+S+"='; ",void 0===d&&(f=e.errSchemaPath+"/"+(F=E),g=t,y=b)):(i=S,(o="number"==typeof w)&&y?(n="'"+i+"'",c+=" if ( ",y&&(c+=" ("+g+" !== undefined && typeof "+g+" != 'number') || "),c+=" ( "+g+" === undefined || "+w+" "+S+"= "+g+" ? "+v+" "+_+"= "+w+" : "+v+" "+_+" "+g+" ) || "+v+" !== "+v+") { "):(o&&void 0===d?(a=!0,f=e.errSchemaPath+"/"+(F=E),g=w,_+="="):(o&&(g=Math[P?"min":"max"](w,d)),w===(!o||g)?(a=!0,f=e.errSchemaPath+"/"+(F=E),_+="="):(a=!1,i+="=")),n="'"+i+"'",c+=" if ( ",y&&(c+=" ("+g+" !== undefined && typeof "+g+" != 'number') || "),c+=" "+v+" "+_+" "+g+" || "+v+" !== "+v+") { ")),F=F||r,(l=l||[]).push(c),c="",!1!==e.createErrors?(c+=" { keyword: '"+(F||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(f)+" , params: { comparison: "+n+", limit: "+g+", exclusive: "+a+" } ",!1!==e.opts.messages&&(c+=" , message: 'should be "+i+" ",c+=y?"' + "+g:g+"'"),e.opts.verbose&&(c+=" , schema: ",c+=y?"validate.schema"+p:""+d,c+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),c+=" } "):c+=" {} ";var x=c;return c=l.pop(),c+=!e.compositeRule&&m?e.async?" throw new ValidationError(["+x+"]); ":" validate.errors = ["+x+"]; return false; ":" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c+=" } ",m&&(c+=" else { "),c}},{}],14:[function(e,r,t){"use strict";r.exports=function(e,r){var t=" ",a=e.level,s=e.dataLevel,o=e.schema[r],i=e.schemaPath+e.util.getProperty(r),n=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,c="data"+(s||""),u=e.opts.$data&&o&&o.$data,h=u?(t+=" var schema"+a+" = "+e.util.getData(o.$data,s,e.dataPathArr)+"; ","schema"+a):o;if(!u&&"number"!=typeof o)throw new Error(r+" must be number");t+="if ( ",u&&(t+=" ("+h+" !== undefined && typeof "+h+" != 'number') || ");var d=r,p=p||[];p.push(t+=" "+c+".length "+("maxItems"==r?">":"<")+" "+h+") { "),t="",!1!==e.createErrors?(t+=" { keyword: '"+(d||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(n)+" , params: { limit: "+h+" } ",!1!==e.opts.messages&&(t+=" , message: 'should NOT have ",t+="maxItems"==r?"more":"fewer",t+=" than ",t+=u?"' + "+h+" + '":""+o,t+=" items' "),e.opts.verbose&&(t+=" , schema: ",t+=u?"validate.schema"+i:""+o,t+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),t+=" } "):t+=" {} ";var f=t,t=p.pop();return t+=!e.compositeRule&&l?e.async?" throw new ValidationError(["+f+"]); ":" validate.errors = ["+f+"]; return false; ":" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+="} ",l&&(t+=" else { "),t}},{}],15:[function(e,r,t){"use strict";r.exports=function(e,r){var t=" ",a=e.level,s=e.dataLevel,o=e.schema[r],i=e.schemaPath+e.util.getProperty(r),n=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,c="data"+(s||""),u=e.opts.$data&&o&&o.$data,h=u?(t+=" var schema"+a+" = "+e.util.getData(o.$data,s,e.dataPathArr)+"; ","schema"+a):o;if(!u&&"number"!=typeof o)throw new Error(r+" must be number");t+="if ( ",u&&(t+=" ("+h+" !== undefined && typeof "+h+" != 'number') || "),t+=!1===e.opts.unicode?" "+c+".length ":" ucs2length("+c+") ";var d=r,p=p||[];p.push(t+=" "+("maxLength"==r?">":"<")+" "+h+") { "),t="",!1!==e.createErrors?(t+=" { keyword: '"+(d||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(n)+" , params: { limit: "+h+" } ",!1!==e.opts.messages&&(t+=" , message: 'should NOT be ",t+="maxLength"==r?"longer":"shorter",t+=" than ",t+=u?"' + "+h+" + '":""+o,t+=" characters' "),e.opts.verbose&&(t+=" , schema: ",t+=u?"validate.schema"+i:""+o,t+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),t+=" } "):t+=" {} ";var f=t,t=p.pop();return t+=!e.compositeRule&&l?e.async?" throw new ValidationError(["+f+"]); ":" validate.errors = ["+f+"]; return false; ":" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+="} ",l&&(t+=" else { "),t}},{}],16:[function(e,r,t){"use strict";r.exports=function(e,r){var t=" ",a=e.level,s=e.dataLevel,o=e.schema[r],i=e.schemaPath+e.util.getProperty(r),n=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,c="data"+(s||""),u=e.opts.$data&&o&&o.$data,h=u?(t+=" var schema"+a+" = "+e.util.getData(o.$data,s,e.dataPathArr)+"; ","schema"+a):o;if(!u&&"number"!=typeof o)throw new Error(r+" must be number");t+="if ( ",u&&(t+=" ("+h+" !== undefined && typeof "+h+" != 'number') || ");var d=r,p=p||[];p.push(t+=" Object.keys("+c+").length "+("maxProperties"==r?">":"<")+" "+h+") { "),t="",!1!==e.createErrors?(t+=" { keyword: '"+(d||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(n)+" , params: { limit: "+h+" } ",!1!==e.opts.messages&&(t+=" , message: 'should NOT have ",t+="maxProperties"==r?"more":"fewer",t+=" than ",t+=u?"' + "+h+" + '":""+o,t+=" properties' "),e.opts.verbose&&(t+=" , schema: ",t+=u?"validate.schema"+i:""+o,t+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),t+=" } "):t+=" {} ";var f=t,t=p.pop();return t+=!e.compositeRule&&l?e.async?" throw new ValidationError(["+f+"]); ":" validate.errors = ["+f+"]; return false; ":" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+="} ",l&&(t+=" else { "),t}},{}],17:[function(e,r,t){"use strict";r.exports=function(e,r){var t=" ",a=e.schema[r],s=e.schemaPath+e.util.getProperty(r),o=e.errSchemaPath+"/"+r,i=!e.opts.allErrors,n=e.util.copy(e),l="";n.level++;var c="valid"+n.level,u=n.baseId,h=!0,d=a;if(d)for(var p,f=-1,m=d.length-1;f "+_+") { ",x=c+"["+_+"]",d.schema=$,d.schemaPath=i+"["+_+"]",d.errSchemaPath=n+"/"+_,d.errorPath=e.util.getPathExpr(e.errorPath,_,e.opts.jsonPointers,!0),d.dataPathArr[v]=_,R=e.validate(d),d.baseId=g,e.util.varOccurences(R,y)<2?t+=" "+e.util.varReplace(R,y,x)+" ":t+=" var "+y+" = "+x+"; "+R+" ",t+=" } ",l&&(t+=" if ("+f+") { ",p+="}"))}"object"==typeof b&&(e.opts.strictKeywords?"object"==typeof b&&0 "+o.length+") { for (var "+m+" = "+o.length+"; "+m+" < "+c+".length; "+m+"++) { ",d.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers,!0),x=c+"["+m+"]",d.dataPathArr[v]=m,R=e.validate(d),d.baseId=g,e.util.varOccurences(R,y)<2?t+=" "+e.util.varReplace(R,y,x)+" ":t+=" var "+y+" = "+x+"; "+R+" ",l&&(t+=" if (!"+f+") break; "),t+=" } } ",l&&(t+=" if ("+f+") { ",p+="}"))}else{(e.opts.strictKeywords?"object"==typeof o&&0 1e-"+e.opts.multipleOfPrecision+" ":" division"+a+" !== parseInt(division"+a+") ",t+=" ) ",u&&(t+=" ) ");var d=d||[];d.push(t+=" ) { "),t="",!1!==e.createErrors?(t+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(n)+" , params: { multipleOf: "+h+" } ",!1!==e.opts.messages&&(t+=" , message: 'should be multiple of ",t+=u?"' + "+h:h+"'"),e.opts.verbose&&(t+=" , schema: ",t+=u?"validate.schema"+i:""+o,t+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),t+=" } "):t+=" {} ";var p=t,t=d.pop();return t+=!e.compositeRule&&l?e.async?" throw new ValidationError(["+p+"]); ":" validate.errors = ["+p+"]; return false; ":" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+="} ",l&&(t+=" else { "),t}},{}],30:[function(e,r,t){"use strict";r.exports=function(e,r){var t=" ",a=e.level,s=e.dataLevel,o=e.schema[r],i=e.schemaPath+e.util.getProperty(r),n=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,c="data"+(s||""),u="errs__"+a,h=e.util.copy(e);h.level++;var d,p,f,m,v="valid"+h.level;return(e.opts.strictKeywords?"object"==typeof o&&0 1) { ",t=e.schema.items&&e.schema.items.type,a=Array.isArray(t),!t||"object"==t||"array"==t||a&&(0<=t.indexOf("object")||0<=t.indexOf("array"))?i+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+p+"[i], "+p+"[j])) { "+f+" = false; break outer; } } } ":(i+=" var itemIndices = {}, item; for (;i--;) { var item = "+p+"[i]; ",i+=" if ("+e.util["checkDataType"+(a?"s":"")](t,"item",e.opts.strictNumbers,!0)+") continue; ",a&&(i+=" if (typeof item == 'string') item = '\"' + item; "),i+=" if (typeof itemIndices[item] == 'number') { "+f+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "),i+=" } ",m&&(i+=" } "),(s=s||[]).push(i+=" if (!"+f+") { "),i="",!1!==e.createErrors?(i+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { i: i, j: j } ",!1!==e.opts.messages&&(i+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(i+=" , schema: ",i+=m?"validate.schema"+u:""+c,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+p+" "),i+=" } "):i+=" {} ",o=i,i=s.pop(),i+=!e.compositeRule&&d?e.async?" throw new ValidationError(["+o+"]); ":" validate.errors = ["+o+"]; return false; ":" var err = "+o+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } ",d&&(i+=" else { ")):d&&(i+=" if (true) { "),i}},{}],38:[function(e,r,t){"use strict";r.exports=function(a,e){var r="",t=!0===a.schema.$async,s=a.util.schemaHasRulesExcept(a.schema,a.RULES.all,"$ref"),o=a.self._getId(a.schema);if(a.opts.strictKeywords){var i=a.util.schemaUnknownRules(a.schema,a.RULES.keywords);if(i){var n="unknown keyword: "+i;if("log"!==a.opts.strictKeywords)throw new Error(n);a.logger.warn(n)}}if(a.isTop&&(r+=" var validate = ",t&&(a.async=!0,r+="async "),r+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",o&&(a.opts.sourceCode||a.opts.processCode)&&(r+=" /*# sourceURL="+o+" */ ")),"boolean"==typeof a.schema||!s&&!a.schema.$ref){var l=a.level,c=a.dataLevel,u=a.schema[e="false schema"],h=a.schemaPath+a.util.getProperty(e),d=a.errSchemaPath+"/"+e,p=!a.opts.allErrors,f="data"+(c||""),m="valid"+l;return!1===a.schema?(a.isTop?p=!0:r+=" var "+m+" = false; ",(U=U||[]).push(r),r="",!1!==a.createErrors?(r+=" { keyword: 'false schema' , dataPath: (dataPath || '') + "+a.errorPath+" , schemaPath: "+a.util.toQuotedString(d)+" , params: {} ",!1!==a.opts.messages&&(r+=" , message: 'boolean schema is false' "),a.opts.verbose&&(r+=" , schema: false , parentSchema: validate.schema"+a.schemaPath+" , data: "+f+" "),r+=" } "):r+=" {} ",D=r,r=U.pop(),r+=!a.compositeRule&&p?a.async?" throw new ValidationError(["+D+"]); ":" validate.errors = ["+D+"]; return false; ":" var err = "+D+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "):r+=a.isTop?t?" return data; ":" validate.errors = null; return true; ":" var "+m+" = true; ",a.isTop&&(r+=" }; return validate; "),r}if(a.isTop){var v=a.isTop,l=a.level=0,c=a.dataLevel=0,f="data";if(a.rootId=a.resolve.fullPath(a.self._getId(a.root.schema)),a.baseId=a.baseId||a.rootId,delete a.isTop,a.dataPathArr=[""],void 0!==a.schema.default&&a.opts.useDefaults&&a.opts.strictDefaults){var y="default is ignored in the schema root";if("log"!==a.opts.strictDefaults)throw new Error(y);a.logger.warn(y)}r+=" var vErrors = null; ",r+=" var errors = 0; ",r+=" if (rootData === undefined) rootData = data; "}else{l=a.level,f="data"+((c=a.dataLevel)||"");if(o&&(a.baseId=a.resolve.url(a.baseId,o)),t&&!a.async)throw new Error("async schema in sync schema");r+=" var errs_"+l+" = errors;"}var g,m="valid"+l,p=!a.opts.allErrors,P="",E="",w=a.schema.type,b=Array.isArray(w);if(w&&a.opts.nullable&&!0===a.schema.nullable&&(b?-1==w.indexOf("null")&&(w=w.concat("null")):"null"!=w&&(w=[w,"null"],b=!0)),b&&1==w.length&&(w=w[0],b=!1),a.schema.$ref&&s){if("fail"==a.opts.extendRefs)throw new Error('$ref: validation keywords used in schema at path "'+a.errSchemaPath+'" (see option extendRefs)');!0!==a.opts.extendRefs&&(s=!1,a.logger.warn('$ref: keywords ignored in schema at path "'+a.errSchemaPath+'"'))}if(a.schema.$comment&&a.opts.$comment&&(r+=" "+a.RULES.all.$comment.code(a,"$comment")),w){a.opts.coerceTypes&&(g=a.util.coerceToTypes(a.opts.coerceTypes,w));var S=a.RULES.types[w];if(g||b||!0===S||S&&!Z(S)){h=a.schemaPath+".type",d=a.errSchemaPath+"/type",h=a.schemaPath+".type",d=a.errSchemaPath+"/type";if(r+=" if ("+a.util[b?"checkDataTypes":"checkDataType"](w,f,a.opts.strictNumbers,!0)+") { ",g){var _="dataType"+l,F="coerced"+l;r+=" var "+_+" = typeof "+f+"; var "+F+" = undefined; ","array"==a.opts.coerceTypes&&(r+=" if ("+_+" == 'object' && Array.isArray("+f+") && "+f+".length == 1) { "+f+" = "+f+"[0]; "+_+" = typeof "+f+"; if ("+a.util.checkDataType(a.schema.type,f,a.opts.strictNumbers)+") "+F+" = "+f+"; } "),r+=" if ("+F+" !== undefined) ; ";var x=g;if(x)for(var R,$=-1,j=x.length-1;$= 0x80 (not a basic code point)","invalid-input":"Invalid input"},k=Math.floor,C=String.fromCharCode;function L(e){throw new RangeError(i[e])}function n(e,r){var t=e.split("@"),a="";return 1>1,e+=k(e/r);455k((A-a)/h))&&L("overflow"),a+=p*h;var f=d<=o?1:o+26<=d?26:d-o;if(pk(A/m)&&L("overflow"),h*=m}var v=r.length+1,o=z(a-u,v,0==u);k(a/v)>A-s&&L("overflow"),s+=k(a/v),a%=v,r.splice(a++,0,s)}return String.fromCodePoint.apply(String,r)}function c(e){var r=[],t=(e=N(e)).length,a=128,s=0,o=72,i=!0,n=!1,l=void 0;try{for(var c,u=e[Symbol.iterator]();!(i=(c=u.next()).done);i=!0){var h=c.value;h<128&&r.push(C(h))}}catch(e){n=!0,l=e}finally{try{!i&&u.return&&u.return()}finally{if(n)throw l}}var d=r.length,p=d;for(d&&r.push("-");pk((A-s)/w)&&L("overflow"),s+=(f-a)*w,a=f;var b=!0,S=!1,_=void 0;try{for(var F,x=e[Symbol.iterator]();!(b=(F=x.next()).done);b=!0){var R=F.value;if(RA&&L("overflow"),R==a){for(var $=s,j=36;;j+=36){var D=j<=o?1:o+26<=j?26:j-o;if($>6|192).toString(16).toUpperCase()+"%"+(63&r|128).toString(16).toUpperCase():"%"+(r>>12|224).toString(16).toUpperCase()+"%"+(r>>6&63|128).toString(16).toUpperCase()+"%"+(63&r|128).toString(16).toUpperCase()}function p(e){for(var r="",t=0,a=e.length;tA-Z\\x5E-\\x7E]",'[\\"\\\\]')),Y=new RegExp(K,"g"),W=new RegExp("(?:(?:%[EFef][0-9A-Fa-f]%[0-9A-Fa-f][0-9A-Fa-f]%[0-9A-Fa-f][0-9A-Fa-f])|(?:%[89A-Fa-f][0-9A-Fa-f]%[0-9A-Fa-f][0-9A-Fa-f])|(?:%[0-9A-Fa-f][0-9A-Fa-f]))","g"),X=new RegExp(J("[^]","[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]","[\\.]",'[\\"]',G),"g"),ee=new RegExp(J("[^]",K,"[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"),"g"),re=ee;function te(e){var r=p(e);return r.match(Y)?r:e}var ae={scheme:"mailto",parse:function(e,r){var t=e,a=t.to=t.path?t.path.split(","):[];if(t.path=void 0,t.query){for(var s=!1,o={},i=t.query.split("&"),n=0,l=i.length;n); + + message: string; + errors: Array; + ajv: true; + validation: true; + } + + class MissingRefError extends Error { + constructor(baseId: string, ref: string, message?: string); + static message: (baseId: string, ref: string) => string; + + message: string; + missingRef: string; + missingSchema: string; + } +} + +declare namespace ajv { + type ValidationError = AjvErrors.ValidationError; + + type MissingRefError = AjvErrors.MissingRefError; + + interface Ajv { + /** + * Validate data using schema + * Schema will be compiled and cached (using serialized JSON as key, [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize by default). + * @param {string|object|Boolean} schemaKeyRef key, ref or schema object + * @param {Any} data to be validated + * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). + */ + validate(schemaKeyRef: object | string | boolean, data: any): boolean | PromiseLike; + /** + * Create validating function for passed schema. + * @param {object|Boolean} schema schema object + * @return {Function} validating function + */ + compile(schema: object | boolean): ValidateFunction; + /** + * Creates validating function for passed schema with asynchronous loading of missing schemas. + * `loadSchema` option should be a function that accepts schema uri and node-style callback. + * @this Ajv + * @param {object|Boolean} schema schema object + * @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped + * @param {Function} callback optional node-style callback, it is always called with 2 parameters: error (or null) and validating function. + * @return {PromiseLike} validating function + */ + compileAsync(schema: object | boolean, meta?: Boolean, callback?: (err: Error, validate: ValidateFunction) => any): PromiseLike; + /** + * Adds schema to the instance. + * @param {object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. + * @param {string} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + * @return {Ajv} this for method chaining + */ + addSchema(schema: Array | object, key?: string): Ajv; + /** + * Add schema that will be used to validate other schemas + * options in META_IGNORE_OPTIONS are alway set to false + * @param {object} schema schema object + * @param {string} key optional schema key + * @return {Ajv} this for method chaining + */ + addMetaSchema(schema: object, key?: string): Ajv; + /** + * Validate schema + * @param {object|Boolean} schema schema to validate + * @return {Boolean} true if schema is valid + */ + validateSchema(schema: object | boolean): boolean; + /** + * Get compiled schema from the instance by `key` or `ref`. + * @param {string} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id). + * @return {Function} schema validating function (with property `schema`). Returns undefined if keyRef can't be resolved to an existing schema. + */ + getSchema(keyRef: string): ValidateFunction | undefined; + /** + * Remove cached schema(s). + * If no parameter is passed all schemas but meta-schemas are removed. + * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + * Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + * @param {string|object|RegExp|Boolean} schemaKeyRef key, ref, pattern to match key/ref or schema object + * @return {Ajv} this for method chaining + */ + removeSchema(schemaKeyRef?: object | string | RegExp | boolean): Ajv; + /** + * Add custom format + * @param {string} name format name + * @param {string|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid) + * @return {Ajv} this for method chaining + */ + addFormat(name: string, format: FormatValidator | FormatDefinition): Ajv; + /** + * Define custom keyword + * @this Ajv + * @param {string} keyword custom keyword, should be a valid identifier, should be different from all standard, custom and macro keywords. + * @param {object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. + * @return {Ajv} this for method chaining + */ + addKeyword(keyword: string, definition: KeywordDefinition): Ajv; + /** + * Get keyword definition + * @this Ajv + * @param {string} keyword pre-defined or custom keyword. + * @return {object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise. + */ + getKeyword(keyword: string): object | boolean; + /** + * Remove keyword + * @this Ajv + * @param {string} keyword pre-defined or custom keyword. + * @return {Ajv} this for method chaining + */ + removeKeyword(keyword: string): Ajv; + /** + * Validate keyword + * @this Ajv + * @param {object} definition keyword definition object + * @param {boolean} throwError true to throw exception if definition is invalid + * @return {boolean} validation result + */ + validateKeyword(definition: KeywordDefinition, throwError: boolean): boolean; + /** + * Convert array of error message objects to string + * @param {Array} errors optional array of validation errors, if not passed errors from the instance are used. + * @param {object} options optional options with properties `separator` and `dataVar`. + * @return {string} human readable string with all errors descriptions + */ + errorsText(errors?: Array | null, options?: ErrorsTextOptions): string; + errors?: Array | null; + _opts: Options; + } + + interface CustomLogger { + log(...args: any[]): any; + warn(...args: any[]): any; + error(...args: any[]): any; + } + + interface ValidateFunction { + ( + data: any, + dataPath?: string, + parentData?: object | Array, + parentDataProperty?: string | number, + rootData?: object | Array + ): boolean | PromiseLike; + schema?: object | boolean; + errors?: null | Array; + refs?: object; + refVal?: Array; + root?: ValidateFunction | object; + $async?: true; + source?: object; + } + + interface Options { + $data?: boolean; + allErrors?: boolean; + verbose?: boolean; + jsonPointers?: boolean; + uniqueItems?: boolean; + unicode?: boolean; + format?: false | string; + formats?: object; + keywords?: object; + unknownFormats?: true | string[] | 'ignore'; + schemas?: Array | object; + schemaId?: '$id' | 'id' | 'auto'; + missingRefs?: true | 'ignore' | 'fail'; + extendRefs?: true | 'ignore' | 'fail'; + loadSchema?: (uri: string, cb?: (err: Error, schema: object) => void) => PromiseLike; + removeAdditional?: boolean | 'all' | 'failing'; + useDefaults?: boolean | 'empty' | 'shared'; + coerceTypes?: boolean | 'array'; + strictDefaults?: boolean | 'log'; + strictKeywords?: boolean | 'log'; + strictNumbers?: boolean; + async?: boolean | string; + transpile?: string | ((code: string) => string); + meta?: boolean | object; + validateSchema?: boolean | 'log'; + addUsedSchema?: boolean; + inlineRefs?: boolean | number; + passContext?: boolean; + loopRequired?: number; + ownProperties?: boolean; + multipleOfPrecision?: boolean | number; + errorDataPath?: string, + messages?: boolean; + sourceCode?: boolean; + processCode?: (code: string, schema: object) => string; + cache?: object; + logger?: CustomLogger | false; + nullable?: boolean; + serialize?: ((schema: object | boolean) => any) | false; + } + + type FormatValidator = string | RegExp | ((data: string) => boolean | PromiseLike); + type NumberFormatValidator = ((data: number) => boolean | PromiseLike); + + interface NumberFormatDefinition { + type: "number", + validate: NumberFormatValidator; + compare?: (data1: number, data2: number) => number; + async?: boolean; + } + + interface StringFormatDefinition { + type?: "string", + validate: FormatValidator; + compare?: (data1: string, data2: string) => number; + async?: boolean; + } + + type FormatDefinition = NumberFormatDefinition | StringFormatDefinition; + + interface KeywordDefinition { + type?: string | Array; + async?: boolean; + $data?: boolean; + errors?: boolean | string; + metaSchema?: object; + // schema: false makes validate not to expect schema (ValidateFunction) + schema?: boolean; + statements?: boolean; + dependencies?: Array; + modifying?: boolean; + valid?: boolean; + // one and only one of the following properties should be present + validate?: SchemaValidateFunction | ValidateFunction; + compile?: (schema: any, parentSchema: object, it: CompilationContext) => ValidateFunction; + macro?: (schema: any, parentSchema: object, it: CompilationContext) => object | boolean; + inline?: (it: CompilationContext, keyword: string, schema: any, parentSchema: object) => string; + } + + interface CompilationContext { + level: number; + dataLevel: number; + dataPathArr: string[]; + schema: any; + schemaPath: string; + baseId: string; + async: boolean; + opts: Options; + formats: { + [index: string]: FormatDefinition | undefined; + }; + keywords: { + [index: string]: KeywordDefinition | undefined; + }; + compositeRule: boolean; + validate: (schema: object) => boolean; + util: { + copy(obj: any, target?: any): any; + toHash(source: string[]): { [index: string]: true | undefined }; + equal(obj: any, target: any): boolean; + getProperty(str: string): string; + schemaHasRules(schema: object, rules: any): string; + escapeQuotes(str: string): string; + toQuotedString(str: string): string; + getData(jsonPointer: string, dataLevel: number, paths: string[]): string; + escapeJsonPointer(str: string): string; + unescapeJsonPointer(str: string): string; + escapeFragment(str: string): string; + unescapeFragment(str: string): string; + }; + self: Ajv; + } + + interface SchemaValidateFunction { + ( + schema: any, + data: any, + parentSchema?: object, + dataPath?: string, + parentData?: object | Array, + parentDataProperty?: string | number, + rootData?: object | Array + ): boolean | PromiseLike; + errors?: Array; + } + + interface ErrorsTextOptions { + separator?: string; + dataVar?: string; + } + + interface ErrorObject { + keyword: string; + dataPath: string; + schemaPath: string; + params: ErrorParameters; + // Added to validation errors of propertyNames keyword schema + propertyName?: string; + // Excluded if messages set to false. + message?: string; + // These are added with the `verbose` option. + schema?: any; + parentSchema?: object; + data?: any; + } + + type ErrorParameters = RefParams | LimitParams | AdditionalPropertiesParams | + DependenciesParams | FormatParams | ComparisonParams | + MultipleOfParams | PatternParams | RequiredParams | + TypeParams | UniqueItemsParams | CustomParams | + PatternRequiredParams | PropertyNamesParams | + IfParams | SwitchParams | NoParams | EnumParams; + + interface RefParams { + ref: string; + } + + interface LimitParams { + limit: number; + } + + interface AdditionalPropertiesParams { + additionalProperty: string; + } + + interface DependenciesParams { + property: string; + missingProperty: string; + depsCount: number; + deps: string; + } + + interface FormatParams { + format: string + } + + interface ComparisonParams { + comparison: string; + limit: number | string; + exclusive: boolean; + } + + interface MultipleOfParams { + multipleOf: number; + } + + interface PatternParams { + pattern: string; + } + + interface RequiredParams { + missingProperty: string; + } + + interface TypeParams { + type: string; + } + + interface UniqueItemsParams { + i: number; + j: number; + } + + interface CustomParams { + keyword: string; + } + + interface PatternRequiredParams { + missingPattern: string; + } + + interface PropertyNamesParams { + propertyName: string; + } + + interface IfParams { + failingKeyword: string; + } + + interface SwitchParams { + caseIndex: number; + } + + interface NoParams { } + + interface EnumParams { + allowedValues: Array; + } +} + +export = ajv; diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/ajv.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/ajv.js new file mode 100644 index 0000000..06a45b6 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/ajv.js @@ -0,0 +1,506 @@ +'use strict'; + +var compileSchema = require('./compile') + , resolve = require('./compile/resolve') + , Cache = require('./cache') + , SchemaObject = require('./compile/schema_obj') + , stableStringify = require('fast-json-stable-stringify') + , formats = require('./compile/formats') + , rules = require('./compile/rules') + , $dataMetaSchema = require('./data') + , util = require('./compile/util'); + +module.exports = Ajv; + +Ajv.prototype.validate = validate; +Ajv.prototype.compile = compile; +Ajv.prototype.addSchema = addSchema; +Ajv.prototype.addMetaSchema = addMetaSchema; +Ajv.prototype.validateSchema = validateSchema; +Ajv.prototype.getSchema = getSchema; +Ajv.prototype.removeSchema = removeSchema; +Ajv.prototype.addFormat = addFormat; +Ajv.prototype.errorsText = errorsText; + +Ajv.prototype._addSchema = _addSchema; +Ajv.prototype._compile = _compile; + +Ajv.prototype.compileAsync = require('./compile/async'); +var customKeyword = require('./keyword'); +Ajv.prototype.addKeyword = customKeyword.add; +Ajv.prototype.getKeyword = customKeyword.get; +Ajv.prototype.removeKeyword = customKeyword.remove; +Ajv.prototype.validateKeyword = customKeyword.validate; + +var errorClasses = require('./compile/error_classes'); +Ajv.ValidationError = errorClasses.Validation; +Ajv.MissingRefError = errorClasses.MissingRef; +Ajv.$dataMetaSchema = $dataMetaSchema; + +var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema'; + +var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ]; +var META_SUPPORT_DATA = ['/properties']; + +/** + * Creates validator instance. + * Usage: `Ajv(opts)` + * @param {Object} opts optional options + * @return {Object} ajv instance + */ +function Ajv(opts) { + if (!(this instanceof Ajv)) return new Ajv(opts); + opts = this._opts = util.copy(opts) || {}; + setLogger(this); + this._schemas = {}; + this._refs = {}; + this._fragments = {}; + this._formats = formats(opts.format); + + this._cache = opts.cache || new Cache; + this._loadingSchemas = {}; + this._compilations = []; + this.RULES = rules(); + this._getId = chooseGetId(opts); + + opts.loopRequired = opts.loopRequired || Infinity; + if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; + if (opts.serialize === undefined) opts.serialize = stableStringify; + this._metaOpts = getMetaSchemaOptions(this); + + if (opts.formats) addInitialFormats(this); + if (opts.keywords) addInitialKeywords(this); + addDefaultMetaSchema(this); + if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta); + if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}}); + addInitialSchemas(this); +} + + + +/** + * Validate data using schema + * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize. + * @this Ajv + * @param {String|Object} schemaKeyRef key, ref or schema object + * @param {Any} data to be validated + * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). + */ +function validate(schemaKeyRef, data) { + var v; + if (typeof schemaKeyRef == 'string') { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); + } else { + var schemaObj = this._addSchema(schemaKeyRef); + v = schemaObj.validate || this._compile(schemaObj); + } + + var valid = v(data); + if (v.$async !== true) this.errors = v.errors; + return valid; +} + + +/** + * Create validating function for passed schema. + * @this Ajv + * @param {Object} schema schema object + * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. + * @return {Function} validating function + */ +function compile(schema, _meta) { + var schemaObj = this._addSchema(schema, undefined, _meta); + return schemaObj.validate || this._compile(schemaObj); +} + + +/** + * Adds schema to the instance. + * @this Ajv + * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. + * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. + * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. + * @return {Ajv} this for method chaining + */ +function addSchema(schema, key, _skipValidation, _meta) { + if (Array.isArray(schema)){ + for (var i=0; i} errors optional array of validation errors, if not passed errors from the instance are used. + * @param {Object} options optional options with properties `separator` and `dataVar`. + * @return {String} human readable string with all errors descriptions + */ +function errorsText(errors, options) { + errors = errors || this.errors; + if (!errors) return 'No errors'; + options = options || {}; + var separator = options.separator === undefined ? ', ' : options.separator; + var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; + + var text = ''; + for (var i=0; i%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; +// For the source: https://gist.github.com/dperini/729294 +// For test cases: https://mathiasbynens.be/demo/url-regex +// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983. +// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; +var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i; +var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; +var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; +var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; +var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; + + +module.exports = formats; + +function formats(mode) { + mode = mode == 'full' ? 'full' : 'fast'; + return util.copy(formats[mode]); +} + + +formats.fast = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, + 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + 'uri-reference': /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + 'uri-template': URITEMPLATE, + url: URL, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation') + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, + hostname: HOSTNAME, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, + regex: regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: UUID, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + 'json-pointer': JSON_POINTER, + 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; + + +formats.full = { + date: date, + time: time, + 'date-time': date_time, + uri: uri, + 'uri-reference': URIREF, + 'uri-template': URITEMPLATE, + url: URL, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: HOSTNAME, + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(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, + regex: regex, + uuid: UUID, + 'json-pointer': JSON_POINTER, + 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; + + +function isLeapYear(year) { + // https://tools.ietf.org/html/rfc3339#appendix-C + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} + + +function date(str) { + // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 + var matches = str.match(DATE); + if (!matches) return false; + + var year = +matches[1]; + var month = +matches[2]; + var day = +matches[3]; + + return month >= 1 && month <= 12 && day >= 1 && + day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); +} + + +function time(str, full) { + var matches = str.match(TIME); + if (!matches) return false; + + var hour = matches[1]; + var minute = matches[2]; + var second = matches[3]; + var timeZone = matches[5]; + return ((hour <= 23 && minute <= 59 && second <= 59) || + (hour == 23 && minute == 59 && second == 60)) && + (!full || timeZone); +} + + +var DATE_TIME_SEPARATOR = /t|\s/i; +function date_time(str) { + // http://tools.ietf.org/html/rfc3339#section-5.6 + var dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); +} + + +var NOT_URI_FRAGMENT = /\/|:/; +function uri(str) { + // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." + return NOT_URI_FRAGMENT.test(str) && URI.test(str); +} + + +var Z_ANCHOR = /[^\\]\\Z/; +function regex(str) { + if (Z_ANCHOR.test(str)) return false; + try { + new RegExp(str); + return true; + } catch(e) { + return false; + } +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/compile/index.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/compile/index.js new file mode 100644 index 0000000..97518c4 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/compile/index.js @@ -0,0 +1,387 @@ +'use strict'; + +var resolve = require('./resolve') + , util = require('./util') + , errorClasses = require('./error_classes') + , stableStringify = require('fast-json-stable-stringify'); + +var validateGenerator = require('../dotjs/validate'); + +/** + * Functions below are used inside compiled validations function + */ + +var ucs2length = util.ucs2length; +var equal = require('fast-deep-equal'); + +// this error is thrown by async schemas to return validation errors via exception +var ValidationError = errorClasses.Validation; + +module.exports = compile; + + +/** + * Compiles schema to validation function + * @this Ajv + * @param {Object} schema schema object + * @param {Object} root object with information about the root schema for this schema + * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution + * @param {String} baseId base ID for IDs in the schema + * @return {Function} validation function + */ +function compile(schema, root, localRefs, baseId) { + /* jshint validthis: true, evil: true */ + /* eslint no-shadow: 0 */ + var self = this + , opts = this._opts + , refVal = [ undefined ] + , refs = {} + , patterns = [] + , patternsHash = {} + , defaults = [] + , defaultsHash = {} + , customRules = []; + + root = root || { schema: schema, refVal: refVal, refs: refs }; + + var c = checkCompiling.call(this, schema, root, baseId); + var compilation = this._compilations[c.index]; + if (c.compiling) return (compilation.callValidate = callValidate); + + var formats = this._formats; + var RULES = this.RULES; + + try { + var v = localCompile(schema, root, localRefs, baseId); + compilation.validate = v; + var cv = compilation.callValidate; + if (cv) { + cv.schema = v.schema; + cv.errors = null; + cv.refs = v.refs; + cv.refVal = v.refVal; + cv.root = v.root; + cv.$async = v.$async; + if (opts.sourceCode) cv.source = v.source; + } + return v; + } finally { + endCompiling.call(this, schema, root, baseId); + } + + /* @this {*} - custom context, see passContext option */ + function callValidate() { + /* jshint validthis: true */ + var validate = compilation.validate; + var result = validate.apply(this, arguments); + callValidate.errors = validate.errors; + return result; + } + + function localCompile(_schema, _root, localRefs, baseId) { + var isRoot = !_root || (_root && _root.schema == _schema); + if (_root.schema != root.schema) + return compile.call(self, _schema, _root, localRefs, baseId); + + var $async = _schema.$async === true; + + var sourceCode = validateGenerator({ + isTop: true, + schema: _schema, + isRoot: isRoot, + baseId: baseId, + root: _root, + schemaPath: '', + errSchemaPath: '#', + errorPath: '""', + MissingRefError: errorClasses.MissingRef, + RULES: RULES, + validate: validateGenerator, + util: util, + resolve: resolve, + resolveRef: resolveRef, + usePattern: usePattern, + useDefault: useDefault, + useCustomRule: useCustomRule, + opts: opts, + formats: formats, + logger: self.logger, + self: self + }); + + sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + + sourceCode; + + if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema); + // console.log('\n\n\n *** \n', JSON.stringify(sourceCode)); + var validate; + try { + var makeValidate = new Function( + 'self', + 'RULES', + 'formats', + 'root', + 'refVal', + 'defaults', + 'customRules', + 'equal', + 'ucs2length', + 'ValidationError', + sourceCode + ); + + validate = makeValidate( + self, + RULES, + formats, + root, + refVal, + defaults, + customRules, + equal, + ucs2length, + ValidationError + ); + + refVal[0] = validate; + } catch(e) { + self.logger.error('Error compiling schema, function code:', sourceCode); + throw e; + } + + validate.schema = _schema; + validate.errors = null; + validate.refs = refs; + validate.refVal = refVal; + validate.root = isRoot ? validate : _root; + if ($async) validate.$async = true; + if (opts.sourceCode === true) { + validate.source = { + code: sourceCode, + patterns: patterns, + defaults: defaults + }; + } + + return validate; + } + + function resolveRef(baseId, ref, isRoot) { + ref = resolve.url(baseId, ref); + var refIndex = refs[ref]; + var _refVal, refCode; + if (refIndex !== undefined) { + _refVal = refVal[refIndex]; + refCode = 'refVal[' + refIndex + ']'; + return resolvedRef(_refVal, refCode); + } + if (!isRoot && root.refs) { + var rootRefId = root.refs[ref]; + if (rootRefId !== undefined) { + _refVal = root.refVal[rootRefId]; + refCode = addLocalRef(ref, _refVal); + return resolvedRef(_refVal, refCode); + } + } + + refCode = addLocalRef(ref); + var v = resolve.call(self, localCompile, root, ref); + if (v === undefined) { + var localSchema = localRefs && localRefs[ref]; + if (localSchema) { + v = resolve.inlineRef(localSchema, opts.inlineRefs) + ? localSchema + : compile.call(self, localSchema, root, localRefs, baseId); + } + } + + if (v === undefined) { + removeLocalRef(ref); + } else { + replaceLocalRef(ref, v); + return resolvedRef(v, refCode); + } + } + + function addLocalRef(ref, v) { + var refId = refVal.length; + refVal[refId] = v; + refs[ref] = refId; + return 'refVal' + refId; + } + + function removeLocalRef(ref) { + delete refs[ref]; + } + + function replaceLocalRef(ref, v) { + var refId = refs[ref]; + refVal[refId] = v; + } + + function resolvedRef(refVal, code) { + return typeof refVal == 'object' || typeof refVal == 'boolean' + ? { code: code, schema: refVal, inline: true } + : { code: code, $async: refVal && !!refVal.$async }; + } + + function usePattern(regexStr) { + var index = patternsHash[regexStr]; + if (index === undefined) { + index = patternsHash[regexStr] = patterns.length; + patterns[index] = regexStr; + } + return 'pattern' + index; + } + + function useDefault(value) { + switch (typeof value) { + case 'boolean': + case 'number': + return '' + value; + case 'string': + return util.toQuotedString(value); + case 'object': + if (value === null) return 'null'; + var valueStr = stableStringify(value); + var index = defaultsHash[valueStr]; + if (index === undefined) { + index = defaultsHash[valueStr] = defaults.length; + defaults[index] = value; + } + return 'default' + index; + } + } + + function useCustomRule(rule, schema, parentSchema, it) { + if (self._opts.validateSchema !== false) { + var deps = rule.definition.dependencies; + if (deps && !deps.every(function(keyword) { + return Object.prototype.hasOwnProperty.call(parentSchema, keyword); + })) + throw new Error('parent schema must have all required keywords: ' + deps.join(',')); + + var validateSchema = rule.definition.validateSchema; + if (validateSchema) { + var valid = validateSchema(schema); + if (!valid) { + var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors); + if (self._opts.validateSchema == 'log') self.logger.error(message); + else throw new Error(message); + } + } + } + + var compile = rule.definition.compile + , inline = rule.definition.inline + , macro = rule.definition.macro; + + var validate; + if (compile) { + validate = compile.call(self, schema, parentSchema, it); + } else if (macro) { + validate = macro.call(self, schema, parentSchema, it); + if (opts.validateSchema !== false) self.validateSchema(validate, true); + } else if (inline) { + validate = inline.call(self, it, rule.keyword, schema, parentSchema); + } else { + validate = rule.definition.validate; + if (!validate) return; + } + + if (validate === undefined) + throw new Error('custom keyword "' + rule.keyword + '"failed to compile'); + + var index = customRules.length; + customRules[index] = validate; + + return { + code: 'customRule' + index, + validate: validate + }; + } +} + + +/** + * Checks if the schema is currently compiled + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean) + */ +function checkCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var index = compIndex.call(this, schema, root, baseId); + if (index >= 0) return { index: index, compiling: true }; + index = this._compilations.length; + this._compilations[index] = { + schema: schema, + root: root, + baseId: baseId + }; + return { index: index, compiling: false }; +} + + +/** + * Removes the schema from the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + */ +function endCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var i = compIndex.call(this, schema, root, baseId); + if (i >= 0) this._compilations.splice(i, 1); +} + + +/** + * Index of schema compilation in the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Integer} compilation index + */ +function compIndex(schema, root, baseId) { + /* jshint validthis: true */ + for (var i=0; i= 0xD800 && value <= 0xDBFF && pos < len) { + // high surrogate, and there is a next character + value = str.charCodeAt(pos); + if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate + } + } + return length; +}; diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/compile/util.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/compile/util.js new file mode 100644 index 0000000..ef07b8c --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/compile/util.js @@ -0,0 +1,239 @@ +'use strict'; + + +module.exports = { + copy: copy, + checkDataType: checkDataType, + checkDataTypes: checkDataTypes, + coerceToTypes: coerceToTypes, + toHash: toHash, + getProperty: getProperty, + escapeQuotes: escapeQuotes, + equal: require('fast-deep-equal'), + ucs2length: require('./ucs2length'), + varOccurences: varOccurences, + varReplace: varReplace, + schemaHasRules: schemaHasRules, + schemaHasRulesExcept: schemaHasRulesExcept, + schemaUnknownRules: schemaUnknownRules, + toQuotedString: toQuotedString, + getPathExpr: getPathExpr, + getPath: getPath, + getData: getData, + unescapeFragment: unescapeFragment, + unescapeJsonPointer: unescapeJsonPointer, + escapeFragment: escapeFragment, + escapeJsonPointer: escapeJsonPointer +}; + + +function copy(o, to) { + to = to || {}; + for (var key in o) to[key] = o[key]; + return to; +} + + +function checkDataType(dataType, data, strictNumbers, negate) { + var EQUAL = negate ? ' !== ' : ' === ' + , AND = negate ? ' || ' : ' && ' + , OK = negate ? '!' : '' + , NOT = negate ? '' : '!'; + switch (dataType) { + case 'null': return data + EQUAL + 'null'; + case 'array': return OK + 'Array.isArray(' + data + ')'; + case 'object': return '(' + OK + data + AND + + 'typeof ' + data + EQUAL + '"object"' + AND + + NOT + 'Array.isArray(' + data + '))'; + case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND + + NOT + '(' + data + ' % 1)' + + AND + data + EQUAL + data + + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; + case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' + + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; + default: return 'typeof ' + data + EQUAL + '"' + dataType + '"'; + } +} + + +function checkDataTypes(dataTypes, data, strictNumbers) { + switch (dataTypes.length) { + case 1: return checkDataType(dataTypes[0], data, strictNumbers, true); + default: + var code = ''; + var types = toHash(dataTypes); + if (types.array && types.object) { + code = types.null ? '(': '(!' + data + ' || '; + code += 'typeof ' + data + ' !== "object")'; + delete types.null; + delete types.array; + delete types.object; + } + if (types.number) delete types.integer; + for (var t in types) + code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true); + + return code; + } +} + + +var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]); +function coerceToTypes(optionCoerceTypes, dataTypes) { + if (Array.isArray(dataTypes)) { + var types = []; + for (var i=0; i= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); + return paths[lvl - up]; + } + + if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); + data = 'data' + ((lvl - up) || ''); + if (!jsonPointer) return data; + } + + var expr = data; + var segments = jsonPointer.split('/'); + for (var i=0; i' + , $notOp = $isMax ? '>' : '<' + , $errorKeyword = undefined; + + if (!($isData || typeof $schema == 'number' || $schema === undefined)) { + throw new Error($keyword + ' must be number'); + } + if (!($isDataExcl || $schemaExcl === undefined + || typeof $schemaExcl == 'number' + || typeof $schemaExcl == 'boolean')) { + throw new Error($exclusiveKeyword + ' must be number or boolean'); + } +}} + +{{? $isDataExcl }} + {{ + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr) + , $exclusive = 'exclusive' + $lvl + , $exclType = 'exclType' + $lvl + , $exclIsNumber = 'exclIsNumber' + $lvl + , $opExpr = 'op' + $lvl + , $opStr = '\' + ' + $opExpr + ' + \''; + }} + var schemaExcl{{=$lvl}} = {{=$schemaValueExcl}}; + {{ $schemaValueExcl = 'schemaExcl' + $lvl; }} + + var {{=$exclusive}}; + var {{=$exclType}} = typeof {{=$schemaValueExcl}}; + if ({{=$exclType}} != 'boolean' && {{=$exclType}} != 'undefined' && {{=$exclType}} != 'number') { + {{ var $errorKeyword = $exclusiveKeyword; }} + {{# def.error:'_exclusiveLimit' }} + } else if ({{# def.$dataNotType:'number' }} + {{=$exclType}} == 'number' + ? ( + ({{=$exclusive}} = {{=$schemaValue}} === undefined || {{=$schemaValueExcl}} {{=$op}}= {{=$schemaValue}}) + ? {{=$data}} {{=$notOp}}= {{=$schemaValueExcl}} + : {{=$data}} {{=$notOp}} {{=$schemaValue}} + ) + : ( + ({{=$exclusive}} = {{=$schemaValueExcl}} === true) + ? {{=$data}} {{=$notOp}}= {{=$schemaValue}} + : {{=$data}} {{=$notOp}} {{=$schemaValue}} + ) + || {{=$data}} !== {{=$data}}) { + var op{{=$lvl}} = {{=$exclusive}} ? '{{=$op}}' : '{{=$op}}='; + {{ + if ($schema === undefined) { + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaValueExcl; + $isData = $isDataExcl; + } + }} +{{??}} + {{ + var $exclIsNumber = typeof $schemaExcl == 'number' + , $opStr = $op; /*used in error*/ + }} + + {{? $exclIsNumber && $isData }} + {{ var $opExpr = '\'' + $opStr + '\''; /*used in error*/ }} + if ({{# def.$dataNotType:'number' }} + ( {{=$schemaValue}} === undefined + || {{=$schemaExcl}} {{=$op}}= {{=$schemaValue}} + ? {{=$data}} {{=$notOp}}= {{=$schemaExcl}} + : {{=$data}} {{=$notOp}} {{=$schemaValue}} ) + || {{=$data}} !== {{=$data}}) { + {{??}} + {{ + if ($exclIsNumber && $schema === undefined) { + {{# def.setExclusiveLimit }} + $schemaValue = $schemaExcl; + $notOp += '='; + } else { + if ($exclIsNumber) + $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema); + + if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { + {{# def.setExclusiveLimit }} + $notOp += '='; + } else { + $exclusive = false; + $opStr += '='; + } + } + + var $opExpr = '\'' + $opStr + '\''; /*used in error*/ + }} + + if ({{# def.$dataNotType:'number' }} + {{=$data}} {{=$notOp}} {{=$schemaValue}} + || {{=$data}} !== {{=$data}}) { + {{?}} +{{?}} + {{ $errorKeyword = $errorKeyword || $keyword; }} + {{# def.error:'_limit' }} + } {{? $breakOnError }} else { {{?}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/_limitItems.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/_limitItems.jst new file mode 100644 index 0000000..741329e --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/_limitItems.jst @@ -0,0 +1,12 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{# def.numberKeyword }} + +{{ var $op = $keyword == 'maxItems' ? '>' : '<'; }} +if ({{# def.$dataNotType:'number' }} {{=$data}}.length {{=$op}} {{=$schemaValue}}) { + {{ var $errorKeyword = $keyword; }} + {{# def.error:'_limitItems' }} +} {{? $breakOnError }} else { {{?}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/_limitLength.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/_limitLength.jst new file mode 100644 index 0000000..285c66b --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/_limitLength.jst @@ -0,0 +1,12 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{# def.numberKeyword }} + +{{ var $op = $keyword == 'maxLength' ? '>' : '<'; }} +if ({{# def.$dataNotType:'number' }} {{# def.strLength }} {{=$op}} {{=$schemaValue}}) { + {{ var $errorKeyword = $keyword; }} + {{# def.error:'_limitLength' }} +} {{? $breakOnError }} else { {{?}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/_limitProperties.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/_limitProperties.jst new file mode 100644 index 0000000..c4c2155 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/_limitProperties.jst @@ -0,0 +1,12 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{# def.numberKeyword }} + +{{ var $op = $keyword == 'maxProperties' ? '>' : '<'; }} +if ({{# def.$dataNotType:'number' }} Object.keys({{=$data}}).length {{=$op}} {{=$schemaValue}}) { + {{ var $errorKeyword = $keyword; }} + {{# def.error:'_limitProperties' }} +} {{? $breakOnError }} else { {{?}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/allOf.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/allOf.jst new file mode 100644 index 0000000..0e782fe --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/allOf.jst @@ -0,0 +1,32 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + +{{ + var $currentBaseId = $it.baseId + , $allSchemasEmpty = true; +}} + +{{~ $schema:$sch:$i }} + {{? {{# def.nonEmptySchema:$sch }} }} + {{ + $allSchemasEmpty = false; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + }} + + {{# def.insertSubschemaCode }} + + {{# def.ifResultValid }} + {{?}} +{{~}} + +{{? $breakOnError }} + {{? $allSchemasEmpty }} + if (true) { + {{??}} + {{= $closingBraces.slice(0,-1) }} + {{?}} +{{?}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/anyOf.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/anyOf.jst new file mode 100644 index 0000000..ea909ee --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/anyOf.jst @@ -0,0 +1,46 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + +{{ + var $noEmptySchema = $schema.every(function($sch) { + return {{# def.nonEmptySchema:$sch }}; + }); +}} +{{? $noEmptySchema }} + {{ var $currentBaseId = $it.baseId; }} + var {{=$errs}} = errors; + var {{=$valid}} = false; + + {{# def.setCompositeRule }} + + {{~ $schema:$sch:$i }} + {{ + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + }} + + {{# def.insertSubschemaCode }} + + {{=$valid}} = {{=$valid}} || {{=$nextValid}}; + + if (!{{=$valid}}) { + {{ $closingBraces += '}'; }} + {{~}} + + {{# def.resetCompositeRule }} + + {{= $closingBraces }} + + if (!{{=$valid}}) { + {{# def.extraError:'anyOf' }} + } else { + {{# def.resetErrors }} + {{? it.opts.allErrors }} } {{?}} +{{??}} + {{? $breakOnError }} + if (true) { + {{?}} +{{?}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/coerce.def b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/coerce.def new file mode 100644 index 0000000..c947ed6 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/coerce.def @@ -0,0 +1,51 @@ +{{## def.coerceType: + {{ + var $dataType = 'dataType' + $lvl + , $coerced = 'coerced' + $lvl; + }} + var {{=$dataType}} = typeof {{=$data}}; + var {{=$coerced}} = undefined; + + {{? it.opts.coerceTypes == 'array' }} + if ({{=$dataType}} == 'object' && Array.isArray({{=$data}}) && {{=$data}}.length == 1) { + {{=$data}} = {{=$data}}[0]; + {{=$dataType}} = typeof {{=$data}}; + if ({{=it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)}}) {{=$coerced}} = {{=$data}}; + } + {{?}} + + if ({{=$coerced}} !== undefined) ; + {{~ $coerceToTypes:$type:$i }} + {{? $type == 'string' }} + else if ({{=$dataType}} == 'number' || {{=$dataType}} == 'boolean') + {{=$coerced}} = '' + {{=$data}}; + else if ({{=$data}} === null) {{=$coerced}} = ''; + {{?? $type == 'number' || $type == 'integer' }} + else if ({{=$dataType}} == 'boolean' || {{=$data}} === null + || ({{=$dataType}} == 'string' && {{=$data}} && {{=$data}} == +{{=$data}} + {{? $type == 'integer' }} && !({{=$data}} % 1){{?}})) + {{=$coerced}} = +{{=$data}}; + {{?? $type == 'boolean' }} + else if ({{=$data}} === 'false' || {{=$data}} === 0 || {{=$data}} === null) + {{=$coerced}} = false; + else if ({{=$data}} === 'true' || {{=$data}} === 1) + {{=$coerced}} = true; + {{?? $type == 'null' }} + else if ({{=$data}} === '' || {{=$data}} === 0 || {{=$data}} === false) + {{=$coerced}} = null; + {{?? it.opts.coerceTypes == 'array' && $type == 'array' }} + else if ({{=$dataType}} == 'string' || {{=$dataType}} == 'number' || {{=$dataType}} == 'boolean' || {{=$data}} == null) + {{=$coerced}} = [{{=$data}}]; + {{?}} + {{~}} + else { + {{# def.error:'type' }} + } + + if ({{=$coerced}} !== undefined) { + {{# def.setParentData }} + {{=$data}} = {{=$coerced}}; + {{? !$dataLvl }}if ({{=$parentData}} !== undefined){{?}} + {{=$parentData}}[{{=$parentDataProperty}}] = {{=$coerced}}; + } +#}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/comment.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/comment.jst new file mode 100644 index 0000000..f959150 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/comment.jst @@ -0,0 +1,9 @@ +{{# def.definitions }} +{{# def.setupKeyword }} + +{{ var $comment = it.util.toQuotedString($schema); }} +{{? it.opts.$comment === true }} + console.log({{=$comment}}); +{{?? typeof it.opts.$comment == 'function' }} + self._opts.$comment({{=$comment}}, {{=it.util.toQuotedString($errSchemaPath)}}, validate.root.schema); +{{?}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/const.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/const.jst new file mode 100644 index 0000000..2aa2298 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/const.jst @@ -0,0 +1,11 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{? !$isData }} + var schema{{=$lvl}} = validate.schema{{=$schemaPath}}; +{{?}} +var {{=$valid}} = equal({{=$data}}, schema{{=$lvl}}); +{{# def.checkError:'const' }} +{{? $breakOnError }} else { {{?}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/contains.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/contains.jst new file mode 100644 index 0000000..4dc9967 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/contains.jst @@ -0,0 +1,55 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + + +{{ + var $idx = 'i' + $lvl + , $dataNxt = $it.dataLevel = it.dataLevel + 1 + , $nextData = 'data' + $dataNxt + , $currentBaseId = it.baseId + , $nonEmptySchema = {{# def.nonEmptySchema:$schema }}; +}} + +var {{=$errs}} = errors; +var {{=$valid}}; + +{{? $nonEmptySchema }} + {{# def.setCompositeRule }} + + {{ + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + }} + + var {{=$nextValid}} = false; + + for (var {{=$idx}} = 0; {{=$idx}} < {{=$data}}.length; {{=$idx}}++) { + {{ + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + }} + + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} + + if ({{=$nextValid}}) break; + } + + {{# def.resetCompositeRule }} + {{= $closingBraces }} + + if (!{{=$nextValid}}) { +{{??}} + if ({{=$data}}.length == 0) { +{{?}} + + {{# def.error:'contains' }} + } else { + {{? $nonEmptySchema }} + {{# def.resetErrors }} + {{?}} + {{? it.opts.allErrors }} } {{?}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/custom.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/custom.jst new file mode 100644 index 0000000..d30588f --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/custom.jst @@ -0,0 +1,191 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{ + var $rule = this + , $definition = 'definition' + $lvl + , $rDef = $rule.definition + , $closingBraces = ''; + var $validate = $rDef.validate; + var $compile, $inline, $macro, $ruleValidate, $validateCode; +}} + +{{? $isData && $rDef.$data }} + {{ + $validateCode = 'keywordValidate' + $lvl; + var $validateSchema = $rDef.validateSchema; + }} + var {{=$definition}} = RULES.custom['{{=$keyword}}'].definition; + var {{=$validateCode}} = {{=$definition}}.validate; +{{??}} + {{ + $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); + if (!$ruleValidate) return; + $schemaValue = 'validate.schema' + $schemaPath; + $validateCode = $ruleValidate.code; + $compile = $rDef.compile; + $inline = $rDef.inline; + $macro = $rDef.macro; + }} +{{?}} + +{{ + var $ruleErrs = $validateCode + '.errors' + , $i = 'i' + $lvl + , $ruleErr = 'ruleErr' + $lvl + , $asyncKeyword = $rDef.async; + + if ($asyncKeyword && !it.async) + throw new Error('async keyword in sync schema'); +}} + + +{{? !($inline || $macro) }}{{=$ruleErrs}} = null;{{?}} +var {{=$errs}} = errors; +var {{=$valid}}; + +{{## def.callRuleValidate: + {{=$validateCode}}.call( + {{? it.opts.passContext }}this{{??}}self{{?}} + {{? $compile || $rDef.schema === false }} + , {{=$data}} + {{??}} + , {{=$schemaValue}} + , {{=$data}} + , validate.schema{{=it.schemaPath}} + {{?}} + , {{# def.dataPath }} + {{# def.passParentData }} + , rootData + ) +#}} + +{{## def.extendErrors:_inline: + for (var {{=$i}}={{=$errs}}; {{=$i}} 0) + || _schema === false + : it.util.schemaHasRules(_schema, it.RULES.all)) +#}} + + +{{## def.strLength: + {{? it.opts.unicode === false }} + {{=$data}}.length + {{??}} + ucs2length({{=$data}}) + {{?}} +#}} + + +{{## def.willOptimize: + it.util.varOccurences($code, $nextData) < 2 +#}} + + +{{## def.generateSubschemaCode: + {{ + var $code = it.validate($it); + $it.baseId = $currentBaseId; + }} +#}} + + +{{## def.insertSubschemaCode: + {{= it.validate($it) }} + {{ $it.baseId = $currentBaseId; }} +#}} + + +{{## def._optimizeValidate: + it.util.varReplace($code, $nextData, $passData) +#}} + + +{{## def.optimizeValidate: + {{? {{# def.willOptimize}} }} + {{= {{# def._optimizeValidate }} }} + {{??}} + var {{=$nextData}} = {{=$passData}}; + {{= $code }} + {{?}} +#}} + + +{{## def.$data: + {{ + var $isData = it.opts.$data && $schema && $schema.$data + , $schemaValue; + }} + {{? $isData }} + var schema{{=$lvl}} = {{= it.util.getData($schema.$data, $dataLvl, it.dataPathArr) }}; + {{ $schemaValue = 'schema' + $lvl; }} + {{??}} + {{ $schemaValue = $schema; }} + {{?}} +#}} + + +{{## def.$dataNotType:_type: + {{?$isData}} ({{=$schemaValue}} !== undefined && typeof {{=$schemaValue}} != _type) || {{?}} +#}} + + +{{## def.check$dataIsArray: + if (schema{{=$lvl}} === undefined) {{=$valid}} = true; + else if (!Array.isArray(schema{{=$lvl}})) {{=$valid}} = false; + else { +#}} + + +{{## def.numberKeyword: + {{? !($isData || typeof $schema == 'number') }} + {{ throw new Error($keyword + ' must be number'); }} + {{?}} +#}} + + +{{## def.beginDefOut: + {{ + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + }} +#}} + + +{{## def.storeDefOut:_variable: + {{ + var _variable = out; + out = $$outStack.pop(); + }} +#}} + + +{{## def.dataPath:(dataPath || ''){{? it.errorPath != '""'}} + {{= it.errorPath }}{{?}}#}} + +{{## def.setParentData: + {{ + var $parentData = $dataLvl ? 'data' + (($dataLvl-1)||'') : 'parentData' + , $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + }} +#}} + +{{## def.passParentData: + {{# def.setParentData }} + , {{= $parentData }} + , {{= $parentDataProperty }} +#}} + + +{{## def.iterateProperties: + {{? $ownProperties }} + {{=$dataProperties}} = {{=$dataProperties}} || Object.keys({{=$data}}); + for (var {{=$idx}}=0; {{=$idx}}<{{=$dataProperties}}.length; {{=$idx}}++) { + var {{=$key}} = {{=$dataProperties}}[{{=$idx}}]; + {{??}} + for (var {{=$key}} in {{=$data}}) { + {{?}} +#}} + + +{{## def.noPropertyInData: + {{=$useData}} === undefined + {{? $ownProperties }} + || !{{# def.isOwnProperty }} + {{?}} +#}} + + +{{## def.isOwnProperty: + Object.prototype.hasOwnProperty.call({{=$data}}, '{{=it.util.escapeQuotes($propertyKey)}}') +#}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/dependencies.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/dependencies.jst new file mode 100644 index 0000000..e4bddde --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/dependencies.jst @@ -0,0 +1,79 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.missing }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + + +{{## def.propertyInData: + {{=$data}}{{= it.util.getProperty($property) }} !== undefined + {{? $ownProperties }} + && Object.prototype.hasOwnProperty.call({{=$data}}, '{{=it.util.escapeQuotes($property)}}') + {{?}} +#}} + + +{{ + var $schemaDeps = {} + , $propertyDeps = {} + , $ownProperties = it.opts.ownProperties; + + for ($property in $schema) { + if ($property == '__proto__') continue; + var $sch = $schema[$property]; + var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps; + $deps[$property] = $sch; + } +}} + +var {{=$errs}} = errors; + +{{ var $currentErrorPath = it.errorPath; }} + +var missing{{=$lvl}}; +{{ for (var $property in $propertyDeps) { }} + {{ $deps = $propertyDeps[$property]; }} + {{? $deps.length }} + if ({{# def.propertyInData }} + {{? $breakOnError }} + && ({{# def.checkMissingProperty:$deps }})) { + {{# def.errorMissingProperty:'dependencies' }} + {{??}} + ) { + {{~ $deps:$propertyKey }} + {{# def.allErrorsMissingProperty:'dependencies' }} + {{~}} + {{?}} + } {{# def.elseIfValid }} + {{?}} +{{ } }} + +{{ + it.errorPath = $currentErrorPath; + var $currentBaseId = $it.baseId; +}} + + +{{ for (var $property in $schemaDeps) { }} + {{ var $sch = $schemaDeps[$property]; }} + {{? {{# def.nonEmptySchema:$sch }} }} + {{=$nextValid}} = true; + + if ({{# def.propertyInData }}) { + {{ + $it.schema = $sch; + $it.schemaPath = $schemaPath + it.util.getProperty($property); + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property); + }} + + {{# def.insertSubschemaCode }} + } + + {{# def.ifResultValid }} + {{?}} +{{ } }} + +{{? $breakOnError }} + {{= $closingBraces }} + if ({{=$errs}} == errors) { +{{?}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/enum.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/enum.jst new file mode 100644 index 0000000..357c2e8 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/enum.jst @@ -0,0 +1,30 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{ + var $i = 'i' + $lvl + , $vSchema = 'schema' + $lvl; +}} + +{{? !$isData }} + var {{=$vSchema}} = validate.schema{{=$schemaPath}}; +{{?}} +var {{=$valid}}; + +{{?$isData}}{{# def.check$dataIsArray }}{{?}} + +{{=$valid}} = false; + +for (var {{=$i}}=0; {{=$i}}<{{=$vSchema}}.length; {{=$i}}++) + if (equal({{=$data}}, {{=$vSchema}}[{{=$i}}])) { + {{=$valid}} = true; + break; + } + +{{? $isData }} } {{?}} + +{{# def.checkError:'enum' }} + +{{? $breakOnError }} else { {{?}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/errors.def b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/errors.def new file mode 100644 index 0000000..5c5752c --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/errors.def @@ -0,0 +1,194 @@ +{{# def.definitions }} + +{{## def._error:_rule: + {{ 'istanbul ignore else'; }} + {{? it.createErrors !== false }} + { + keyword: '{{= $errorKeyword || _rule }}' + , dataPath: (dataPath || '') + {{= it.errorPath }} + , schemaPath: {{=it.util.toQuotedString($errSchemaPath)}} + , params: {{# def._errorParams[_rule] }} + {{? it.opts.messages !== false }} + , message: {{# def._errorMessages[_rule] }} + {{?}} + {{? it.opts.verbose }} + , schema: {{# def._errorSchemas[_rule] }} + , parentSchema: validate.schema{{=it.schemaPath}} + , data: {{=$data}} + {{?}} + } + {{??}} + {} + {{?}} +#}} + + +{{## def._addError:_rule: + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; +#}} + + +{{## def.addError:_rule: + var err = {{# def._error:_rule }}; + {{# def._addError:_rule }} +#}} + + +{{## def.error:_rule: + {{# def.beginDefOut}} + {{# def._error:_rule }} + {{# def.storeDefOut:__err }} + + {{? !it.compositeRule && $breakOnError }} + {{ 'istanbul ignore if'; }} + {{? it.async }} + throw new ValidationError([{{=__err}}]); + {{??}} + validate.errors = [{{=__err}}]; + return false; + {{?}} + {{??}} + var err = {{=__err}}; + {{# def._addError:_rule }} + {{?}} +#}} + + +{{## def.extraError:_rule: + {{# def.addError:_rule}} + {{? !it.compositeRule && $breakOnError }} + {{ 'istanbul ignore if'; }} + {{? it.async }} + throw new ValidationError(vErrors); + {{??}} + validate.errors = vErrors; + return false; + {{?}} + {{?}} +#}} + + +{{## def.checkError:_rule: + if (!{{=$valid}}) { + {{# def.error:_rule }} + } +#}} + + +{{## def.resetErrors: + errors = {{=$errs}}; + if (vErrors !== null) { + if ({{=$errs}}) vErrors.length = {{=$errs}}; + else vErrors = null; + } +#}} + + +{{## def.concatSchema:{{?$isData}}' + {{=$schemaValue}} + '{{??}}{{=$schema}}{{?}}#}} +{{## def.appendSchema:{{?$isData}}' + {{=$schemaValue}}{{??}}{{=$schemaValue}}'{{?}}#}} +{{## def.concatSchemaEQ:{{?$isData}}' + {{=$schemaValue}} + '{{??}}{{=it.util.escapeQuotes($schema)}}{{?}}#}} + +{{## def._errorMessages = { + 'false schema': "'boolean schema is false'", + $ref: "'can\\\'t resolve reference {{=it.util.escapeQuotes($schema)}}'", + additionalItems: "'should NOT have more than {{=$schema.length}} items'", + additionalProperties: "'{{? it.opts._errorDataPathProperty }}is an invalid additional property{{??}}should NOT have additional properties{{?}}'", + anyOf: "'should match some schema in anyOf'", + const: "'should be equal to constant'", + contains: "'should contain a valid item'", + dependencies: "'should have {{? $deps.length == 1 }}property {{= it.util.escapeQuotes($deps[0]) }}{{??}}properties {{= it.util.escapeQuotes($deps.join(\", \")) }}{{?}} when property {{= it.util.escapeQuotes($property) }} is present'", + 'enum': "'should be equal to one of the allowed values'", + format: "'should match format \"{{#def.concatSchemaEQ}}\"'", + 'if': "'should match \"' + {{=$ifClause}} + '\" schema'", + _limit: "'should be {{=$opStr}} {{#def.appendSchema}}", + _exclusiveLimit: "'{{=$exclusiveKeyword}} should be boolean'", + _limitItems: "'should NOT have {{?$keyword=='maxItems'}}more{{??}}fewer{{?}} than {{#def.concatSchema}} items'", + _limitLength: "'should NOT be {{?$keyword=='maxLength'}}longer{{??}}shorter{{?}} than {{#def.concatSchema}} characters'", + _limitProperties:"'should NOT have {{?$keyword=='maxProperties'}}more{{??}}fewer{{?}} than {{#def.concatSchema}} properties'", + multipleOf: "'should be multiple of {{#def.appendSchema}}", + not: "'should NOT be valid'", + oneOf: "'should match exactly one schema in oneOf'", + pattern: "'should match pattern \"{{#def.concatSchemaEQ}}\"'", + propertyNames: "'property name \\'{{=$invalidName}}\\' is invalid'", + required: "'{{? it.opts._errorDataPathProperty }}is a required property{{??}}should have required property \\'{{=$missingProperty}}\\'{{?}}'", + type: "'should be {{? $typeIsArray }}{{= $typeSchema.join(\",\") }}{{??}}{{=$typeSchema}}{{?}}'", + uniqueItems: "'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)'", + custom: "'should pass \"{{=$rule.keyword}}\" keyword validation'", + patternRequired: "'should have property matching pattern \\'{{=$missingPattern}}\\''", + switch: "'should pass \"switch\" keyword validation'", + _formatLimit: "'should be {{=$opStr}} \"{{#def.concatSchemaEQ}}\"'", + _formatExclusiveLimit: "'{{=$exclusiveKeyword}} should be boolean'" +} #}} + + +{{## def.schemaRefOrVal: {{?$isData}}validate.schema{{=$schemaPath}}{{??}}{{=$schema}}{{?}} #}} +{{## def.schemaRefOrQS: {{?$isData}}validate.schema{{=$schemaPath}}{{??}}{{=it.util.toQuotedString($schema)}}{{?}} #}} + +{{## def._errorSchemas = { + 'false schema': "false", + $ref: "{{=it.util.toQuotedString($schema)}}", + additionalItems: "false", + additionalProperties: "false", + anyOf: "validate.schema{{=$schemaPath}}", + const: "validate.schema{{=$schemaPath}}", + contains: "validate.schema{{=$schemaPath}}", + dependencies: "validate.schema{{=$schemaPath}}", + 'enum': "validate.schema{{=$schemaPath}}", + format: "{{#def.schemaRefOrQS}}", + 'if': "validate.schema{{=$schemaPath}}", + _limit: "{{#def.schemaRefOrVal}}", + _exclusiveLimit: "validate.schema{{=$schemaPath}}", + _limitItems: "{{#def.schemaRefOrVal}}", + _limitLength: "{{#def.schemaRefOrVal}}", + _limitProperties:"{{#def.schemaRefOrVal}}", + multipleOf: "{{#def.schemaRefOrVal}}", + not: "validate.schema{{=$schemaPath}}", + oneOf: "validate.schema{{=$schemaPath}}", + pattern: "{{#def.schemaRefOrQS}}", + propertyNames: "validate.schema{{=$schemaPath}}", + required: "validate.schema{{=$schemaPath}}", + type: "validate.schema{{=$schemaPath}}", + uniqueItems: "{{#def.schemaRefOrVal}}", + custom: "validate.schema{{=$schemaPath}}", + patternRequired: "validate.schema{{=$schemaPath}}", + switch: "validate.schema{{=$schemaPath}}", + _formatLimit: "{{#def.schemaRefOrQS}}", + _formatExclusiveLimit: "validate.schema{{=$schemaPath}}" +} #}} + + +{{## def.schemaValueQS: {{?$isData}}{{=$schemaValue}}{{??}}{{=it.util.toQuotedString($schema)}}{{?}} #}} + +{{## def._errorParams = { + 'false schema': "{}", + $ref: "{ ref: '{{=it.util.escapeQuotes($schema)}}' }", + additionalItems: "{ limit: {{=$schema.length}} }", + additionalProperties: "{ additionalProperty: '{{=$additionalProperty}}' }", + anyOf: "{}", + const: "{ allowedValue: schema{{=$lvl}} }", + contains: "{}", + dependencies: "{ property: '{{= it.util.escapeQuotes($property) }}', missingProperty: '{{=$missingProperty}}', depsCount: {{=$deps.length}}, deps: '{{= it.util.escapeQuotes($deps.length==1 ? $deps[0] : $deps.join(\", \")) }}' }", + 'enum': "{ allowedValues: schema{{=$lvl}} }", + format: "{ format: {{#def.schemaValueQS}} }", + 'if': "{ failingKeyword: {{=$ifClause}} }", + _limit: "{ comparison: {{=$opExpr}}, limit: {{=$schemaValue}}, exclusive: {{=$exclusive}} }", + _exclusiveLimit: "{}", + _limitItems: "{ limit: {{=$schemaValue}} }", + _limitLength: "{ limit: {{=$schemaValue}} }", + _limitProperties:"{ limit: {{=$schemaValue}} }", + multipleOf: "{ multipleOf: {{=$schemaValue}} }", + not: "{}", + oneOf: "{ passingSchemas: {{=$passingSchemas}} }", + pattern: "{ pattern: {{#def.schemaValueQS}} }", + propertyNames: "{ propertyName: '{{=$invalidName}}' }", + required: "{ missingProperty: '{{=$missingProperty}}' }", + type: "{ type: '{{? $typeIsArray }}{{= $typeSchema.join(\",\") }}{{??}}{{=$typeSchema}}{{?}}' }", + uniqueItems: "{ i: i, j: j }", + custom: "{ keyword: '{{=$rule.keyword}}' }", + patternRequired: "{ missingPattern: '{{=$missingPattern}}' }", + switch: "{ caseIndex: {{=$caseIndex}} }", + _formatLimit: "{ comparison: {{=$opExpr}}, limit: {{#def.schemaValueQS}}, exclusive: {{=$exclusive}} }", + _formatExclusiveLimit: "{}" +} #}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/format.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/format.jst new file mode 100644 index 0000000..37f14da --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/format.jst @@ -0,0 +1,106 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} + +{{## def.skipFormat: + {{? $breakOnError }} if (true) { {{?}} + {{ return out; }} +#}} + +{{? it.opts.format === false }}{{# def.skipFormat }}{{?}} + + +{{# def.$data }} + + +{{## def.$dataCheckFormat: + {{# def.$dataNotType:'string' }} + ({{? $unknownFormats != 'ignore' }} + ({{=$schemaValue}} && !{{=$format}} + {{? $allowUnknown }} + && self._opts.unknownFormats.indexOf({{=$schemaValue}}) == -1 + {{?}}) || + {{?}} + ({{=$format}} && {{=$formatType}} == '{{=$ruleType}}' + && !(typeof {{=$format}} == 'function' + ? {{? it.async}} + (async{{=$lvl}} ? await {{=$format}}({{=$data}}) : {{=$format}}({{=$data}})) + {{??}} + {{=$format}}({{=$data}}) + {{?}} + : {{=$format}}.test({{=$data}})))) +#}} + +{{## def.checkFormat: + {{ + var $formatRef = 'formats' + it.util.getProperty($schema); + if ($isObject) $formatRef += '.validate'; + }} + {{? typeof $format == 'function' }} + {{=$formatRef}}({{=$data}}) + {{??}} + {{=$formatRef}}.test({{=$data}}) + {{?}} +#}} + + +{{ + var $unknownFormats = it.opts.unknownFormats + , $allowUnknown = Array.isArray($unknownFormats); +}} + +{{? $isData }} + {{ + var $format = 'format' + $lvl + , $isObject = 'isObject' + $lvl + , $formatType = 'formatType' + $lvl; + }} + var {{=$format}} = formats[{{=$schemaValue}}]; + var {{=$isObject}} = typeof {{=$format}} == 'object' + && !({{=$format}} instanceof RegExp) + && {{=$format}}.validate; + var {{=$formatType}} = {{=$isObject}} && {{=$format}}.type || 'string'; + if ({{=$isObject}}) { + {{? it.async}} + var async{{=$lvl}} = {{=$format}}.async; + {{?}} + {{=$format}} = {{=$format}}.validate; + } + if ({{# def.$dataCheckFormat }}) { +{{??}} + {{ var $format = it.formats[$schema]; }} + {{? !$format }} + {{? $unknownFormats == 'ignore' }} + {{ it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); }} + {{# def.skipFormat }} + {{?? $allowUnknown && $unknownFormats.indexOf($schema) >= 0 }} + {{# def.skipFormat }} + {{??}} + {{ throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); }} + {{?}} + {{?}} + {{ + var $isObject = typeof $format == 'object' + && !($format instanceof RegExp) + && $format.validate; + var $formatType = $isObject && $format.type || 'string'; + if ($isObject) { + var $async = $format.async === true; + $format = $format.validate; + } + }} + {{? $formatType != $ruleType }} + {{# def.skipFormat }} + {{?}} + {{? $async }} + {{ + if (!it.async) throw new Error('async format in sync schema'); + var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; + }} + if (!(await {{=$formatRef}}({{=$data}}))) { + {{??}} + if (!{{# def.checkFormat }}) { + {{?}} +{{?}} + {{# def.error:'format' }} + } {{? $breakOnError }} else { {{?}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/if.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/if.jst new file mode 100644 index 0000000..adb5036 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/if.jst @@ -0,0 +1,73 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + + +{{## def.validateIfClause:_clause: + {{ + $it.schema = it.schema['_clause']; + $it.schemaPath = it.schemaPath + '._clause'; + $it.errSchemaPath = it.errSchemaPath + '/_clause'; + }} + {{# def.insertSubschemaCode }} + {{=$valid}} = {{=$nextValid}}; + {{? $thenPresent && $elsePresent }} + {{ $ifClause = 'ifClause' + $lvl; }} + var {{=$ifClause}} = '_clause'; + {{??}} + {{ $ifClause = '\'_clause\''; }} + {{?}} +#}} + +{{ + var $thenSch = it.schema['then'] + , $elseSch = it.schema['else'] + , $thenPresent = $thenSch !== undefined && {{# def.nonEmptySchema:$thenSch }} + , $elsePresent = $elseSch !== undefined && {{# def.nonEmptySchema:$elseSch }} + , $currentBaseId = $it.baseId; +}} + +{{? $thenPresent || $elsePresent }} + {{ + var $ifClause; + $it.createErrors = false; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + }} + var {{=$errs}} = errors; + var {{=$valid}} = true; + + {{# def.setCompositeRule }} + {{# def.insertSubschemaCode }} + {{ $it.createErrors = true; }} + {{# def.resetErrors }} + {{# def.resetCompositeRule }} + + {{? $thenPresent }} + if ({{=$nextValid}}) { + {{# def.validateIfClause:then }} + } + {{? $elsePresent }} + else { + {{?}} + {{??}} + if (!{{=$nextValid}}) { + {{?}} + + {{? $elsePresent }} + {{# def.validateIfClause:else }} + } + {{?}} + + if (!{{=$valid}}) { + {{# def.extraError:'if' }} + } + {{? $breakOnError }} else { {{?}} +{{??}} + {{? $breakOnError }} + if (true) { + {{?}} +{{?}} + diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/items.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/items.jst new file mode 100644 index 0000000..acc932a --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/items.jst @@ -0,0 +1,98 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + + +{{## def.validateItems:startFrom: + for (var {{=$idx}} = {{=startFrom}}; {{=$idx}} < {{=$data}}.length; {{=$idx}}++) { + {{ + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + }} + + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} + + {{? $breakOnError }} + if (!{{=$nextValid}}) break; + {{?}} + } +#}} + +{{ + var $idx = 'i' + $lvl + , $dataNxt = $it.dataLevel = it.dataLevel + 1 + , $nextData = 'data' + $dataNxt + , $currentBaseId = it.baseId; +}} + +var {{=$errs}} = errors; +var {{=$valid}}; + +{{? Array.isArray($schema) }} + {{ /* 'items' is an array of schemas */}} + {{ var $additionalItems = it.schema.additionalItems; }} + {{? $additionalItems === false }} + {{=$valid}} = {{=$data}}.length <= {{= $schema.length }}; + {{ + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalItems'; + }} + {{# def.checkError:'additionalItems' }} + {{ $errSchemaPath = $currErrSchemaPath; }} + {{# def.elseIfValid}} + {{?}} + + {{~ $schema:$sch:$i }} + {{? {{# def.nonEmptySchema:$sch }} }} + {{=$nextValid}} = true; + + if ({{=$data}}.length > {{=$i}}) { + {{ + var $passData = $data + '[' + $i + ']'; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); + $it.dataPathArr[$dataNxt] = $i; + }} + + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} + } + + {{# def.ifResultValid }} + {{?}} + {{~}} + + {{? typeof $additionalItems == 'object' && {{# def.nonEmptySchema:$additionalItems }} }} + {{ + $it.schema = $additionalItems; + $it.schemaPath = it.schemaPath + '.additionalItems'; + $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; + }} + {{=$nextValid}} = true; + + if ({{=$data}}.length > {{= $schema.length }}) { + {{# def.validateItems: $schema.length }} + } + + {{# def.ifResultValid }} + {{?}} + +{{?? {{# def.nonEmptySchema:$schema }} }} + {{ /* 'items' is a single schema */}} + {{ + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + }} + {{# def.validateItems: 0 }} +{{?}} + +{{? $breakOnError }} + {{= $closingBraces }} + if ({{=$errs}} == errors) { +{{?}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/missing.def b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/missing.def new file mode 100644 index 0000000..a73b9f9 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/missing.def @@ -0,0 +1,39 @@ +{{## def.checkMissingProperty:_properties: + {{~ _properties:$propertyKey:$i }} + {{?$i}} || {{?}} + {{ + var $prop = it.util.getProperty($propertyKey) + , $useData = $data + $prop; + }} + ( ({{# def.noPropertyInData }}) && (missing{{=$lvl}} = {{= it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) }}) ) + {{~}} +#}} + + +{{## def.errorMissingProperty:_error: + {{ + var $propertyPath = 'missing' + $lvl + , $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers + ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) + : $currentErrorPath + ' + ' + $propertyPath; + } + }} + {{# def.error:_error }} +#}} + + +{{## def.allErrorsMissingProperty:_error: + {{ + var $prop = it.util.getProperty($propertyKey) + , $missingProperty = it.util.escapeQuotes($propertyKey) + , $useData = $data + $prop; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + }} + if ({{# def.noPropertyInData }}) { + {{# def.addError:_error }} + } +#}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/multipleOf.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/multipleOf.jst new file mode 100644 index 0000000..6d88a45 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/multipleOf.jst @@ -0,0 +1,22 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{# def.numberKeyword }} + +var division{{=$lvl}}; +if ({{?$isData}} + {{=$schemaValue}} !== undefined && ( + typeof {{=$schemaValue}} != 'number' || + {{?}} + (division{{=$lvl}} = {{=$data}} / {{=$schemaValue}}, + {{? it.opts.multipleOfPrecision }} + Math.abs(Math.round(division{{=$lvl}}) - division{{=$lvl}}) > 1e-{{=it.opts.multipleOfPrecision}} + {{??}} + division{{=$lvl}} !== parseInt(division{{=$lvl}}) + {{?}} + ) + {{?$isData}} ) {{?}} ) { + {{# def.error:'multipleOf' }} +} {{? $breakOnError }} else { {{?}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/not.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/not.jst new file mode 100644 index 0000000..e03185a --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/not.jst @@ -0,0 +1,43 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + +{{? {{# def.nonEmptySchema:$schema }} }} + {{ + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + }} + + var {{=$errs}} = errors; + + {{# def.setCompositeRule }} + + {{ + $it.createErrors = false; + var $allErrorsOption; + if ($it.opts.allErrors) { + $allErrorsOption = $it.opts.allErrors; + $it.opts.allErrors = false; + } + }} + {{= it.validate($it) }} + {{ + $it.createErrors = true; + if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; + }} + + {{# def.resetCompositeRule }} + + if ({{=$nextValid}}) { + {{# def.error:'not' }} + } else { + {{# def.resetErrors }} + {{? it.opts.allErrors }} } {{?}} +{{??}} + {{# def.addError:'not' }} + {{? $breakOnError}} + if (false) { + {{?}} +{{?}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/oneOf.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/oneOf.jst new file mode 100644 index 0000000..bcce2c6 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/oneOf.jst @@ -0,0 +1,54 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + +{{ + var $currentBaseId = $it.baseId + , $prevValid = 'prevValid' + $lvl + , $passingSchemas = 'passingSchemas' + $lvl; +}} + +var {{=$errs}} = errors + , {{=$prevValid}} = false + , {{=$valid}} = false + , {{=$passingSchemas}} = null; + +{{# def.setCompositeRule }} + +{{~ $schema:$sch:$i }} + {{? {{# def.nonEmptySchema:$sch }} }} + {{ + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + }} + + {{# def.insertSubschemaCode }} + {{??}} + var {{=$nextValid}} = true; + {{?}} + + {{? $i }} + if ({{=$nextValid}} && {{=$prevValid}}) { + {{=$valid}} = false; + {{=$passingSchemas}} = [{{=$passingSchemas}}, {{=$i}}]; + } else { + {{ $closingBraces += '}'; }} + {{?}} + + if ({{=$nextValid}}) { + {{=$valid}} = {{=$prevValid}} = true; + {{=$passingSchemas}} = {{=$i}}; + } +{{~}} + +{{# def.resetCompositeRule }} + +{{= $closingBraces }} + +if (!{{=$valid}}) { + {{# def.extraError:'oneOf' }} +} else { + {{# def.resetErrors }} +{{? it.opts.allErrors }} } {{?}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/pattern.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/pattern.jst new file mode 100644 index 0000000..3a37ef6 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/pattern.jst @@ -0,0 +1,14 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{ + var $regexp = $isData + ? '(new RegExp(' + $schemaValue + '))' + : it.usePattern($schema); +}} + +if ({{# def.$dataNotType:'string' }} !{{=$regexp}}.test({{=$data}}) ) { + {{# def.error:'pattern' }} +} {{? $breakOnError }} else { {{?}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/properties.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/properties.jst new file mode 100644 index 0000000..5cebb9b --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/properties.jst @@ -0,0 +1,245 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + + +{{## def.validateAdditional: + {{ /* additionalProperties is schema */ + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty + ? it.errorPath + : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + }} + + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} +#}} + + +{{ + var $key = 'key' + $lvl + , $idx = 'idx' + $lvl + , $dataNxt = $it.dataLevel = it.dataLevel + 1 + , $nextData = 'data' + $dataNxt + , $dataProperties = 'dataProperties' + $lvl; + + var $schemaKeys = Object.keys($schema || {}).filter(notProto) + , $pProperties = it.schema.patternProperties || {} + , $pPropertyKeys = Object.keys($pProperties).filter(notProto) + , $aProperties = it.schema.additionalProperties + , $someProperties = $schemaKeys.length || $pPropertyKeys.length + , $noAdditional = $aProperties === false + , $additionalIsSchema = typeof $aProperties == 'object' + && Object.keys($aProperties).length + , $removeAdditional = it.opts.removeAdditional + , $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional + , $ownProperties = it.opts.ownProperties + , $currentBaseId = it.baseId; + + var $required = it.schema.required; + if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) { + var $requiredHash = it.util.toHash($required); + } + + function notProto(p) { return p !== '__proto__'; } +}} + + +var {{=$errs}} = errors; +var {{=$nextValid}} = true; +{{? $ownProperties }} + var {{=$dataProperties}} = undefined; +{{?}} + +{{? $checkAdditional }} + {{# def.iterateProperties }} + {{? $someProperties }} + var isAdditional{{=$lvl}} = !(false + {{? $schemaKeys.length }} + {{? $schemaKeys.length > 8 }} + || validate.schema{{=$schemaPath}}.hasOwnProperty({{=$key}}) + {{??}} + {{~ $schemaKeys:$propertyKey }} + || {{=$key}} == {{= it.util.toQuotedString($propertyKey) }} + {{~}} + {{?}} + {{?}} + {{? $pPropertyKeys.length }} + {{~ $pPropertyKeys:$pProperty:$i }} + || {{= it.usePattern($pProperty) }}.test({{=$key}}) + {{~}} + {{?}} + ); + + if (isAdditional{{=$lvl}}) { + {{?}} + {{? $removeAdditional == 'all' }} + delete {{=$data}}[{{=$key}}]; + {{??}} + {{ + var $currentErrorPath = it.errorPath; + var $additionalProperty = '\' + ' + $key + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + } + }} + {{? $noAdditional }} + {{? $removeAdditional }} + delete {{=$data}}[{{=$key}}]; + {{??}} + {{=$nextValid}} = false; + {{ + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalProperties'; + }} + {{# def.error:'additionalProperties' }} + {{ $errSchemaPath = $currErrSchemaPath; }} + {{? $breakOnError }} break; {{?}} + {{?}} + {{?? $additionalIsSchema }} + {{? $removeAdditional == 'failing' }} + var {{=$errs}} = errors; + {{# def.setCompositeRule }} + + {{# def.validateAdditional }} + + if (!{{=$nextValid}}) { + errors = {{=$errs}}; + if (validate.errors !== null) { + if (errors) validate.errors.length = errors; + else validate.errors = null; + } + delete {{=$data}}[{{=$key}}]; + } + + {{# def.resetCompositeRule }} + {{??}} + {{# def.validateAdditional }} + {{? $breakOnError }} if (!{{=$nextValid}}) break; {{?}} + {{?}} + {{?}} + {{ it.errorPath = $currentErrorPath; }} + {{?}} + {{? $someProperties }} + } + {{?}} + } + + {{# def.ifResultValid }} +{{?}} + +{{ var $useDefaults = it.opts.useDefaults && !it.compositeRule; }} + +{{? $schemaKeys.length }} + {{~ $schemaKeys:$propertyKey }} + {{ var $sch = $schema[$propertyKey]; }} + + {{? {{# def.nonEmptySchema:$sch}} }} + {{ + var $prop = it.util.getProperty($propertyKey) + , $passData = $data + $prop + , $hasDefault = $useDefaults && $sch.default !== undefined; + $it.schema = $sch; + $it.schemaPath = $schemaPath + $prop; + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); + $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); + $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); + }} + + {{# def.generateSubschemaCode }} + + {{? {{# def.willOptimize }} }} + {{ + $code = {{# def._optimizeValidate }}; + var $useData = $passData; + }} + {{??}} + {{ var $useData = $nextData; }} + var {{=$nextData}} = {{=$passData}}; + {{?}} + + {{? $hasDefault }} + {{= $code }} + {{??}} + {{? $requiredHash && $requiredHash[$propertyKey] }} + if ({{# def.noPropertyInData }}) { + {{=$nextValid}} = false; + {{ + var $currentErrorPath = it.errorPath + , $currErrSchemaPath = $errSchemaPath + , $missingProperty = it.util.escapeQuotes($propertyKey); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + $errSchemaPath = it.errSchemaPath + '/required'; + }} + {{# def.error:'required' }} + {{ $errSchemaPath = $currErrSchemaPath; }} + {{ it.errorPath = $currentErrorPath; }} + } else { + {{??}} + {{? $breakOnError }} + if ({{# def.noPropertyInData }}) { + {{=$nextValid}} = true; + } else { + {{??}} + if ({{=$useData}} !== undefined + {{? $ownProperties }} + && {{# def.isOwnProperty }} + {{?}} + ) { + {{?}} + {{?}} + + {{= $code }} + } + {{?}} {{ /* $hasDefault */ }} + {{?}} {{ /* def.nonEmptySchema */ }} + + {{# def.ifResultValid }} + {{~}} +{{?}} + +{{? $pPropertyKeys.length }} + {{~ $pPropertyKeys:$pProperty }} + {{ var $sch = $pProperties[$pProperty]; }} + + {{? {{# def.nonEmptySchema:$sch}} }} + {{ + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); + $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + + it.util.escapeFragment($pProperty); + }} + + {{# def.iterateProperties }} + if ({{= it.usePattern($pProperty) }}.test({{=$key}})) { + {{ + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + }} + + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} + + {{? $breakOnError }} if (!{{=$nextValid}}) break; {{?}} + } + {{? $breakOnError }} else {{=$nextValid}} = true; {{?}} + } + + {{# def.ifResultValid }} + {{?}} {{ /* def.nonEmptySchema */ }} + {{~}} +{{?}} + + +{{? $breakOnError }} + {{= $closingBraces }} + if ({{=$errs}} == errors) { +{{?}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/propertyNames.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/propertyNames.jst new file mode 100644 index 0000000..d456cca --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/propertyNames.jst @@ -0,0 +1,52 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + +var {{=$errs}} = errors; + +{{? {{# def.nonEmptySchema:$schema }} }} + {{ + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + }} + + {{ + var $key = 'key' + $lvl + , $idx = 'idx' + $lvl + , $i = 'i' + $lvl + , $invalidName = '\' + ' + $key + ' + \'' + , $dataNxt = $it.dataLevel = it.dataLevel + 1 + , $nextData = 'data' + $dataNxt + , $dataProperties = 'dataProperties' + $lvl + , $ownProperties = it.opts.ownProperties + , $currentBaseId = it.baseId; + }} + + {{? $ownProperties }} + var {{=$dataProperties}} = undefined; + {{?}} + {{# def.iterateProperties }} + var startErrs{{=$lvl}} = errors; + + {{ var $passData = $key; }} + {{# def.setCompositeRule }} + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} + {{# def.resetCompositeRule }} + + if (!{{=$nextValid}}) { + for (var {{=$i}}=startErrs{{=$lvl}}; {{=$i}}= it.opts.loopRequired + , $ownProperties = it.opts.ownProperties; + }} + + {{? $breakOnError }} + var missing{{=$lvl}}; + {{? $loopRequired }} + {{# def.setupLoop }} + var {{=$valid}} = true; + + {{?$isData}}{{# def.check$dataIsArray }}{{?}} + + for (var {{=$i}} = 0; {{=$i}} < {{=$vSchema}}.length; {{=$i}}++) { + {{=$valid}} = {{=$data}}[{{=$vSchema}}[{{=$i}}]] !== undefined + {{? $ownProperties }} + && {{# def.isRequiredOwnProperty }} + {{?}}; + if (!{{=$valid}}) break; + } + + {{? $isData }} } {{?}} + + {{# def.checkError:'required' }} + else { + {{??}} + if ({{# def.checkMissingProperty:$required }}) { + {{# def.errorMissingProperty:'required' }} + } else { + {{?}} + {{??}} + {{? $loopRequired }} + {{# def.setupLoop }} + {{? $isData }} + if ({{=$vSchema}} && !Array.isArray({{=$vSchema}})) { + {{# def.addError:'required' }} + } else if ({{=$vSchema}} !== undefined) { + {{?}} + + for (var {{=$i}} = 0; {{=$i}} < {{=$vSchema}}.length; {{=$i}}++) { + if ({{=$data}}[{{=$vSchema}}[{{=$i}}]] === undefined + {{? $ownProperties }} + || !{{# def.isRequiredOwnProperty }} + {{?}}) { + {{# def.addError:'required' }} + } + } + + {{? $isData }} } {{?}} + {{??}} + {{~ $required:$propertyKey }} + {{# def.allErrorsMissingProperty:'required' }} + {{~}} + {{?}} + {{?}} + + {{ it.errorPath = $currentErrorPath; }} + +{{?? $breakOnError }} + if (true) { +{{?}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/uniqueItems.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/uniqueItems.jst new file mode 100644 index 0000000..e69b830 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/uniqueItems.jst @@ -0,0 +1,62 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + + +{{? ($schema || $isData) && it.opts.uniqueItems !== false }} + {{? $isData }} + var {{=$valid}}; + if ({{=$schemaValue}} === false || {{=$schemaValue}} === undefined) + {{=$valid}} = true; + else if (typeof {{=$schemaValue}} != 'boolean') + {{=$valid}} = false; + else { + {{?}} + + var i = {{=$data}}.length + , {{=$valid}} = true + , j; + if (i > 1) { + {{ + var $itemType = it.schema.items && it.schema.items.type + , $typeIsArray = Array.isArray($itemType); + }} + {{? !$itemType || $itemType == 'object' || $itemType == 'array' || + ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0)) }} + outer: + for (;i--;) { + for (j = i; j--;) { + if (equal({{=$data}}[i], {{=$data}}[j])) { + {{=$valid}} = false; + break outer; + } + } + } + {{??}} + var itemIndices = {}, item; + for (;i--;) { + var item = {{=$data}}[i]; + {{ var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); }} + if ({{= it.util[$method]($itemType, 'item', it.opts.strictNumbers, true) }}) continue; + {{? $typeIsArray}} + if (typeof item == 'string') item = '"' + item; + {{?}} + if (typeof itemIndices[item] == 'number') { + {{=$valid}} = false; + j = itemIndices[item]; + break; + } + itemIndices[item] = i; + } + {{?}} + } + + {{? $isData }} } {{?}} + + if (!{{=$valid}}) { + {{# def.error:'uniqueItems' }} + } {{? $breakOnError }} else { {{?}} +{{??}} + {{? $breakOnError }} if (true) { {{?}} +{{?}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/validate.jst b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/validate.jst new file mode 100644 index 0000000..32087e7 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dot/validate.jst @@ -0,0 +1,276 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.defaults }} +{{# def.coerce }} + +{{ /** + * schema compilation (render) time: + * it = { schema, RULES, _validate, opts } + * it.validate - this template function, + * it is used recursively to generate code for subschemas + * + * runtime: + * "validate" is a variable name to which this function will be assigned + * validateRef etc. are defined in the parent scope in index.js + */ }} + +{{ + var $async = it.schema.$async === true + , $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref') + , $id = it.self._getId(it.schema); +}} + +{{ + if (it.opts.strictKeywords) { + var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords); + if ($unknownKwd) { + var $keywordsMsg = 'unknown keyword: ' + $unknownKwd; + if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg); + else throw new Error($keywordsMsg); + } + } +}} + +{{? it.isTop }} + var validate = {{?$async}}{{it.async = true;}}async {{?}}function(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + {{? $id && (it.opts.sourceCode || it.opts.processCode) }} + {{= '/\*# sourceURL=' + $id + ' */' }} + {{?}} +{{?}} + +{{? typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref) }} + {{ var $keyword = 'false schema'; }} + {{# def.setupKeyword }} + {{? it.schema === false}} + {{? it.isTop}} + {{ $breakOnError = true; }} + {{??}} + var {{=$valid}} = false; + {{?}} + {{# def.error:'false schema' }} + {{??}} + {{? it.isTop}} + {{? $async }} + return data; + {{??}} + validate.errors = null; + return true; + {{?}} + {{??}} + var {{=$valid}} = true; + {{?}} + {{?}} + + {{? it.isTop}} + }; + return validate; + {{?}} + + {{ return out; }} +{{?}} + + +{{? it.isTop }} + {{ + var $top = it.isTop + , $lvl = it.level = 0 + , $dataLvl = it.dataLevel = 0 + , $data = 'data'; + it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema)); + it.baseId = it.baseId || it.rootId; + delete it.isTop; + + it.dataPathArr = [""]; + + if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored in the schema root'; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + }} + + var vErrors = null; {{ /* don't edit, used in replace */ }} + var errors = 0; {{ /* don't edit, used in replace */ }} + if (rootData === undefined) rootData = data; {{ /* don't edit, used in replace */ }} +{{??}} + {{ + var $lvl = it.level + , $dataLvl = it.dataLevel + , $data = 'data' + ($dataLvl || ''); + + if ($id) it.baseId = it.resolve.url(it.baseId, $id); + + if ($async && !it.async) throw new Error('async schema in sync schema'); + }} + + var errs_{{=$lvl}} = errors; +{{?}} + +{{ + var $valid = 'valid' + $lvl + , $breakOnError = !it.opts.allErrors + , $closingBraces1 = '' + , $closingBraces2 = ''; + + var $errorKeyword; + var $typeSchema = it.schema.type + , $typeIsArray = Array.isArray($typeSchema); + + if ($typeSchema && it.opts.nullable && it.schema.nullable === true) { + if ($typeIsArray) { + if ($typeSchema.indexOf('null') == -1) + $typeSchema = $typeSchema.concat('null'); + } else if ($typeSchema != 'null') { + $typeSchema = [$typeSchema, 'null']; + $typeIsArray = true; + } + } + + if ($typeIsArray && $typeSchema.length == 1) { + $typeSchema = $typeSchema[0]; + $typeIsArray = false; + } +}} + +{{## def.checkType: + {{ + var $schemaPath = it.schemaPath + '.type' + , $errSchemaPath = it.errSchemaPath + '/type' + , $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; + }} + + if ({{= it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true) }}) { +#}} + +{{? it.schema.$ref && $refKeywords }} + {{? it.opts.extendRefs == 'fail' }} + {{ throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); }} + {{?? it.opts.extendRefs !== true }} + {{ + $refKeywords = false; + it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); + }} + {{?}} +{{?}} + +{{? it.schema.$comment && it.opts.$comment }} + {{= it.RULES.all.$comment.code(it, '$comment') }} +{{?}} + +{{? $typeSchema }} + {{? it.opts.coerceTypes }} + {{ var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); }} + {{?}} + + {{ var $rulesGroup = it.RULES.types[$typeSchema]; }} + {{? $coerceToTypes || $typeIsArray || $rulesGroup === true || + ($rulesGroup && !$shouldUseGroup($rulesGroup)) }} + {{ + var $schemaPath = it.schemaPath + '.type' + , $errSchemaPath = it.errSchemaPath + '/type'; + }} + {{# def.checkType }} + {{? $coerceToTypes }} + {{# def.coerceType }} + {{??}} + {{# def.error:'type' }} + {{?}} + } + {{?}} +{{?}} + + +{{? it.schema.$ref && !$refKeywords }} + {{= it.RULES.all.$ref.code(it, '$ref') }} + {{? $breakOnError }} + } + if (errors === {{?$top}}0{{??}}errs_{{=$lvl}}{{?}}) { + {{ $closingBraces2 += '}'; }} + {{?}} +{{??}} + {{~ it.RULES:$rulesGroup }} + {{? $shouldUseGroup($rulesGroup) }} + {{? $rulesGroup.type }} + if ({{= it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers) }}) { + {{?}} + {{? it.opts.useDefaults }} + {{? $rulesGroup.type == 'object' && it.schema.properties }} + {{# def.defaultProperties }} + {{?? $rulesGroup.type == 'array' && Array.isArray(it.schema.items) }} + {{# def.defaultItems }} + {{?}} + {{?}} + {{~ $rulesGroup.rules:$rule }} + {{? $shouldUseRule($rule) }} + {{ var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); }} + {{? $code }} + {{= $code }} + {{? $breakOnError }} + {{ $closingBraces1 += '}'; }} + {{?}} + {{?}} + {{?}} + {{~}} + {{? $breakOnError }} + {{= $closingBraces1 }} + {{ $closingBraces1 = ''; }} + {{?}} + {{? $rulesGroup.type }} + } + {{? $typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes }} + else { + {{ + var $schemaPath = it.schemaPath + '.type' + , $errSchemaPath = it.errSchemaPath + '/type'; + }} + {{# def.error:'type' }} + } + {{?}} + {{?}} + + {{? $breakOnError }} + if (errors === {{?$top}}0{{??}}errs_{{=$lvl}}{{?}}) { + {{ $closingBraces2 += '}'; }} + {{?}} + {{?}} + {{~}} +{{?}} + +{{? $breakOnError }} {{= $closingBraces2 }} {{?}} + +{{? $top }} + {{? $async }} + if (errors === 0) return data; {{ /* don't edit, used in replace */ }} + else throw new ValidationError(vErrors); {{ /* don't edit, used in replace */ }} + {{??}} + validate.errors = vErrors; {{ /* don't edit, used in replace */ }} + return errors === 0; {{ /* don't edit, used in replace */ }} + {{?}} + }; + + return validate; +{{??}} + var {{=$valid}} = errors === errs_{{=$lvl}}; +{{?}} + +{{ + function $shouldUseGroup($rulesGroup) { + var rules = $rulesGroup.rules; + for (var i=0; i < rules.length; i++) + if ($shouldUseRule(rules[i])) + return true; + } + + function $shouldUseRule($rule) { + return it.schema[$rule.keyword] !== undefined || + ($rule.implements && $ruleImplementsSomeKeyword($rule)); + } + + function $ruleImplementsSomeKeyword($rule) { + var impl = $rule.implements; + for (var i=0; i < impl.length; i++) + if (it.schema[impl[i]] !== undefined) + return true; + } +}} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/README.md b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/README.md new file mode 100644 index 0000000..4d99484 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/README.md @@ -0,0 +1,3 @@ +These files are compiled dot templates from dot folder. + +Do NOT edit them directly, edit the templates and run `npm run build` from main ajv folder. diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/_limit.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/_limit.js new file mode 100644 index 0000000..05a1979 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/_limit.js @@ -0,0 +1,163 @@ +'use strict'; +module.exports = function generate__limit(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $isMax = $keyword == 'maximum', + $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum', + $schemaExcl = it.schema[$exclusiveKeyword], + $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, + $op = $isMax ? '<' : '>', + $notOp = $isMax ? '>' : '<', + $errorKeyword = undefined; + if (!($isData || typeof $schema == 'number' || $schema === undefined)) { + throw new Error($keyword + ' must be number'); + } + if (!($isDataExcl || $schemaExcl === undefined || typeof $schemaExcl == 'number' || typeof $schemaExcl == 'boolean')) { + throw new Error($exclusiveKeyword + ' must be number or boolean'); + } + if ($isDataExcl) { + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), + $exclusive = 'exclusive' + $lvl, + $exclType = 'exclType' + $lvl, + $exclIsNumber = 'exclIsNumber' + $lvl, + $opExpr = 'op' + $lvl, + $opStr = '\' + ' + $opExpr + ' + \''; + out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; + $schemaValueExcl = 'schemaExcl' + $lvl; + out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { '; + var $errorKeyword = $exclusiveKeyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; '; + if ($schema === undefined) { + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaValueExcl; + $isData = $isDataExcl; + } + } else { + var $exclIsNumber = typeof $schemaExcl == 'number', + $opStr = $op; + if ($exclIsNumber && $isData) { + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { '; + } else { + if ($exclIsNumber && $schema === undefined) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaExcl; + $notOp += '='; + } else { + if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema); + if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $notOp += '='; + } else { + $exclusive = false; + $opStr += '='; + } + } + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { '; + } + } + $errorKeyword = $errorKeyword || $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be ' + ($opStr) + ' '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schemaValue) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/_limitItems.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/_limitItems.js new file mode 100644 index 0000000..e092a55 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/_limitItems.js @@ -0,0 +1,80 @@ +'use strict'; +module.exports = function generate__limitItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxItems' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxItems') { + out += 'more'; + } else { + out += 'fewer'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/_limitLength.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/_limitLength.js new file mode 100644 index 0000000..ecbd3fe --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/_limitLength.js @@ -0,0 +1,85 @@ +'use strict'; +module.exports = function generate__limitLength(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxLength' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + if (it.opts.unicode === false) { + out += ' ' + ($data) + '.length '; + } else { + out += ' ucs2length(' + ($data) + ') '; + } + out += ' ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be '; + if ($keyword == 'maxLength') { + out += 'longer'; + } else { + out += 'shorter'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' characters\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/_limitProperties.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/_limitProperties.js new file mode 100644 index 0000000..d232755 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/_limitProperties.js @@ -0,0 +1,80 @@ +'use strict'; +module.exports = function generate__limitProperties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + var $op = $keyword == 'maxProperties' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxProperties') { + out += 'more'; + } else { + out += 'fewer'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' properties\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/allOf.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/allOf.js new file mode 100644 index 0000000..fb8c2e4 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/allOf.js @@ -0,0 +1,42 @@ +'use strict'; +module.exports = function generate_allOf(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $allSchemasEmpty = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $allSchemasEmpty = false; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if ($breakOnError) { + if ($allSchemasEmpty) { + out += ' if (true) { '; + } else { + out += ' ' + ($closingBraces.slice(0, -1)) + ' '; + } + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/anyOf.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/anyOf.js new file mode 100644 index 0000000..0600a9d --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/anyOf.js @@ -0,0 +1,73 @@ +'use strict'; +module.exports = function generate_anyOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $noEmptySchema = $schema.every(function($sch) { + return (it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)); + }); + if ($noEmptySchema) { + var $currentBaseId = $it.baseId; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { '; + $closingBraces += '}'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should match some schema in anyOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/comment.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/comment.js new file mode 100644 index 0000000..dd66bb8 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/comment.js @@ -0,0 +1,14 @@ +'use strict'; +module.exports = function generate_comment(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $comment = it.util.toQuotedString($schema); + if (it.opts.$comment === true) { + out += ' console.log(' + ($comment) + ');'; + } else if (typeof it.opts.$comment == 'function') { + out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);'; + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/const.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/const.js new file mode 100644 index 0000000..15b7c61 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/const.js @@ -0,0 +1,56 @@ +'use strict'; +module.exports = function generate_const(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!$isData) { + out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to constant\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/contains.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/contains.js new file mode 100644 index 0000000..7d76300 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/contains.js @@ -0,0 +1,81 @@ +'use strict'; +module.exports = function generate_contains(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId, + $nonEmptySchema = (it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all)); + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($nonEmptySchema) { + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' if (' + ($nextValid) + ') break; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {'; + } else { + out += ' if (' + ($data) + '.length == 0) {'; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should contain a valid item\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + if ($nonEmptySchema) { + out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + } + if (it.opts.allErrors) { + out += ' } '; + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/custom.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/custom.js new file mode 100644 index 0000000..f3e641e --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/custom.js @@ -0,0 +1,228 @@ +'use strict'; +module.exports = function generate_custom(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $rule = this, + $definition = 'definition' + $lvl, + $rDef = $rule.definition, + $closingBraces = ''; + var $compile, $inline, $macro, $ruleValidate, $validateCode; + if ($isData && $rDef.$data) { + $validateCode = 'keywordValidate' + $lvl; + var $validateSchema = $rDef.validateSchema; + out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;'; + } else { + $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); + if (!$ruleValidate) return; + $schemaValue = 'validate.schema' + $schemaPath; + $validateCode = $ruleValidate.code; + $compile = $rDef.compile; + $inline = $rDef.inline; + $macro = $rDef.macro; + } + var $ruleErrs = $validateCode + '.errors', + $i = 'i' + $lvl, + $ruleErr = 'ruleErr' + $lvl, + $asyncKeyword = $rDef.async; + if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema'); + if (!($inline || $macro)) { + out += '' + ($ruleErrs) + ' = null;'; + } + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($isData && $rDef.$data) { + $closingBraces += '}'; + out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { '; + if ($validateSchema) { + $closingBraces += '}'; + out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { '; + } + } + if ($inline) { + if ($rDef.statements) { + out += ' ' + ($ruleValidate.validate) + ' '; + } else { + out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; '; + } + } else if ($macro) { + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $ruleValidate.validate; + $it.schemaPath = ''; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($code); + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + out += ' ' + ($validateCode) + '.call( '; + if (it.opts.passContext) { + out += 'this'; + } else { + out += 'self'; + } + if ($compile || $rDef.schema === false) { + out += ' , ' + ($data) + ' '; + } else { + out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' '; + } + out += ' , (dataPath || \'\')'; + if (it.errorPath != '""') { + out += ' + ' + (it.errorPath); + } + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) '; + var def_callRuleValidate = out; + out = $$outStack.pop(); + if ($rDef.errors === false) { + out += ' ' + ($valid) + ' = '; + if ($asyncKeyword) { + out += 'await '; + } + out += '' + (def_callRuleValidate) + '; '; + } else { + if ($asyncKeyword) { + $ruleErrs = 'customErrors' + $lvl; + out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } '; + } else { + out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; '; + } + } + } + if ($rDef.modifying) { + out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];'; + } + out += '' + ($closingBraces); + if ($rDef.valid) { + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + out += ' if ( '; + if ($rDef.valid === undefined) { + out += ' !'; + if ($macro) { + out += '' + ($nextValid); + } else { + out += '' + ($valid); + } + } else { + out += ' ' + (!$rDef.valid) + ' '; + } + out += ') { '; + $errorKeyword = $rule.keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + var def_customError = out; + out = $$outStack.pop(); + if ($inline) { + if ($rDef.errors) { + if ($rDef.errors != 'full') { + out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + ' 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; + } + out += ') { '; + $it.schema = $sch; + $it.schemaPath = $schemaPath + it.util.getProperty($property); + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property); + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/enum.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/enum.js new file mode 100644 index 0000000..90580b9 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/enum.js @@ -0,0 +1,66 @@ +'use strict'; +module.exports = function generate_enum(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $i = 'i' + $lvl, + $vSchema = 'schema' + $lvl; + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ';'; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }'; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to one of the allowed values\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/format.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/format.js new file mode 100644 index 0000000..cd9a569 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/format.js @@ -0,0 +1,150 @@ +'use strict'; +module.exports = function generate_format(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + if (it.opts.format === false) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $unknownFormats = it.opts.unknownFormats, + $allowUnknown = Array.isArray($unknownFormats); + if ($isData) { + var $format = 'format' + $lvl, + $isObject = 'isObject' + $lvl, + $formatType = 'formatType' + $lvl; + out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { '; + if (it.async) { + out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; '; + } + out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' ('; + if ($unknownFormats != 'ignore') { + out += ' (' + ($schemaValue) + ' && !' + ($format) + ' '; + if ($allowUnknown) { + out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 '; + } + out += ') || '; + } + out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? '; + if (it.async) { + out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) '; + } else { + out += ' ' + ($format) + '(' + ($data) + ') '; + } + out += ' : ' + ($format) + '.test(' + ($data) + '))))) {'; + } else { + var $format = it.formats[$schema]; + if (!$format) { + if ($unknownFormats == 'ignore') { + it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } else { + throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); + } + } + var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate; + var $formatType = $isObject && $format.type || 'string'; + if ($isObject) { + var $async = $format.async === true; + $format = $format.validate; + } + if ($formatType != $ruleType) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } + if ($async) { + if (!it.async) throw new Error('async format in sync schema'); + var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; + out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { '; + } else { + out += ' if (! '; + var $formatRef = 'formats' + it.util.getProperty($schema); + if ($isObject) $formatRef += '.validate'; + if (typeof $format == 'function') { + out += ' ' + ($formatRef) + '(' + ($data) + ') '; + } else { + out += ' ' + ($formatRef) + '.test(' + ($data) + ') '; + } + out += ') { '; + } + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match format "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/if.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/if.js new file mode 100644 index 0000000..94d27ad --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/if.js @@ -0,0 +1,103 @@ +'use strict'; +module.exports = function generate_if(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + var $thenSch = it.schema['then'], + $elseSch = it.schema['else'], + $thenPresent = $thenSch !== undefined && (it.opts.strictKeywords ? (typeof $thenSch == 'object' && Object.keys($thenSch).length > 0) || $thenSch === false : it.util.schemaHasRules($thenSch, it.RULES.all)), + $elsePresent = $elseSch !== undefined && (it.opts.strictKeywords ? (typeof $elseSch == 'object' && Object.keys($elseSch).length > 0) || $elseSch === false : it.util.schemaHasRules($elseSch, it.RULES.all)), + $currentBaseId = $it.baseId; + if ($thenPresent || $elsePresent) { + var $ifClause; + $it.createErrors = false; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + $it.createErrors = true; + out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + if ($thenPresent) { + out += ' if (' + ($nextValid) + ') { '; + $it.schema = it.schema['then']; + $it.schemaPath = it.schemaPath + '.then'; + $it.errSchemaPath = it.errSchemaPath + '/then'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; + if ($thenPresent && $elsePresent) { + $ifClause = 'ifClause' + $lvl; + out += ' var ' + ($ifClause) + ' = \'then\'; '; + } else { + $ifClause = '\'then\''; + } + out += ' } '; + if ($elsePresent) { + out += ' else { '; + } + } else { + out += ' if (!' + ($nextValid) + ') { '; + } + if ($elsePresent) { + $it.schema = it.schema['else']; + $it.schemaPath = it.schemaPath + '.else'; + $it.errSchemaPath = it.errSchemaPath + '/else'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; + if ($thenPresent && $elsePresent) { + $ifClause = 'ifClause' + $lvl; + out += ' var ' + ($ifClause) + ' = \'else\'; '; + } else { + $ifClause = '\'else\''; + } + out += ' } '; + } + out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/index.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/index.js new file mode 100644 index 0000000..2fb1b00 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/index.js @@ -0,0 +1,33 @@ +'use strict'; + +//all requires must be explicit because browserify won't work with dynamic requires +module.exports = { + '$ref': require('./ref'), + allOf: require('./allOf'), + anyOf: require('./anyOf'), + '$comment': require('./comment'), + const: require('./const'), + contains: require('./contains'), + dependencies: require('./dependencies'), + 'enum': require('./enum'), + format: require('./format'), + 'if': require('./if'), + items: require('./items'), + maximum: require('./_limit'), + minimum: require('./_limit'), + maxItems: require('./_limitItems'), + minItems: require('./_limitItems'), + maxLength: require('./_limitLength'), + minLength: require('./_limitLength'), + maxProperties: require('./_limitProperties'), + minProperties: require('./_limitProperties'), + multipleOf: require('./multipleOf'), + not: require('./not'), + oneOf: require('./oneOf'), + pattern: require('./pattern'), + properties: require('./properties'), + propertyNames: require('./propertyNames'), + required: require('./required'), + uniqueItems: require('./uniqueItems'), + validate: require('./validate') +}; diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/items.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/items.js new file mode 100644 index 0000000..bee5d67 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/items.js @@ -0,0 +1,140 @@ +'use strict'; +module.exports = function generate_items(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId; + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if (Array.isArray($schema)) { + var $additionalItems = it.schema.additionalItems; + if ($additionalItems === false) { + out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { '; + var $passData = $data + '[' + $i + ']'; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); + $it.dataPathArr[$dataNxt] = $i; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if (typeof $additionalItems == 'object' && (it.opts.strictKeywords ? (typeof $additionalItems == 'object' && Object.keys($additionalItems).length > 0) || $additionalItems === false : it.util.schemaHasRules($additionalItems, it.RULES.all))) { + $it.schema = $additionalItems; + $it.schemaPath = it.schemaPath + '.additionalItems'; + $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } else if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' }'; + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/multipleOf.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/multipleOf.js new file mode 100644 index 0000000..9d6401b --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/multipleOf.js @@ -0,0 +1,80 @@ +'use strict'; +module.exports = function generate_multipleOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + out += 'var division' + ($lvl) + ';if ('; + if ($isData) { + out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || '; + } + out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', '; + if (it.opts.multipleOfPrecision) { + out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' '; + } else { + out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') '; + } + out += ' ) '; + if ($isData) { + out += ' ) '; + } + out += ' ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be multiple of '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schemaValue) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/not.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/not.js new file mode 100644 index 0000000..f50c937 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/not.js @@ -0,0 +1,84 @@ +'use strict'; +module.exports = function generate_not(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.createErrors = false; + var $allErrorsOption; + if ($it.opts.allErrors) { + $allErrorsOption = $it.opts.allErrors; + $it.opts.allErrors = false; + } + out += ' ' + (it.validate($it)) + ' '; + $it.createErrors = true; + if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (' + ($nextValid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + out += ' var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if ($breakOnError) { + out += ' if (false) { '; + } + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/oneOf.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/oneOf.js new file mode 100644 index 0000000..dfe2fd5 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/oneOf.js @@ -0,0 +1,73 @@ +'use strict'; +module.exports = function generate_oneOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $prevValid = 'prevValid' + $lvl, + $passingSchemas = 'passingSchemas' + $lvl; + out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } else { + out += ' var ' + ($nextValid) + ' = true; '; + } + if ($i) { + out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { '; + $closingBraces += '}'; + } + out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match exactly one schema in oneOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }'; + if (it.opts.allErrors) { + out += ' } '; + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/pattern.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/pattern.js new file mode 100644 index 0000000..1d74d6b --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/pattern.js @@ -0,0 +1,75 @@ +'use strict'; +module.exports = function generate_pattern(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema); + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match pattern "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/properties.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/properties.js new file mode 100644 index 0000000..bc5ee55 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/properties.js @@ -0,0 +1,335 @@ +'use strict'; +module.exports = function generate_properties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl; + var $schemaKeys = Object.keys($schema || {}).filter(notProto), + $pProperties = it.schema.patternProperties || {}, + $pPropertyKeys = Object.keys($pProperties).filter(notProto), + $aProperties = it.schema.additionalProperties, + $someProperties = $schemaKeys.length || $pPropertyKeys.length, + $noAdditional = $aProperties === false, + $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length, + $removeAdditional = it.opts.removeAdditional, + $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + var $required = it.schema.required; + if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) { + var $requiredHash = it.util.toHash($required); + } + + function notProto(p) { + return p !== '__proto__'; + } + out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;'; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined;'; + } + if ($checkAdditional) { + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + if ($someProperties) { + out += ' var isAdditional' + ($lvl) + ' = !(false '; + if ($schemaKeys.length) { + if ($schemaKeys.length > 8) { + out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') '; + } else { + var arr1 = $schemaKeys; + if (arr1) { + var $propertyKey, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $propertyKey = arr1[i1 += 1]; + out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' '; + } + } + } + } + if ($pPropertyKeys.length) { + var arr2 = $pPropertyKeys; + if (arr2) { + var $pProperty, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $pProperty = arr2[$i += 1]; + out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') '; + } + } + } + out += ' ); if (isAdditional' + ($lvl) + ') { '; + } + if ($removeAdditional == 'all') { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + var $currentErrorPath = it.errorPath; + var $additionalProperty = '\' + ' + $key + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + } + if ($noAdditional) { + if ($removeAdditional) { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + out += ' ' + ($nextValid) + ' = false; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalProperties'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is an invalid additional property'; + } else { + out += 'should NOT have additional properties'; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + out += ' break; '; + } + } + } else if ($additionalIsSchema) { + if ($removeAdditional == 'failing') { + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + } else { + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + } + } + it.errorPath = $currentErrorPath; + } + if ($someProperties) { + out += ' } '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + var $useDefaults = it.opts.useDefaults && !it.compositeRule; + if ($schemaKeys.length) { + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + var $prop = it.util.getProperty($propertyKey), + $passData = $data + $prop, + $hasDefault = $useDefaults && $sch.default !== undefined; + $it.schema = $sch; + $it.schemaPath = $schemaPath + $prop; + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); + $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); + $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + $code = it.util.varReplace($code, $nextData, $passData); + var $useData = $passData; + } else { + var $useData = $nextData; + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; '; + } + if ($hasDefault) { + out += ' ' + ($code) + ' '; + } else { + if ($requiredHash && $requiredHash[$propertyKey]) { + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { ' + ($nextValid) + ' = false; '; + var $currentErrorPath = it.errorPath, + $currErrSchemaPath = $errSchemaPath, + $missingProperty = it.util.escapeQuotes($propertyKey); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + $errSchemaPath = it.errSchemaPath + '/required'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + it.errorPath = $currentErrorPath; + out += ' } else { '; + } else { + if ($breakOnError) { + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { ' + ($nextValid) + ' = true; } else { '; + } else { + out += ' if (' + ($useData) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ' ) { '; + } + } + out += ' ' + ($code) + ' } '; + } + } + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if ($pPropertyKeys.length) { + var arr4 = $pPropertyKeys; + if (arr4) { + var $pProperty, i4 = -1, + l4 = arr4.length - 1; + while (i4 < l4) { + $pProperty = arr4[i4 += 1]; + var $sch = $pProperties[$pProperty]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); + $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty); + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else ' + ($nextValid) + ' = true; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/propertyNames.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/propertyNames.js new file mode 100644 index 0000000..2a54a08 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/propertyNames.js @@ -0,0 +1,81 @@ +'use strict'; +module.exports = function generate_propertyNames(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + out += 'var ' + ($errs) + ' = errors;'; + if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $i = 'i' + $lvl, + $invalidName = '\' + ' + $key + ' + \'', + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined; '; + } + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + out += ' var startErrs' + ($lvl) + ' = errors; '; + var $passData = $key; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + ' 0) || $propertySch === false : it.util.schemaHasRules($propertySch, it.RULES.all)))) { + $required[$required.length] = $property; + } + } + } + } else { + var $required = $schema; + } + } + if ($isData || $required.length) { + var $currentErrorPath = it.errorPath, + $loopRequired = $isData || $required.length >= it.opts.loopRequired, + $ownProperties = it.opts.ownProperties; + if ($breakOnError) { + out += ' var missing' + ($lvl) + '; '; + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + out += ' var ' + ($valid) + ' = true; '; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; + } + out += '; if (!' + ($valid) + ') break; } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } else { + out += ' if ( '; + var arr2 = $required; + if (arr2) { + var $propertyKey, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $propertyKey = arr2[$i += 1]; + if ($i) { + out += ' || '; + } + var $prop = it.util.getProperty($propertyKey), + $useData = $data + $prop; + out += ' ( ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; + } + } + out += ') { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } + } else { + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + if ($isData) { + out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { '; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } '; + if ($isData) { + out += ' } '; + } + } else { + var arr3 = $required; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $prop = it.util.getProperty($propertyKey), + $missingProperty = it.util.escapeQuotes($propertyKey), + $useData = $data + $prop; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } + } + } + } + it.errorPath = $currentErrorPath; + } else if ($breakOnError) { + out += ' if (true) {'; + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/uniqueItems.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/uniqueItems.js new file mode 100644 index 0000000..0736a0e --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/uniqueItems.js @@ -0,0 +1,86 @@ +'use strict'; +module.exports = function generate_uniqueItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (($schema || $isData) && it.opts.uniqueItems !== false) { + if ($isData) { + out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { '; + } + out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { '; + var $itemType = it.schema.items && it.schema.items.type, + $typeIsArray = Array.isArray($itemType); + if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) { + out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } '; + } else { + out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; '; + var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); + out += ' if (' + (it.util[$method]($itemType, 'item', it.opts.strictNumbers, true)) + ') continue; '; + if ($typeIsArray) { + out += ' if (typeof item == \'string\') item = \'"\' + item; '; + } + out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } '; + } + out += ' } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/validate.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/validate.js new file mode 100644 index 0000000..f295824 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/dotjs/validate.js @@ -0,0 +1,482 @@ +'use strict'; +module.exports = function generate_validate(it, $keyword, $ruleType) { + var out = ''; + var $async = it.schema.$async === true, + $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'), + $id = it.self._getId(it.schema); + if (it.opts.strictKeywords) { + var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords); + if ($unknownKwd) { + var $keywordsMsg = 'unknown keyword: ' + $unknownKwd; + if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg); + else throw new Error($keywordsMsg); + } + } + if (it.isTop) { + out += ' var validate = '; + if ($async) { + it.async = true; + out += 'async '; + } + out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; '; + if ($id && (it.opts.sourceCode || it.opts.processCode)) { + out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' '; + } + } + if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) { + var $keyword = 'false schema'; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + if (it.schema === false) { + if (it.isTop) { + $breakOnError = true; + } else { + out += ' var ' + ($valid) + ' = false; '; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'boolean schema is false\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } else { + if (it.isTop) { + if ($async) { + out += ' return data; '; + } else { + out += ' validate.errors = null; return true; '; + } + } else { + out += ' var ' + ($valid) + ' = true; '; + } + } + if (it.isTop) { + out += ' }; return validate; '; + } + return out; + } + if (it.isTop) { + var $top = it.isTop, + $lvl = it.level = 0, + $dataLvl = it.dataLevel = 0, + $data = 'data'; + it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema)); + it.baseId = it.baseId || it.rootId; + delete it.isTop; + it.dataPathArr = [""]; + if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored in the schema root'; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + out += ' var vErrors = null; '; + out += ' var errors = 0; '; + out += ' if (rootData === undefined) rootData = data; '; + } else { + var $lvl = it.level, + $dataLvl = it.dataLevel, + $data = 'data' + ($dataLvl || ''); + if ($id) it.baseId = it.resolve.url(it.baseId, $id); + if ($async && !it.async) throw new Error('async schema in sync schema'); + out += ' var errs_' + ($lvl) + ' = errors;'; + } + var $valid = 'valid' + $lvl, + $breakOnError = !it.opts.allErrors, + $closingBraces1 = '', + $closingBraces2 = ''; + var $errorKeyword; + var $typeSchema = it.schema.type, + $typeIsArray = Array.isArray($typeSchema); + if ($typeSchema && it.opts.nullable && it.schema.nullable === true) { + if ($typeIsArray) { + if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null'); + } else if ($typeSchema != 'null') { + $typeSchema = [$typeSchema, 'null']; + $typeIsArray = true; + } + } + if ($typeIsArray && $typeSchema.length == 1) { + $typeSchema = $typeSchema[0]; + $typeIsArray = false; + } + if (it.schema.$ref && $refKeywords) { + if (it.opts.extendRefs == 'fail') { + throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); + } else if (it.opts.extendRefs !== true) { + $refKeywords = false; + it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); + } + } + if (it.schema.$comment && it.opts.$comment) { + out += ' ' + (it.RULES.all.$comment.code(it, '$comment')); + } + if ($typeSchema) { + if (it.opts.coerceTypes) { + var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); + } + var $rulesGroup = it.RULES.types[$typeSchema]; + if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) { + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type', + $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; + out += ' if (' + (it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true)) + ') { '; + if ($coerceToTypes) { + var $dataType = 'dataType' + $lvl, + $coerced = 'coerced' + $lvl; + out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; var ' + ($coerced) + ' = undefined; '; + if (it.opts.coerceTypes == 'array') { + out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ') && ' + ($data) + '.length == 1) { ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; if (' + (it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)) + ') ' + ($coerced) + ' = ' + ($data) + '; } '; + } + out += ' if (' + ($coerced) + ' !== undefined) ; '; + var arr1 = $coerceToTypes; + if (arr1) { + var $type, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $type = arr1[$i += 1]; + if ($type == 'string') { + out += ' else if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; '; + } else if ($type == 'number' || $type == 'integer') { + out += ' else if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' '; + if ($type == 'integer') { + out += ' && !(' + ($data) + ' % 1)'; + } + out += ')) ' + ($coerced) + ' = +' + ($data) + '; '; + } else if ($type == 'boolean') { + out += ' else if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; '; + } else if ($type == 'null') { + out += ' else if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; '; + } else if (it.opts.coerceTypes == 'array' && $type == 'array') { + out += ' else if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; '; + } + } + } + out += ' else { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } if (' + ($coerced) + ' !== undefined) { '; + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' ' + ($data) + ' = ' + ($coerced) + '; '; + if (!$dataLvl) { + out += 'if (' + ($parentData) + ' !== undefined)'; + } + out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } '; + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } + out += ' } '; + } + } + if (it.schema.$ref && !$refKeywords) { + out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' '; + if ($breakOnError) { + out += ' } if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } + } else { + var arr2 = it.RULES; + if (arr2) { + var $rulesGroup, i2 = -1, + l2 = arr2.length - 1; + while (i2 < l2) { + $rulesGroup = arr2[i2 += 1]; + if ($shouldUseGroup($rulesGroup)) { + if ($rulesGroup.type) { + out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers)) + ') { '; + } + if (it.opts.useDefaults) { + if ($rulesGroup.type == 'object' && it.schema.properties) { + var $schema = it.schema.properties, + $schemaKeys = Object.keys($schema); + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if ($sch.default !== undefined) { + var $passData = $data + it.util.getProperty($propertyKey); + if (it.compositeRule) { + if (it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored for: ' + $passData; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + } else { + out += ' if (' + ($passData) + ' === undefined '; + if (it.opts.useDefaults == 'empty') { + out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; + } + out += ' ) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } + } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) { + var arr4 = it.schema.items; + if (arr4) { + var $sch, $i = -1, + l4 = arr4.length - 1; + while ($i < l4) { + $sch = arr4[$i += 1]; + if ($sch.default !== undefined) { + var $passData = $data + '[' + $i + ']'; + if (it.compositeRule) { + if (it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored for: ' + $passData; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + } else { + out += ' if (' + ($passData) + ' === undefined '; + if (it.opts.useDefaults == 'empty') { + out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; + } + out += ' ) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } + } + } + var arr5 = $rulesGroup.rules; + if (arr5) { + var $rule, i5 = -1, + l5 = arr5.length - 1; + while (i5 < l5) { + $rule = arr5[i5 += 1]; + if ($shouldUseRule($rule)) { + var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); + if ($code) { + out += ' ' + ($code) + ' '; + if ($breakOnError) { + $closingBraces1 += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces1) + ' '; + $closingBraces1 = ''; + } + if ($rulesGroup.type) { + out += ' } '; + if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) { + out += ' else { '; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + } + } + if ($breakOnError) { + out += ' if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces2) + ' '; + } + if ($top) { + if ($async) { + out += ' if (errors === 0) return data; '; + out += ' else throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; '; + out += ' return errors === 0; '; + } + out += ' }; return validate;'; + } else { + out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';'; + } + + function $shouldUseGroup($rulesGroup) { + var rules = $rulesGroup.rules; + for (var i = 0; i < rules.length; i++) + if ($shouldUseRule(rules[i])) return true; + } + + function $shouldUseRule($rule) { + return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule)); + } + + function $ruleImplementsSomeKeyword($rule) { + var impl = $rule.implements; + for (var i = 0; i < impl.length; i++) + if (it.schema[impl[i]] !== undefined) return true; + } + return out; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/lib/keyword.js b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/keyword.js new file mode 100644 index 0000000..06da9a2 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/lib/keyword.js @@ -0,0 +1,146 @@ +'use strict'; + +var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i; +var customRuleCode = require('./dotjs/custom'); +var definitionSchema = require('./definition_schema'); + +module.exports = { + add: addKeyword, + get: getKeyword, + remove: removeKeyword, + validate: validateKeyword +}; + + +/** + * Define custom keyword + * @this Ajv + * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords). + * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. + * @return {Ajv} this for method chaining + */ +function addKeyword(keyword, definition) { + /* jshint validthis: true */ + /* eslint no-shadow: 0 */ + var RULES = this.RULES; + if (RULES.keywords[keyword]) + throw new Error('Keyword ' + keyword + ' is already defined'); + + if (!IDENTIFIER.test(keyword)) + throw new Error('Keyword ' + keyword + ' is not a valid identifier'); + + if (definition) { + this.validateKeyword(definition, true); + + var dataType = definition.type; + if (Array.isArray(dataType)) { + for (var i=0; i ../ajv-dist/bower.json + cd ../ajv-dist + + if [[ `git status --porcelain` ]]; then + echo "Changes detected. Updating master branch..." + git add -A + git commit -m "updated by travis build #$TRAVIS_BUILD_NUMBER" + git push --quiet origin master > /dev/null 2>&1 + fi + + echo "Publishing tag..." + + git tag $TRAVIS_TAG + git push --tags > /dev/null 2>&1 + + echo "Done" +fi diff --git a/node_modules/terser-webpack-plugin/node_modules/ajv/scripts/travis-gh-pages b/node_modules/terser-webpack-plugin/node_modules/ajv/scripts/travis-gh-pages new file mode 100644 index 0000000..b3d4f3d --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/ajv/scripts/travis-gh-pages @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +set -e + +if [[ "$TRAVIS_BRANCH" == "master" && "$TRAVIS_PULL_REQUEST" == "false" && $TRAVIS_JOB_NUMBER =~ ".3" ]]; then + git diff --name-only $TRAVIS_COMMIT_RANGE | grep -qE '\.md$|^LICENSE$|travis-gh-pages$' && { + rm -rf ../gh-pages + git clone -b gh-pages --single-branch https://${GITHUB_TOKEN}@github.com/ajv-validator/ajv.git ../gh-pages + mkdir -p ../gh-pages/_source + cp *.md ../gh-pages/_source + cp LICENSE ../gh-pages/_source + currentDir=$(pwd) + cd ../gh-pages + $currentDir/node_modules/.bin/gh-pages-generator + # remove logo from README + sed -i -E "s/]+ajv_logo[^>]+>//" index.md + git config user.email "$GIT_USER_EMAIL" + git config user.name "$GIT_USER_NAME" + git add . + git commit -am "updated by travis build #$TRAVIS_BUILD_NUMBER" + git push --quiet origin gh-pages > /dev/null 2>&1 + } +fi diff --git a/node_modules/terser-webpack-plugin/node_modules/json-schema-traverse/.eslintrc.yml b/node_modules/terser-webpack-plugin/node_modules/json-schema-traverse/.eslintrc.yml new file mode 100644 index 0000000..ab1762d --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/json-schema-traverse/.eslintrc.yml @@ -0,0 +1,27 @@ +extends: eslint:recommended +env: + node: true + browser: true +rules: + block-scoped-var: 2 + complexity: [2, 13] + curly: [2, multi-or-nest, consistent] + dot-location: [2, property] + dot-notation: 2 + indent: [2, 2, SwitchCase: 1] + linebreak-style: [2, unix] + new-cap: 2 + no-console: [2, allow: [warn, error]] + no-else-return: 2 + no-eq-null: 2 + no-fallthrough: 2 + no-invalid-this: 2 + no-return-assign: 2 + no-shadow: 1 + no-trailing-spaces: 2 + no-use-before-define: [2, nofunc] + quotes: [2, single, avoid-escape] + semi: [2, always] + strict: [2, global] + valid-jsdoc: [2, requireReturn: false] + no-control-regex: 0 diff --git a/node_modules/terser-webpack-plugin/node_modules/json-schema-traverse/.travis.yml b/node_modules/terser-webpack-plugin/node_modules/json-schema-traverse/.travis.yml new file mode 100644 index 0000000..7ddce74 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/json-schema-traverse/.travis.yml @@ -0,0 +1,8 @@ +language: node_js +node_js: + - "4" + - "6" + - "7" + - "8" +after_script: + - coveralls < coverage/lcov.info diff --git a/node_modules/terser-webpack-plugin/node_modules/json-schema-traverse/LICENSE b/node_modules/terser-webpack-plugin/node_modules/json-schema-traverse/LICENSE new file mode 100644 index 0000000..7f15435 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/json-schema-traverse/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Evgeny Poberezkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/terser-webpack-plugin/node_modules/json-schema-traverse/README.md b/node_modules/terser-webpack-plugin/node_modules/json-schema-traverse/README.md new file mode 100644 index 0000000..d5ccaf4 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/json-schema-traverse/README.md @@ -0,0 +1,83 @@ +# json-schema-traverse +Traverse JSON Schema passing each schema object to callback + +[![Build Status](https://travis-ci.org/epoberezkin/json-schema-traverse.svg?branch=master)](https://travis-ci.org/epoberezkin/json-schema-traverse) +[![npm version](https://badge.fury.io/js/json-schema-traverse.svg)](https://www.npmjs.com/package/json-schema-traverse) +[![Coverage Status](https://coveralls.io/repos/github/epoberezkin/json-schema-traverse/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/json-schema-traverse?branch=master) + + +## Install + +``` +npm install json-schema-traverse +``` + + +## Usage + +```javascript +const traverse = require('json-schema-traverse'); +const schema = { + properties: { + foo: {type: 'string'}, + bar: {type: 'integer'} + } +}; + +traverse(schema, {cb}); +// cb is called 3 times with: +// 1. root schema +// 2. {type: 'string'} +// 3. {type: 'integer'} + +// Or: + +traverse(schema, {cb: {pre, post}}); +// pre is called 3 times with: +// 1. root schema +// 2. {type: 'string'} +// 3. {type: 'integer'} +// +// post is called 3 times with: +// 1. {type: 'string'} +// 2. {type: 'integer'} +// 3. root schema + +``` + +Callback function `cb` is called for each schema object (not including draft-06 boolean schemas), including the root schema, in pre-order traversal. Schema references ($ref) are not resolved, they are passed as is. Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre` will be called before traversing child elements, and `post` will be called after all child elements have been traversed. + +Callback is passed these parameters: + +- _schema_: the current schema object +- _JSON pointer_: from the root schema to the current schema object +- _root schema_: the schema passed to `traverse` object +- _parent JSON pointer_: from the root schema to the parent schema object (see below) +- _parent keyword_: the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.) +- _parent schema_: not necessarily parent object/array; in the example above the parent schema for `{type: 'string'}` is the root schema +- _index/property_: index or property name in the array/object containing multiple schemas; in the example above for `{type: 'string'}` the property name is `'foo'` + + +## Traverse objects in all unknown keywords + +```javascript +const traverse = require('json-schema-traverse'); +const schema = { + mySchema: { + minimum: 1, + maximum: 2 + } +}; + +traverse(schema, {allKeys: true, cb}); +// cb is called 2 times with: +// 1. root schema +// 2. mySchema +``` + +Without option `allKeys: true` callback will be called only with root schema. + + +## License + +[MIT](https://github.com/epoberezkin/json-schema-traverse/blob/master/LICENSE) diff --git a/node_modules/terser-webpack-plugin/node_modules/json-schema-traverse/index.js b/node_modules/terser-webpack-plugin/node_modules/json-schema-traverse/index.js new file mode 100644 index 0000000..d4a18df --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/json-schema-traverse/index.js @@ -0,0 +1,89 @@ +'use strict'; + +var traverse = module.exports = function (schema, opts, cb) { + // Legacy support for v0.3.1 and earlier. + if (typeof opts == 'function') { + cb = opts; + opts = {}; + } + + cb = opts.cb || cb; + var pre = (typeof cb == 'function') ? cb : cb.pre || function() {}; + var post = cb.post || function() {}; + + _traverse(opts, pre, post, schema, '', schema); +}; + + +traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true +}; + +traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true +}; + +traverse.propsKeywords = { + definitions: true, + properties: true, + patternProperties: true, + dependencies: true +}; + +traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true +}; + + +function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == 'object' && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) { + for (var i=0; i +# [1.0.0](https://github.com/webpack-contrib/schema-utils/compare/v0.4.7...v1.0.0) (2018-08-07) + + +### Features + +* **src:** add support for custom error messages ([#33](https://github.com/webpack-contrib/schema-utils/issues/33)) ([1cbe4ef](https://github.com/webpack-contrib/schema-utils/commit/1cbe4ef)) + + + + +## [0.4.7](https://github.com/webpack-contrib/schema-utils/compare/v0.4.6...v0.4.7) (2018-08-07) + + +### Bug Fixes + +* **src:** `node >= v4.0.0` support ([#32](https://github.com/webpack-contrib/schema-utils/issues/32)) ([cb13dd4](https://github.com/webpack-contrib/schema-utils/commit/cb13dd4)) + + + + +## [0.4.6](https://github.com/webpack-contrib/schema-utils/compare/v0.4.5...v0.4.6) (2018-08-06) + + +### Bug Fixes + +* **package:** remove lockfile ([#28](https://github.com/webpack-contrib/schema-utils/issues/28)) ([69f1a81](https://github.com/webpack-contrib/schema-utils/commit/69f1a81)) +* **package:** remove unnecessary `webpack` dependency ([#26](https://github.com/webpack-contrib/schema-utils/issues/26)) ([532eaa5](https://github.com/webpack-contrib/schema-utils/commit/532eaa5)) + + + + +## [0.4.5](https://github.com/webpack-contrib/schema-utils/compare/v0.4.4...v0.4.5) (2018-02-13) + + +### Bug Fixes + +* **CHANGELOG:** update broken links ([4483b9f](https://github.com/webpack-contrib/schema-utils/commit/4483b9f)) +* **package:** update broken links ([f2494ba](https://github.com/webpack-contrib/schema-utils/commit/f2494ba)) + + + + +## [0.4.4](https://github.com/webpack-contrib/schema-utils/compare/v0.4.3...v0.4.4) (2018-02-13) + + +### Bug Fixes + +* **package:** update `dependencies` ([#22](https://github.com/webpack-contrib/schema-utils/issues/22)) ([3aecac6](https://github.com/webpack-contrib/schema-utils/commit/3aecac6)) + + + + +## [0.4.3](https://github.com/webpack-contrib/schema-utils/compare/v0.4.2...v0.4.3) (2017-12-14) + + +### Bug Fixes + +* **validateOptions:** throw `err` instead of `process.exit(1)` ([#17](https://github.com/webpack-contrib/schema-utils/issues/17)) ([c595eda](https://github.com/webpack-contrib/schema-utils/commit/c595eda)) +* **ValidationError:** never return `this` in the ctor ([#16](https://github.com/webpack-contrib/schema-utils/issues/16)) ([c723791](https://github.com/webpack-contrib/schema-utils/commit/c723791)) + + + + +## [0.4.2](https://github.com/webpack-contrib/schema-utils/compare/v0.4.1...v0.4.2) (2017-11-09) + + +### Bug Fixes + +* **validateOptions:** catch `ValidationError` and handle it internally ([#15](https://github.com/webpack-contrib/schema-utils/issues/15)) ([9c5ef5e](https://github.com/webpack-contrib/schema-utils/commit/9c5ef5e)) + + + + +## [0.4.1](https://github.com/webpack-contrib/schema-utils/compare/v0.4.0...v0.4.1) (2017-11-03) + + +### Bug Fixes + +* **ValidationError:** use `Error.captureStackTrace` for `err.stack` handling ([#14](https://github.com/webpack-contrib/schema-utils/issues/14)) ([a6fb974](https://github.com/webpack-contrib/schema-utils/commit/a6fb974)) + + + + +# [0.4.0](https://github.com/webpack-contrib/schema-utils/compare/v0.3.0...v0.4.0) (2017-10-28) + + +### Features + +* add support for `typeof`, `instanceof` (`{Function\|RegExp}`) ([#10](https://github.com/webpack-contrib/schema-utils/issues/10)) ([9f01816](https://github.com/webpack-contrib/schema-utils/commit/9f01816)) + + + + +# [0.3.0](https://github.com/webpack-contrib/schema-utils/compare/v0.2.1...v0.3.0) (2017-04-29) + + +### Features + +* add ValidationError ([#8](https://github.com/webpack-contrib/schema-utils/issues/8)) ([d48f0fb](https://github.com/webpack-contrib/schema-utils/commit/d48f0fb)) + + + + +## [0.2.1](https://github.com/webpack-contrib/schema-utils/compare/v0.2.0...v0.2.1) (2017-03-13) + + +### Bug Fixes + +* Include .babelrc to `files` ([28f0363](https://github.com/webpack-contrib/schema-utils/commit/28f0363)) +* Include source to `files` ([43b0f2f](https://github.com/webpack-contrib/schema-utils/commit/43b0f2f)) + + + + +# [0.2.0](https://github.com/webpack-contrib/schema-utils/compare/v0.1.0...v0.2.0) (2017-03-12) + + +# 0.1.0 (2017-03-07) + + +### Features + +* **validations:** add validateOptions module ([ae9b47b](https://github.com/webpack-contrib/schema-utils/commit/ae9b47b)) + + + +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. diff --git a/node_modules/terser-webpack-plugin/node_modules/schema-utils/LICENSE b/node_modules/terser-webpack-plugin/node_modules/schema-utils/LICENSE new file mode 100644 index 0000000..8c11fc7 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/schema-utils/LICENSE @@ -0,0 +1,20 @@ +Copyright JS Foundation and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/terser-webpack-plugin/node_modules/schema-utils/README.md b/node_modules/terser-webpack-plugin/node_modules/schema-utils/README.md new file mode 100644 index 0000000..b56ab02 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/schema-utils/README.md @@ -0,0 +1,290 @@ + + +[![npm][npm]][npm-url] +[![node][node]][node-url] +[![deps][deps]][deps-url] +[![tests][tests]][tests-url] +[![coverage][cover]][cover-url] +[![chat][chat]][chat-url] +[![size][size]][size-url] + +# schema-utils + +Package for validate options in loaders and plugins. + +## Getting Started + +To begin, you'll need to install `schema-utils`: + +```console +npm install schema-utils +``` + +## API + +**schema.json** + +```json +{ + "type": "object", + "properties": { + "option": { + "type": "boolean" + } + }, + "additionalProperties": false +} +``` + +```js +import schema from "./path/to/schema.json"; +import { validate } from "schema-utils"; + +const options = { option: true }; +const configuration = { name: "Loader Name/Plugin Name/Name" }; + +validate(schema, options, configuration); +``` + +### `schema` + +Type: `String` + +JSON schema. + +Simple example of schema: + +```json +{ + "type": "object", + "properties": { + "name": { + "description": "This is description of option.", + "type": "string" + } + }, + "additionalProperties": false +} +``` + +### `options` + +Type: `Object` + +Object with options. + +```js +import schema from "./path/to/schema.json"; +import { validate } from "schema-utils"; + +const options = { foo: "bar" }; + +validate(schema, { name: 123 }, { name: "MyPlugin" }); +``` + +### `configuration` + +Allow to configure validator. + +There is an alternative method to configure the `name` and`baseDataPath` options via the `title` property in the schema. +For example: + +```json +{ + "title": "My Loader options", + "type": "object", + "properties": { + "name": { + "description": "This is description of option.", + "type": "string" + } + }, + "additionalProperties": false +} +``` + +The last word used for the `baseDataPath` option, other words used for the `name` option. +Based on the example above the `name` option equals `My Loader`, the `baseDataPath` option equals `options`. + +#### `name` + +Type: `Object` +Default: `"Object"` + +Allow to setup name in validation errors. + +```js +import schema from "./path/to/schema.json"; +import { validate } from "schema-utils"; + +const options = { foo: "bar" }; + +validate(schema, options, { name: "MyPlugin" }); +``` + +```shell +Invalid configuration object. MyPlugin has been initialised using a configuration object that does not match the API schema. + - configuration.optionName should be a integer. +``` + +#### `baseDataPath` + +Type: `String` +Default: `"configuration"` + +Allow to setup base data path in validation errors. + +```js +import schema from "./path/to/schema.json"; +import { validate } from "schema-utils"; + +const options = { foo: "bar" }; + +validate(schema, options, { name: "MyPlugin", baseDataPath: "options" }); +``` + +```shell +Invalid options object. MyPlugin has been initialised using an options object that does not match the API schema. + - options.optionName should be a integer. +``` + +#### `postFormatter` + +Type: `Function` +Default: `undefined` + +Allow to reformat errors. + +```js +import schema from "./path/to/schema.json"; +import { validate } from "schema-utils"; + +const options = { foo: "bar" }; + +validate(schema, options, { + name: "MyPlugin", + postFormatter: (formattedError, error) => { + if (error.keyword === "type") { + return `${formattedError}\nAdditional Information.`; + } + + return formattedError; + }, +}); +``` + +```shell +Invalid options object. MyPlugin has been initialized using an options object that does not match the API schema. + - options.optionName should be a integer. + Additional Information. +``` + +## Examples + +**schema.json** + +```json +{ + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "test": { + "anyOf": [ + { "type": "array" }, + { "type": "string" }, + { "instanceof": "RegExp" } + ] + }, + "transform": { + "instanceof": "Function" + }, + "sourceMap": { + "type": "boolean" + } + }, + "additionalProperties": false +} +``` + +### `Loader` + +```js +import { getOptions } from "loader-utils"; +import { validate } from "schema-utils"; + +import schema from "path/to/schema.json"; + +function loader(src, map) { + const options = getOptions(this); + + validate(schema, options, { + name: "Loader Name", + baseDataPath: "options", + }); + + // Code... +} + +export default loader; +``` + +### `Plugin` + +```js +import { validate } from "schema-utils"; + +import schema from "path/to/schema.json"; + +class Plugin { + constructor(options) { + validate(schema, options, { + name: "Plugin Name", + baseDataPath: "options", + }); + + this.options = options; + } + + apply(compiler) { + // Code... + } +} + +export default Plugin; +``` + +## Contributing + +Please take a moment to read our contributing guidelines if you haven't yet done so. + +[CONTRIBUTING](./.github/CONTRIBUTING.md) + +## License + +[MIT](./LICENSE) + +[npm]: https://img.shields.io/npm/v/schema-utils.svg +[npm-url]: https://npmjs.com/package/schema-utils +[node]: https://img.shields.io/node/v/schema-utils.svg +[node-url]: https://nodejs.org +[deps]: https://david-dm.org/webpack/schema-utils.svg +[deps-url]: https://david-dm.org/webpack/schema-utils +[tests]: https://github.com/webpack/schema-utils/workflows/schema-utils/badge.svg +[tests-url]: https://github.com/webpack/schema-utils/actions +[cover]: https://codecov.io/gh/webpack/schema-utils/branch/master/graph/badge.svg +[cover-url]: https://codecov.io/gh/webpack/schema-utils +[chat]: https://badges.gitter.im/webpack/webpack.svg +[chat-url]: https://gitter.im/webpack/webpack +[size]: https://packagephobia.com/badge?p=schema-utils +[size-url]: https://packagephobia.com/result?p=schema-utils diff --git a/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/ValidationError.d.ts b/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/ValidationError.d.ts new file mode 100644 index 0000000..55a8a9a --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/ValidationError.d.ts @@ -0,0 +1,74 @@ +export default ValidationError; +export type JSONSchema6 = import("json-schema").JSONSchema6; +export type JSONSchema7 = import("json-schema").JSONSchema7; +export type Schema = import("./validate").Schema; +export type ValidationErrorConfiguration = + import("./validate").ValidationErrorConfiguration; +export type PostFormatter = import("./validate").PostFormatter; +export type SchemaUtilErrorObject = import("./validate").SchemaUtilErrorObject; +declare class ValidationError extends Error { + /** + * @param {Array} errors + * @param {Schema} schema + * @param {ValidationErrorConfiguration} configuration + */ + constructor( + errors: Array, + schema: Schema, + configuration?: ValidationErrorConfiguration + ); + /** @type {Array} */ + errors: Array; + /** @type {Schema} */ + schema: Schema; + /** @type {string} */ + headerName: string; + /** @type {string} */ + baseDataPath: string; + /** @type {PostFormatter | null} */ + postFormatter: PostFormatter | null; + /** + * @param {string} path + * @returns {Schema} + */ + getSchemaPart(path: string): Schema; + /** + * @param {Schema} schema + * @param {boolean} logic + * @param {Array} prevSchemas + * @returns {string} + */ + formatSchema( + schema: Schema, + logic?: boolean, + prevSchemas?: Array + ): string; + /** + * @param {Schema=} schemaPart + * @param {(boolean | Array)=} additionalPath + * @param {boolean=} needDot + * @param {boolean=} logic + * @returns {string} + */ + getSchemaPartText( + schemaPart?: Schema | undefined, + additionalPath?: (boolean | Array) | undefined, + needDot?: boolean | undefined, + logic?: boolean | undefined + ): string; + /** + * @param {Schema=} schemaPart + * @returns {string} + */ + getSchemaPartDescription(schemaPart?: Schema | undefined): string; + /** + * @param {SchemaUtilErrorObject} error + * @returns {string} + */ + formatValidationError(error: SchemaUtilErrorObject): string; + /** + * @param {Array} errors + * @returns {string} + */ + formatValidationErrors(errors: Array): string; +} diff --git a/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/index.d.ts b/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/index.d.ts new file mode 100644 index 0000000..def01ba --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/index.d.ts @@ -0,0 +1,12 @@ +import { validate } from "./validate"; +import { ValidationError } from "./validate"; +import { enableValidation } from "./validate"; +import { disableValidation } from "./validate"; +import { needValidate } from "./validate"; +export { + validate, + ValidationError, + enableValidation, + disableValidation, + needValidate, +}; diff --git a/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/keywords/absolutePath.d.ts b/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/keywords/absolutePath.d.ts new file mode 100644 index 0000000..0d16689 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/keywords/absolutePath.d.ts @@ -0,0 +1,10 @@ +export default addAbsolutePathKeyword; +export type Ajv = import("ajv").Ajv; +export type ValidateFunction = import("ajv").ValidateFunction; +export type SchemaUtilErrorObject = import("../validate").SchemaUtilErrorObject; +/** + * + * @param {Ajv} ajv + * @returns {Ajv} + */ +declare function addAbsolutePathKeyword(ajv: Ajv): Ajv; diff --git a/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/keywords/undefinedAsNull.d.ts b/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/keywords/undefinedAsNull.d.ts new file mode 100644 index 0000000..3509652 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/keywords/undefinedAsNull.d.ts @@ -0,0 +1,8 @@ +export default addUndefinedAsNullKeyword; +export type Ajv = import("ajv").Ajv; +/** + * + * @param {Ajv} ajv + * @returns {Ajv} + */ +declare function addUndefinedAsNullKeyword(ajv: Ajv): Ajv; diff --git a/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/util/Range.d.ts b/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/util/Range.d.ts new file mode 100644 index 0000000..2ba97fc --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/util/Range.d.ts @@ -0,0 +1,79 @@ +export = Range; +/** + * @typedef {[number, boolean]} RangeValue + */ +/** + * @callback RangeValueCallback + * @param {RangeValue} rangeValue + * @returns {boolean} + */ +declare class Range { + /** + * @param {"left" | "right"} side + * @param {boolean} exclusive + * @returns {">" | ">=" | "<" | "<="} + */ + static getOperator( + side: "left" | "right", + exclusive: boolean + ): ">" | ">=" | "<" | "<="; + /** + * @param {number} value + * @param {boolean} logic is not logic applied + * @param {boolean} exclusive is range exclusive + * @returns {string} + */ + static formatRight(value: number, logic: boolean, exclusive: boolean): string; + /** + * @param {number} value + * @param {boolean} logic is not logic applied + * @param {boolean} exclusive is range exclusive + * @returns {string} + */ + static formatLeft(value: number, logic: boolean, exclusive: boolean): string; + /** + * @param {number} start left side value + * @param {number} end right side value + * @param {boolean} startExclusive is range exclusive from left side + * @param {boolean} endExclusive is range exclusive from right side + * @param {boolean} logic is not logic applied + * @returns {string} + */ + static formatRange( + start: number, + end: number, + startExclusive: boolean, + endExclusive: boolean, + logic: boolean + ): string; + /** + * @param {Array} values + * @param {boolean} logic is not logic applied + * @return {RangeValue} computed value and it's exclusive flag + */ + static getRangeValue(values: Array, logic: boolean): RangeValue; + /** @type {Array} */ + _left: Array; + /** @type {Array} */ + _right: Array; + /** + * @param {number} value + * @param {boolean=} exclusive + */ + left(value: number, exclusive?: boolean | undefined): void; + /** + * @param {number} value + * @param {boolean=} exclusive + */ + right(value: number, exclusive?: boolean | undefined): void; + /** + * @param {boolean} logic is not logic applied + * @return {string} "smart" range string representation + */ + format(logic?: boolean): string; +} +declare namespace Range { + export { RangeValue, RangeValueCallback }; +} +type RangeValue = [number, boolean]; +type RangeValueCallback = (rangeValue: RangeValue) => boolean; diff --git a/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/util/hints.d.ts b/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/util/hints.d.ts new file mode 100644 index 0000000..e43e32a --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/util/hints.d.ts @@ -0,0 +1,3 @@ +export function stringHints(schema: Schema, logic: boolean): string[]; +export function numberHints(schema: Schema, logic: boolean): string[]; +export type Schema = import("../validate").Schema; diff --git a/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/validate.d.ts b/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/validate.d.ts new file mode 100644 index 0000000..7f1c87f --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/schema-utils/declarations/validate.d.ts @@ -0,0 +1,42 @@ +export type JSONSchema4 = import("json-schema").JSONSchema4; +export type JSONSchema6 = import("json-schema").JSONSchema6; +export type JSONSchema7 = import("json-schema").JSONSchema7; +export type ErrorObject = import("ajv").ErrorObject; +export type ValidateFunction = import("ajv").ValidateFunction; +export type Extend = { + formatMinimum?: number | undefined; + formatMaximum?: number | undefined; + formatExclusiveMinimum?: boolean | undefined; + formatExclusiveMaximum?: boolean | undefined; + link?: string | undefined; + undefinedAsNull?: boolean | undefined; +}; +export type Schema = (JSONSchema4 | JSONSchema6 | JSONSchema7) & Extend; +export type SchemaUtilErrorObject = ErrorObject & { + children?: Array; +}; +export type PostFormatter = ( + formattedError: string, + error: SchemaUtilErrorObject +) => string; +export type ValidationErrorConfiguration = { + name?: string | undefined; + baseDataPath?: string | undefined; + postFormatter?: PostFormatter | undefined; +}; +/** + * @param {Schema} schema + * @param {Array | object} options + * @param {ValidationErrorConfiguration=} configuration + * @returns {void} + */ +export function validate( + schema: Schema, + options: Array | object, + configuration?: ValidationErrorConfiguration | undefined +): void; +export function enableValidation(): void; +export function disableValidation(): void; +export function needValidate(): boolean; +import ValidationError from "./ValidationError"; +export { ValidationError }; diff --git a/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/ValidationError.js b/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/ValidationError.js new file mode 100644 index 0000000..bd4086f --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/ValidationError.js @@ -0,0 +1,1277 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +const { + stringHints, + numberHints +} = require("./util/hints"); +/** @typedef {import("json-schema").JSONSchema6} JSONSchema6 */ + +/** @typedef {import("json-schema").JSONSchema7} JSONSchema7 */ + +/** @typedef {import("./validate").Schema} Schema */ + +/** @typedef {import("./validate").ValidationErrorConfiguration} ValidationErrorConfiguration */ + +/** @typedef {import("./validate").PostFormatter} PostFormatter */ + +/** @typedef {import("./validate").SchemaUtilErrorObject} SchemaUtilErrorObject */ + +/** @enum {number} */ + + +const SPECIFICITY = { + type: 1, + not: 1, + oneOf: 1, + anyOf: 1, + if: 1, + enum: 1, + const: 1, + instanceof: 1, + required: 2, + pattern: 2, + patternRequired: 2, + format: 2, + formatMinimum: 2, + formatMaximum: 2, + minimum: 2, + exclusiveMinimum: 2, + maximum: 2, + exclusiveMaximum: 2, + multipleOf: 2, + uniqueItems: 2, + contains: 2, + minLength: 2, + maxLength: 2, + minItems: 2, + maxItems: 2, + minProperties: 2, + maxProperties: 2, + dependencies: 2, + propertyNames: 2, + additionalItems: 2, + additionalProperties: 2, + absolutePath: 2 +}; +/** + * + * @param {Array} array + * @param {(item: SchemaUtilErrorObject) => number} fn + * @returns {Array} + */ + +function filterMax(array, fn) { + const evaluatedMax = array.reduce((max, item) => Math.max(max, fn(item)), 0); + return array.filter(item => fn(item) === evaluatedMax); +} +/** + * + * @param {Array} children + * @returns {Array} + */ + + +function filterChildren(children) { + let newChildren = children; + newChildren = filterMax(newChildren, + /** + * + * @param {SchemaUtilErrorObject} error + * @returns {number} + */ + error => error.dataPath ? error.dataPath.length : 0); + newChildren = filterMax(newChildren, + /** + * @param {SchemaUtilErrorObject} error + * @returns {number} + */ + error => SPECIFICITY[ + /** @type {keyof typeof SPECIFICITY} */ + error.keyword] || 2); + return newChildren; +} +/** + * Find all children errors + * @param {Array} children + * @param {Array} schemaPaths + * @return {number} returns index of first child + */ + + +function findAllChildren(children, schemaPaths) { + let i = children.length - 1; + + const predicate = + /** + * @param {string} schemaPath + * @returns {boolean} + */ + schemaPath => children[i].schemaPath.indexOf(schemaPath) !== 0; + + while (i > -1 && !schemaPaths.every(predicate)) { + if (children[i].keyword === "anyOf" || children[i].keyword === "oneOf") { + const refs = extractRefs(children[i]); + const childrenStart = findAllChildren(children.slice(0, i), refs.concat(children[i].schemaPath)); + i = childrenStart - 1; + } else { + i -= 1; + } + } + + return i + 1; +} +/** + * Extracts all refs from schema + * @param {SchemaUtilErrorObject} error + * @return {Array} + */ + + +function extractRefs(error) { + const { + schema + } = error; + + if (!Array.isArray(schema)) { + return []; + } + + return schema.map(({ + $ref + }) => $ref).filter(s => s); +} +/** + * Groups children by their first level parent (assuming that error is root) + * @param {Array} children + * @return {Array} + */ + + +function groupChildrenByFirstChild(children) { + const result = []; + let i = children.length - 1; + + while (i > 0) { + const child = children[i]; + + if (child.keyword === "anyOf" || child.keyword === "oneOf") { + const refs = extractRefs(child); + const childrenStart = findAllChildren(children.slice(0, i), refs.concat(child.schemaPath)); + + if (childrenStart !== i) { + result.push(Object.assign({}, child, { + children: children.slice(childrenStart, i) + })); + i = childrenStart; + } else { + result.push(child); + } + } else { + result.push(child); + } + + i -= 1; + } + + if (i === 0) { + result.push(children[i]); + } + + return result.reverse(); +} +/** + * @param {string} str + * @param {string} prefix + * @returns {string} + */ + + +function indent(str, prefix) { + return str.replace(/\n(?!$)/g, `\n${prefix}`); +} +/** + * @param {Schema} schema + * @returns {schema is (Schema & {not: Schema})} + */ + + +function hasNotInSchema(schema) { + return !!schema.not; +} +/** + * @param {Schema} schema + * @return {Schema} + */ + + +function findFirstTypedSchema(schema) { + if (hasNotInSchema(schema)) { + return findFirstTypedSchema(schema.not); + } + + return schema; +} +/** + * @param {Schema} schema + * @return {boolean} + */ + + +function canApplyNot(schema) { + const typedSchema = findFirstTypedSchema(schema); + return likeNumber(typedSchema) || likeInteger(typedSchema) || likeString(typedSchema) || likeNull(typedSchema) || likeBoolean(typedSchema); +} +/** + * @param {any} maybeObj + * @returns {boolean} + */ + + +function isObject(maybeObj) { + return typeof maybeObj === "object" && maybeObj !== null; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ + + +function likeNumber(schema) { + return schema.type === "number" || typeof schema.minimum !== "undefined" || typeof schema.exclusiveMinimum !== "undefined" || typeof schema.maximum !== "undefined" || typeof schema.exclusiveMaximum !== "undefined" || typeof schema.multipleOf !== "undefined"; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ + + +function likeInteger(schema) { + return schema.type === "integer" || typeof schema.minimum !== "undefined" || typeof schema.exclusiveMinimum !== "undefined" || typeof schema.maximum !== "undefined" || typeof schema.exclusiveMaximum !== "undefined" || typeof schema.multipleOf !== "undefined"; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ + + +function likeString(schema) { + return schema.type === "string" || typeof schema.minLength !== "undefined" || typeof schema.maxLength !== "undefined" || typeof schema.pattern !== "undefined" || typeof schema.format !== "undefined" || typeof schema.formatMinimum !== "undefined" || typeof schema.formatMaximum !== "undefined"; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ + + +function likeBoolean(schema) { + return schema.type === "boolean"; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ + + +function likeArray(schema) { + return schema.type === "array" || typeof schema.minItems === "number" || typeof schema.maxItems === "number" || typeof schema.uniqueItems !== "undefined" || typeof schema.items !== "undefined" || typeof schema.additionalItems !== "undefined" || typeof schema.contains !== "undefined"; +} +/** + * @param {Schema & {patternRequired?: Array}} schema + * @returns {boolean} + */ + + +function likeObject(schema) { + return schema.type === "object" || typeof schema.minProperties !== "undefined" || typeof schema.maxProperties !== "undefined" || typeof schema.required !== "undefined" || typeof schema.properties !== "undefined" || typeof schema.patternProperties !== "undefined" || typeof schema.additionalProperties !== "undefined" || typeof schema.dependencies !== "undefined" || typeof schema.propertyNames !== "undefined" || typeof schema.patternRequired !== "undefined"; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ + + +function likeNull(schema) { + return schema.type === "null"; +} +/** + * @param {string} type + * @returns {string} + */ + + +function getArticle(type) { + if (/^[aeiou]/i.test(type)) { + return "an"; + } + + return "a"; +} +/** + * @param {Schema=} schema + * @returns {string} + */ + + +function getSchemaNonTypes(schema) { + if (!schema) { + return ""; + } + + if (!schema.type) { + if (likeNumber(schema) || likeInteger(schema)) { + return " | should be any non-number"; + } + + if (likeString(schema)) { + return " | should be any non-string"; + } + + if (likeArray(schema)) { + return " | should be any non-array"; + } + + if (likeObject(schema)) { + return " | should be any non-object"; + } + } + + return ""; +} +/** + * @param {Array} hints + * @returns {string} + */ + + +function formatHints(hints) { + return hints.length > 0 ? `(${hints.join(", ")})` : ""; +} +/** + * @param {Schema} schema + * @param {boolean} logic + * @returns {string[]} + */ + + +function getHints(schema, logic) { + if (likeNumber(schema) || likeInteger(schema)) { + return numberHints(schema, logic); + } else if (likeString(schema)) { + return stringHints(schema, logic); + } + + return []; +} + +class ValidationError extends Error { + /** + * @param {Array} errors + * @param {Schema} schema + * @param {ValidationErrorConfiguration} configuration + */ + constructor(errors, schema, configuration = {}) { + super(); + /** @type {string} */ + + this.name = "ValidationError"; + /** @type {Array} */ + + this.errors = errors; + /** @type {Schema} */ + + this.schema = schema; + let headerNameFromSchema; + let baseDataPathFromSchema; + + if (schema.title && (!configuration.name || !configuration.baseDataPath)) { + const splittedTitleFromSchema = schema.title.match(/^(.+) (.+)$/); + + if (splittedTitleFromSchema) { + if (!configuration.name) { + [, headerNameFromSchema] = splittedTitleFromSchema; + } + + if (!configuration.baseDataPath) { + [,, baseDataPathFromSchema] = splittedTitleFromSchema; + } + } + } + /** @type {string} */ + + + this.headerName = configuration.name || headerNameFromSchema || "Object"; + /** @type {string} */ + + this.baseDataPath = configuration.baseDataPath || baseDataPathFromSchema || "configuration"; + /** @type {PostFormatter | null} */ + + this.postFormatter = configuration.postFormatter || null; + const header = `Invalid ${this.baseDataPath} object. ${this.headerName} has been initialized using ${getArticle(this.baseDataPath)} ${this.baseDataPath} object that does not match the API schema.\n`; + /** @type {string} */ + + this.message = `${header}${this.formatValidationErrors(errors)}`; + Error.captureStackTrace(this, this.constructor); + } + /** + * @param {string} path + * @returns {Schema} + */ + + + getSchemaPart(path) { + const newPath = path.split("/"); + let schemaPart = this.schema; + + for (let i = 1; i < newPath.length; i++) { + const inner = schemaPart[ + /** @type {keyof Schema} */ + newPath[i]]; + + if (!inner) { + break; + } + + schemaPart = inner; + } + + return schemaPart; + } + /** + * @param {Schema} schema + * @param {boolean} logic + * @param {Array} prevSchemas + * @returns {string} + */ + + + formatSchema(schema, logic = true, prevSchemas = []) { + let newLogic = logic; + + const formatInnerSchema = + /** + * + * @param {Object} innerSchema + * @param {boolean=} addSelf + * @returns {string} + */ + (innerSchema, addSelf) => { + if (!addSelf) { + return this.formatSchema(innerSchema, newLogic, prevSchemas); + } + + if (prevSchemas.includes(innerSchema)) { + return "(recursive)"; + } + + return this.formatSchema(innerSchema, newLogic, prevSchemas.concat(schema)); + }; + + if (hasNotInSchema(schema) && !likeObject(schema)) { + if (canApplyNot(schema.not)) { + newLogic = !logic; + return formatInnerSchema(schema.not); + } + + const needApplyLogicHere = !schema.not.not; + const prefix = logic ? "" : "non "; + newLogic = !logic; + return needApplyLogicHere ? prefix + formatInnerSchema(schema.not) : formatInnerSchema(schema.not); + } + + if ( + /** @type {Schema & {instanceof: string | Array}} */ + schema.instanceof) { + const { + instanceof: value + } = + /** @type {Schema & {instanceof: string | Array}} */ + schema; + const values = !Array.isArray(value) ? [value] : value; + return values.map( + /** + * @param {string} item + * @returns {string} + */ + item => item === "Function" ? "function" : item).join(" | "); + } + + if (schema.enum) { + const enumValues = + /** @type {Array} */ + schema.enum.map(item => { + if (item === null && schema.undefinedAsNull) { + return `${JSON.stringify(item)} | undefined`; + } + + return JSON.stringify(item); + }).join(" | "); + return `${enumValues}`; + } + + if (typeof schema.const !== "undefined") { + return JSON.stringify(schema.const); + } + + if (schema.oneOf) { + return ( + /** @type {Array} */ + schema.oneOf.map(item => formatInnerSchema(item, true)).join(" | ") + ); + } + + if (schema.anyOf) { + return ( + /** @type {Array} */ + schema.anyOf.map(item => formatInnerSchema(item, true)).join(" | ") + ); + } + + if (schema.allOf) { + return ( + /** @type {Array} */ + schema.allOf.map(item => formatInnerSchema(item, true)).join(" & ") + ); + } + + if ( + /** @type {JSONSchema7} */ + schema.if) { + const { + if: ifValue, + then: thenValue, + else: elseValue + } = + /** @type {JSONSchema7} */ + schema; + return `${ifValue ? `if ${formatInnerSchema(ifValue)}` : ""}${thenValue ? ` then ${formatInnerSchema(thenValue)}` : ""}${elseValue ? ` else ${formatInnerSchema(elseValue)}` : ""}`; + } + + if (schema.$ref) { + return formatInnerSchema(this.getSchemaPart(schema.$ref), true); + } + + if (likeNumber(schema) || likeInteger(schema)) { + const [type, ...hints] = getHints(schema, logic); + const str = `${type}${hints.length > 0 ? ` ${formatHints(hints)}` : ""}`; + return logic ? str : hints.length > 0 ? `non-${type} | ${str}` : `non-${type}`; + } + + if (likeString(schema)) { + const [type, ...hints] = getHints(schema, logic); + const str = `${type}${hints.length > 0 ? ` ${formatHints(hints)}` : ""}`; + return logic ? str : str === "string" ? "non-string" : `non-string | ${str}`; + } + + if (likeBoolean(schema)) { + return `${logic ? "" : "non-"}boolean`; + } + + if (likeArray(schema)) { + // not logic already applied in formatValidationError + newLogic = true; + const hints = []; + + if (typeof schema.minItems === "number") { + hints.push(`should not have fewer than ${schema.minItems} item${schema.minItems > 1 ? "s" : ""}`); + } + + if (typeof schema.maxItems === "number") { + hints.push(`should not have more than ${schema.maxItems} item${schema.maxItems > 1 ? "s" : ""}`); + } + + if (schema.uniqueItems) { + hints.push("should not have duplicate items"); + } + + const hasAdditionalItems = typeof schema.additionalItems === "undefined" || Boolean(schema.additionalItems); + let items = ""; + + if (schema.items) { + if (Array.isArray(schema.items) && schema.items.length > 0) { + items = `${ + /** @type {Array} */ + schema.items.map(item => formatInnerSchema(item)).join(", ")}`; + + if (hasAdditionalItems) { + if (schema.additionalItems && isObject(schema.additionalItems) && Object.keys(schema.additionalItems).length > 0) { + hints.push(`additional items should be ${formatInnerSchema(schema.additionalItems)}`); + } + } + } else if (schema.items && Object.keys(schema.items).length > 0) { + // "additionalItems" is ignored + items = `${formatInnerSchema(schema.items)}`; + } else { + // Fallback for empty `items` value + items = "any"; + } + } else { + // "additionalItems" is ignored + items = "any"; + } + + if (schema.contains && Object.keys(schema.contains).length > 0) { + hints.push(`should contains at least one ${this.formatSchema(schema.contains)} item`); + } + + return `[${items}${hasAdditionalItems ? ", ..." : ""}]${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`; + } + + if (likeObject(schema)) { + // not logic already applied in formatValidationError + newLogic = true; + const hints = []; + + if (typeof schema.minProperties === "number") { + hints.push(`should not have fewer than ${schema.minProperties} ${schema.minProperties > 1 ? "properties" : "property"}`); + } + + if (typeof schema.maxProperties === "number") { + hints.push(`should not have more than ${schema.maxProperties} ${schema.minProperties && schema.minProperties > 1 ? "properties" : "property"}`); + } + + if (schema.patternProperties && Object.keys(schema.patternProperties).length > 0) { + const patternProperties = Object.keys(schema.patternProperties); + hints.push(`additional property names should match pattern${patternProperties.length > 1 ? "s" : ""} ${patternProperties.map(pattern => JSON.stringify(pattern)).join(" | ")}`); + } + + const properties = schema.properties ? Object.keys(schema.properties) : []; + const required = schema.required ? schema.required : []; + const allProperties = [...new Set( + /** @type {Array} */ + [].concat(required).concat(properties))]; + const objectStructure = allProperties.map(property => { + const isRequired = required.includes(property); // Some properties need quotes, maybe we should add check + // Maybe we should output type of property (`foo: string`), but it is looks very unreadable + + return `${property}${isRequired ? "" : "?"}`; + }).concat(typeof schema.additionalProperties === "undefined" || Boolean(schema.additionalProperties) ? schema.additionalProperties && isObject(schema.additionalProperties) ? [`: ${formatInnerSchema(schema.additionalProperties)}`] : ["…"] : []).join(", "); + const { + dependencies, + propertyNames, + patternRequired + } = + /** @type {Schema & {patternRequired?: Array;}} */ + schema; + + if (dependencies) { + Object.keys(dependencies).forEach(dependencyName => { + const dependency = dependencies[dependencyName]; + + if (Array.isArray(dependency)) { + hints.push(`should have ${dependency.length > 1 ? "properties" : "property"} ${dependency.map(dep => `'${dep}'`).join(", ")} when property '${dependencyName}' is present`); + } else { + hints.push(`should be valid according to the schema ${formatInnerSchema(dependency)} when property '${dependencyName}' is present`); + } + }); + } + + if (propertyNames && Object.keys(propertyNames).length > 0) { + hints.push(`each property name should match format ${JSON.stringify(schema.propertyNames.format)}`); + } + + if (patternRequired && patternRequired.length > 0) { + hints.push(`should have property matching pattern ${patternRequired.map( + /** + * @param {string} item + * @returns {string} + */ + item => JSON.stringify(item))}`); + } + + return `object {${objectStructure ? ` ${objectStructure} ` : ""}}${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`; + } + + if (likeNull(schema)) { + return `${logic ? "" : "non-"}null`; + } + + if (Array.isArray(schema.type)) { + // not logic already applied in formatValidationError + return `${schema.type.join(" | ")}`; + } // Fallback for unknown keywords + // not logic already applied in formatValidationError + + /* istanbul ignore next */ + + + return JSON.stringify(schema, null, 2); + } + /** + * @param {Schema=} schemaPart + * @param {(boolean | Array)=} additionalPath + * @param {boolean=} needDot + * @param {boolean=} logic + * @returns {string} + */ + + + getSchemaPartText(schemaPart, additionalPath, needDot = false, logic = true) { + if (!schemaPart) { + return ""; + } + + if (Array.isArray(additionalPath)) { + for (let i = 0; i < additionalPath.length; i++) { + /** @type {Schema | undefined} */ + const inner = schemaPart[ + /** @type {keyof Schema} */ + additionalPath[i]]; + + if (inner) { + // eslint-disable-next-line no-param-reassign + schemaPart = inner; + } else { + break; + } + } + } + + while (schemaPart.$ref) { + // eslint-disable-next-line no-param-reassign + schemaPart = this.getSchemaPart(schemaPart.$ref); + } + + let schemaText = `${this.formatSchema(schemaPart, logic)}${needDot ? "." : ""}`; + + if (schemaPart.description) { + schemaText += `\n-> ${schemaPart.description}`; + } + + if (schemaPart.link) { + schemaText += `\n-> Read more at ${schemaPart.link}`; + } + + return schemaText; + } + /** + * @param {Schema=} schemaPart + * @returns {string} + */ + + + getSchemaPartDescription(schemaPart) { + if (!schemaPart) { + return ""; + } + + while (schemaPart.$ref) { + // eslint-disable-next-line no-param-reassign + schemaPart = this.getSchemaPart(schemaPart.$ref); + } + + let schemaText = ""; + + if (schemaPart.description) { + schemaText += `\n-> ${schemaPart.description}`; + } + + if (schemaPart.link) { + schemaText += `\n-> Read more at ${schemaPart.link}`; + } + + return schemaText; + } + /** + * @param {SchemaUtilErrorObject} error + * @returns {string} + */ + + + formatValidationError(error) { + const { + keyword, + dataPath: errorDataPath + } = error; + const dataPath = `${this.baseDataPath}${errorDataPath}`; + + switch (keyword) { + case "type": + { + const { + parentSchema, + params + } = error; // eslint-disable-next-line default-case + + switch ( + /** @type {import("ajv").TypeParams} */ + params.type) { + case "number": + return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; + + case "integer": + return `${dataPath} should be an ${this.getSchemaPartText(parentSchema, false, true)}`; + + case "string": + return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; + + case "boolean": + return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; + + case "array": + return `${dataPath} should be an array:\n${this.getSchemaPartText(parentSchema)}`; + + case "object": + return `${dataPath} should be an object:\n${this.getSchemaPartText(parentSchema)}`; + + case "null": + return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; + + default: + return `${dataPath} should be:\n${this.getSchemaPartText(parentSchema)}`; + } + } + + case "instanceof": + { + const { + parentSchema + } = error; + return `${dataPath} should be an instance of ${this.getSchemaPartText(parentSchema, false, true)}`; + } + + case "pattern": + { + const { + params, + parentSchema + } = error; + const { + pattern + } = + /** @type {import("ajv").PatternParams} */ + params; + return `${dataPath} should match pattern ${JSON.stringify(pattern)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "format": + { + const { + params, + parentSchema + } = error; + const { + format + } = + /** @type {import("ajv").FormatParams} */ + params; + return `${dataPath} should match format ${JSON.stringify(format)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "formatMinimum": + case "formatMaximum": + { + const { + params, + parentSchema + } = error; + const { + comparison, + limit + } = + /** @type {import("ajv").ComparisonParams} */ + params; + return `${dataPath} should be ${comparison} ${JSON.stringify(limit)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "minimum": + case "maximum": + case "exclusiveMinimum": + case "exclusiveMaximum": + { + const { + parentSchema, + params + } = error; + const { + comparison, + limit + } = + /** @type {import("ajv").ComparisonParams} */ + params; + const [, ...hints] = getHints( + /** @type {Schema} */ + parentSchema, true); + + if (hints.length === 0) { + hints.push(`should be ${comparison} ${limit}`); + } + + return `${dataPath} ${hints.join(" ")}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "multipleOf": + { + const { + params, + parentSchema + } = error; + const { + multipleOf + } = + /** @type {import("ajv").MultipleOfParams} */ + params; + return `${dataPath} should be multiple of ${multipleOf}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "patternRequired": + { + const { + params, + parentSchema + } = error; + const { + missingPattern + } = + /** @type {import("ajv").PatternRequiredParams} */ + params; + return `${dataPath} should have property matching pattern ${JSON.stringify(missingPattern)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "minLength": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + + if (limit === 1) { + return `${dataPath} should be a non-empty string${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + const length = limit - 1; + return `${dataPath} should be longer than ${length} character${length > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "minItems": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + + if (limit === 1) { + return `${dataPath} should be a non-empty array${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + return `${dataPath} should not have fewer than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "minProperties": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + + if (limit === 1) { + return `${dataPath} should be a non-empty object${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + return `${dataPath} should not have fewer than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "maxLength": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + const max = limit + 1; + return `${dataPath} should be shorter than ${max} character${max > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "maxItems": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + return `${dataPath} should not have more than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "maxProperties": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + return `${dataPath} should not have more than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "uniqueItems": + { + const { + params, + parentSchema + } = error; + const { + i + } = + /** @type {import("ajv").UniqueItemsParams} */ + params; + return `${dataPath} should not contain the item '${error.data[i]}' twice${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "additionalItems": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + return `${dataPath} should not have more than ${limit} items${getSchemaNonTypes(parentSchema)}. These items are valid:\n${this.getSchemaPartText(parentSchema)}`; + } + + case "contains": + { + const { + parentSchema + } = error; + return `${dataPath} should contains at least one ${this.getSchemaPartText(parentSchema, ["contains"])} item${getSchemaNonTypes(parentSchema)}.`; + } + + case "required": + { + const { + parentSchema, + params + } = error; + const missingProperty = + /** @type {import("ajv").DependenciesParams} */ + params.missingProperty.replace(/^\./, ""); + const hasProperty = parentSchema && Boolean( + /** @type {Schema} */ + parentSchema.properties && + /** @type {Schema} */ + parentSchema.properties[missingProperty]); + return `${dataPath} misses the property '${missingProperty}'${getSchemaNonTypes(parentSchema)}.${hasProperty ? ` Should be:\n${this.getSchemaPartText(parentSchema, ["properties", missingProperty])}` : this.getSchemaPartDescription(parentSchema)}`; + } + + case "additionalProperties": + { + const { + params, + parentSchema + } = error; + const { + additionalProperty + } = + /** @type {import("ajv").AdditionalPropertiesParams} */ + params; + return `${dataPath} has an unknown property '${additionalProperty}'${getSchemaNonTypes(parentSchema)}. These properties are valid:\n${this.getSchemaPartText(parentSchema)}`; + } + + case "dependencies": + { + const { + params, + parentSchema + } = error; + const { + property, + deps + } = + /** @type {import("ajv").DependenciesParams} */ + params; + const dependencies = deps.split(",").map( + /** + * @param {string} dep + * @returns {string} + */ + dep => `'${dep.trim()}'`).join(", "); + return `${dataPath} should have properties ${dependencies} when property '${property}' is present${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "propertyNames": + { + const { + params, + parentSchema, + schema + } = error; + const { + propertyName + } = + /** @type {import("ajv").PropertyNamesParams} */ + params; + return `${dataPath} property name '${propertyName}' is invalid${getSchemaNonTypes(parentSchema)}. Property names should be match format ${JSON.stringify(schema.format)}.${this.getSchemaPartDescription(parentSchema)}`; + } + + case "enum": + { + const { + parentSchema + } = error; + + if (parentSchema && + /** @type {Schema} */ + parentSchema.enum && + /** @type {Schema} */ + parentSchema.enum.length === 1) { + return `${dataPath} should be ${this.getSchemaPartText(parentSchema, false, true)}`; + } + + return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`; + } + + case "const": + { + const { + parentSchema + } = error; + return `${dataPath} should be equal to constant ${this.getSchemaPartText(parentSchema, false, true)}`; + } + + case "not": + { + const postfix = likeObject( + /** @type {Schema} */ + error.parentSchema) ? `\n${this.getSchemaPartText(error.parentSchema)}` : ""; + const schemaOutput = this.getSchemaPartText(error.schema, false, false, false); + + if (canApplyNot(error.schema)) { + return `${dataPath} should be any ${schemaOutput}${postfix}.`; + } + + const { + schema, + parentSchema + } = error; + return `${dataPath} should not be ${this.getSchemaPartText(schema, false, true)}${parentSchema && likeObject(parentSchema) ? `\n${this.getSchemaPartText(parentSchema)}` : ""}`; + } + + case "oneOf": + case "anyOf": + { + const { + parentSchema, + children + } = error; + + if (children && children.length > 0) { + if (error.schema.length === 1) { + const lastChild = children[children.length - 1]; + const remainingChildren = children.slice(0, children.length - 1); + return this.formatValidationError(Object.assign({}, lastChild, { + children: remainingChildren, + parentSchema: Object.assign({}, parentSchema, lastChild.parentSchema) + })); + } + + let filteredChildren = filterChildren(children); + + if (filteredChildren.length === 1) { + return this.formatValidationError(filteredChildren[0]); + } + + filteredChildren = groupChildrenByFirstChild(filteredChildren); + return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}\nDetails:\n${filteredChildren.map( + /** + * @param {SchemaUtilErrorObject} nestedError + * @returns {string} + */ + nestedError => ` * ${indent(this.formatValidationError(nestedError), " ")}`).join("\n")}`; + } + + return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`; + } + + case "if": + { + const { + params, + parentSchema + } = error; + const { + failingKeyword + } = + /** @type {import("ajv").IfParams} */ + params; + return `${dataPath} should match "${failingKeyword}" schema:\n${this.getSchemaPartText(parentSchema, [failingKeyword])}`; + } + + case "absolutePath": + { + const { + message, + parentSchema + } = error; + return `${dataPath}: ${message}${this.getSchemaPartDescription(parentSchema)}`; + } + + /* istanbul ignore next */ + + default: + { + const { + message, + parentSchema + } = error; + const ErrorInJSON = JSON.stringify(error, null, 2); // For `custom`, `false schema`, `$ref` keywords + // Fallback for unknown keywords + + return `${dataPath} ${message} (${ErrorInJSON}).\n${this.getSchemaPartText(parentSchema, false)}`; + } + } + } + /** + * @param {Array} errors + * @returns {string} + */ + + + formatValidationErrors(errors) { + return errors.map(error => { + let formattedError = this.formatValidationError(error); + + if (this.postFormatter) { + formattedError = this.postFormatter(formattedError, error); + } + + return ` - ${indent(formattedError, " ")}`; + }).join("\n"); + } + +} + +var _default = ValidationError; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/index.js b/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/index.js new file mode 100644 index 0000000..94d676f --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/index.js @@ -0,0 +1,17 @@ +"use strict"; + +const { + validate, + ValidationError, + enableValidation, + disableValidation, + needValidate +} = require("./validate"); + +module.exports = { + validate, + ValidationError, + enableValidation, + disableValidation, + needValidate +}; \ No newline at end of file diff --git a/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/keywords/absolutePath.js b/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/keywords/absolutePath.js new file mode 100644 index 0000000..0a912da --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/keywords/absolutePath.js @@ -0,0 +1,93 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/** @typedef {import("ajv").Ajv} Ajv */ + +/** @typedef {import("ajv").ValidateFunction} ValidateFunction */ + +/** @typedef {import("../validate").SchemaUtilErrorObject} SchemaUtilErrorObject */ + +/** + * @param {string} message + * @param {object} schema + * @param {string} data + * @returns {SchemaUtilErrorObject} + */ +function errorMessage(message, schema, data) { + return { + // @ts-ignore + // eslint-disable-next-line no-undefined + dataPath: undefined, + // @ts-ignore + // eslint-disable-next-line no-undefined + schemaPath: undefined, + keyword: "absolutePath", + params: { + absolutePath: data + }, + message, + parentSchema: schema + }; +} +/** + * @param {boolean} shouldBeAbsolute + * @param {object} schema + * @param {string} data + * @returns {SchemaUtilErrorObject} + */ + + +function getErrorFor(shouldBeAbsolute, schema, data) { + const message = shouldBeAbsolute ? `The provided value ${JSON.stringify(data)} is not an absolute path!` : `A relative path is expected. However, the provided value ${JSON.stringify(data)} is an absolute path!`; + return errorMessage(message, schema, data); +} +/** + * + * @param {Ajv} ajv + * @returns {Ajv} + */ + + +function addAbsolutePathKeyword(ajv) { + ajv.addKeyword("absolutePath", { + errors: true, + type: "string", + + compile(schema, parentSchema) { + /** @type {ValidateFunction} */ + const callback = data => { + let passes = true; + const isExclamationMarkPresent = data.includes("!"); + + if (isExclamationMarkPresent) { + callback.errors = [errorMessage(`The provided value ${JSON.stringify(data)} contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.`, parentSchema, data)]; + passes = false; + } // ?:[A-Za-z]:\\ - Windows absolute path + // \\\\ - Windows network absolute path + // \/ - Unix-like OS absolute path + + + const isCorrectAbsolutePath = schema === /^(?:[A-Za-z]:(\\|\/)|\\\\|\/)/.test(data); + + if (!isCorrectAbsolutePath) { + callback.errors = [getErrorFor(schema, parentSchema, data)]; + passes = false; + } + + return passes; + }; + + callback.errors = []; + return callback; + } + + }); + return ajv; +} + +var _default = addAbsolutePathKeyword; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/keywords/undefinedAsNull.js b/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/keywords/undefinedAsNull.js new file mode 100644 index 0000000..1d54aab --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/keywords/undefinedAsNull.js @@ -0,0 +1,95 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/** @typedef {import("ajv").Ajv} Ajv */ + +/** + * + * @param {Ajv} ajv + * @param {string} keyword + * @param {any} definition + */ +function addKeyword(ajv, keyword, definition) { + let customRuleCode; + + try { + // @ts-ignore + // eslint-disable-next-line global-require + customRuleCode = require("ajv/lib/dotjs/custom"); // @ts-ignore + + const { + RULES + } = ajv; + let ruleGroup; + + for (let i = 0; i < RULES.length; i++) { + const rg = RULES[i]; + + if (typeof rg.type === "undefined") { + ruleGroup = rg; + break; + } + } + + const rule = { + keyword, + definition, + custom: true, + code: customRuleCode, + implements: definition.implements + }; + ruleGroup.rules.unshift(rule); + RULES.custom[keyword] = rule; + RULES.keywords[keyword] = true; + RULES.all[keyword] = true; + } catch (e) {// Nothing, fallback + } +} +/** + * + * @param {Ajv} ajv + * @returns {Ajv} + */ + + +function addUndefinedAsNullKeyword(ajv) { + // There is workaround for old versions of ajv, where `before` is not implemented + addKeyword(ajv, "undefinedAsNull", { + modifying: true, + + /** + * @param {boolean} kwVal + * @param {unknown} data + * @param {any} parentSchema + * @param {string} dataPath + * @param {unknown} parentData + * @param {number | string} parentDataProperty + * @return {boolean} + */ + validate(kwVal, data, parentSchema, dataPath, parentData, parentDataProperty) { + if (kwVal && parentSchema && typeof parentSchema.enum !== "undefined" && parentData && typeof parentDataProperty === "number") { + const idx = + /** @type {number} */ + parentDataProperty; + const parentDataRef = + /** @type {any[]} */ + parentData; + + if (typeof parentDataRef[idx] === "undefined") { + parentDataRef[idx] = null; + } + } + + return true; + } + + }); + return ajv; +} + +var _default = addUndefinedAsNullKeyword; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/util/Range.js b/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/util/Range.js new file mode 100644 index 0000000..14b2431 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/util/Range.js @@ -0,0 +1,163 @@ +"use strict"; + +/** + * @typedef {[number, boolean]} RangeValue + */ + +/** + * @callback RangeValueCallback + * @param {RangeValue} rangeValue + * @returns {boolean} + */ +class Range { + /** + * @param {"left" | "right"} side + * @param {boolean} exclusive + * @returns {">" | ">=" | "<" | "<="} + */ + static getOperator(side, exclusive) { + if (side === "left") { + return exclusive ? ">" : ">="; + } + + return exclusive ? "<" : "<="; + } + /** + * @param {number} value + * @param {boolean} logic is not logic applied + * @param {boolean} exclusive is range exclusive + * @returns {string} + */ + + + static formatRight(value, logic, exclusive) { + if (logic === false) { + return Range.formatLeft(value, !logic, !exclusive); + } + + return `should be ${Range.getOperator("right", exclusive)} ${value}`; + } + /** + * @param {number} value + * @param {boolean} logic is not logic applied + * @param {boolean} exclusive is range exclusive + * @returns {string} + */ + + + static formatLeft(value, logic, exclusive) { + if (logic === false) { + return Range.formatRight(value, !logic, !exclusive); + } + + return `should be ${Range.getOperator("left", exclusive)} ${value}`; + } + /** + * @param {number} start left side value + * @param {number} end right side value + * @param {boolean} startExclusive is range exclusive from left side + * @param {boolean} endExclusive is range exclusive from right side + * @param {boolean} logic is not logic applied + * @returns {string} + */ + + + static formatRange(start, end, startExclusive, endExclusive, logic) { + let result = "should be"; + result += ` ${Range.getOperator(logic ? "left" : "right", logic ? startExclusive : !startExclusive)} ${start} `; + result += logic ? "and" : "or"; + result += ` ${Range.getOperator(logic ? "right" : "left", logic ? endExclusive : !endExclusive)} ${end}`; + return result; + } + /** + * @param {Array} values + * @param {boolean} logic is not logic applied + * @return {RangeValue} computed value and it's exclusive flag + */ + + + static getRangeValue(values, logic) { + let minMax = logic ? Infinity : -Infinity; + let j = -1; + const predicate = logic ? + /** @type {RangeValueCallback} */ + ([value]) => value <= minMax : + /** @type {RangeValueCallback} */ + ([value]) => value >= minMax; + + for (let i = 0; i < values.length; i++) { + if (predicate(values[i])) { + [minMax] = values[i]; + j = i; + } + } + + if (j > -1) { + return values[j]; + } + + return [Infinity, true]; + } + + constructor() { + /** @type {Array} */ + this._left = []; + /** @type {Array} */ + + this._right = []; + } + /** + * @param {number} value + * @param {boolean=} exclusive + */ + + + left(value, exclusive = false) { + this._left.push([value, exclusive]); + } + /** + * @param {number} value + * @param {boolean=} exclusive + */ + + + right(value, exclusive = false) { + this._right.push([value, exclusive]); + } + /** + * @param {boolean} logic is not logic applied + * @return {string} "smart" range string representation + */ + + + format(logic = true) { + const [start, leftExclusive] = Range.getRangeValue(this._left, logic); + const [end, rightExclusive] = Range.getRangeValue(this._right, !logic); + + if (!Number.isFinite(start) && !Number.isFinite(end)) { + return ""; + } + + const realStart = leftExclusive ? start + 1 : start; + const realEnd = rightExclusive ? end - 1 : end; // e.g. 5 < x < 7, 5 < x <= 6, 6 <= x <= 6 + + if (realStart === realEnd) { + return `should be ${logic ? "" : "!"}= ${realStart}`; + } // e.g. 4 < x < ∞ + + + if (Number.isFinite(start) && !Number.isFinite(end)) { + return Range.formatLeft(start, logic, leftExclusive); + } // e.g. ∞ < x < 4 + + + if (!Number.isFinite(start) && Number.isFinite(end)) { + return Range.formatRight(end, logic, rightExclusive); + } + + return Range.formatRange(start, end, leftExclusive, rightExclusive, logic); + } + +} + +module.exports = Range; \ No newline at end of file diff --git a/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/util/hints.js b/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/util/hints.js new file mode 100644 index 0000000..4317b86 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/util/hints.js @@ -0,0 +1,105 @@ +"use strict"; + +const Range = require("./Range"); +/** @typedef {import("../validate").Schema} Schema */ + +/** + * @param {Schema} schema + * @param {boolean} logic + * @return {string[]} + */ + + +module.exports.stringHints = function stringHints(schema, logic) { + const hints = []; + let type = "string"; + const currentSchema = { ...schema + }; + + if (!logic) { + const tmpLength = currentSchema.minLength; + const tmpFormat = currentSchema.formatMinimum; + const tmpExclusive = currentSchema.formatExclusiveMaximum; + currentSchema.minLength = currentSchema.maxLength; + currentSchema.maxLength = tmpLength; + currentSchema.formatMinimum = currentSchema.formatMaximum; + currentSchema.formatMaximum = tmpFormat; + currentSchema.formatExclusiveMaximum = !currentSchema.formatExclusiveMinimum; + currentSchema.formatExclusiveMinimum = !tmpExclusive; + } + + if (typeof currentSchema.minLength === "number") { + if (currentSchema.minLength === 1) { + type = "non-empty string"; + } else { + const length = Math.max(currentSchema.minLength - 1, 0); + hints.push(`should be longer than ${length} character${length > 1 ? "s" : ""}`); + } + } + + if (typeof currentSchema.maxLength === "number") { + if (currentSchema.maxLength === 0) { + type = "empty string"; + } else { + const length = currentSchema.maxLength + 1; + hints.push(`should be shorter than ${length} character${length > 1 ? "s" : ""}`); + } + } + + if (currentSchema.pattern) { + hints.push(`should${logic ? "" : " not"} match pattern ${JSON.stringify(currentSchema.pattern)}`); + } + + if (currentSchema.format) { + hints.push(`should${logic ? "" : " not"} match format ${JSON.stringify(currentSchema.format)}`); + } + + if (currentSchema.formatMinimum) { + hints.push(`should be ${currentSchema.formatExclusiveMinimum ? ">" : ">="} ${JSON.stringify(currentSchema.formatMinimum)}`); + } + + if (currentSchema.formatMaximum) { + hints.push(`should be ${currentSchema.formatExclusiveMaximum ? "<" : "<="} ${JSON.stringify(currentSchema.formatMaximum)}`); + } + + return [type].concat(hints); +}; +/** + * @param {Schema} schema + * @param {boolean} logic + * @return {string[]} + */ + + +module.exports.numberHints = function numberHints(schema, logic) { + const hints = [schema.type === "integer" ? "integer" : "number"]; + const range = new Range(); + + if (typeof schema.minimum === "number") { + range.left(schema.minimum); + } + + if (typeof schema.exclusiveMinimum === "number") { + range.left(schema.exclusiveMinimum, true); + } + + if (typeof schema.maximum === "number") { + range.right(schema.maximum); + } + + if (typeof schema.exclusiveMaximum === "number") { + range.right(schema.exclusiveMaximum, true); + } + + const rangeFormat = range.format(logic); + + if (rangeFormat) { + hints.push(rangeFormat); + } + + if (typeof schema.multipleOf === "number") { + hints.push(`should${logic ? "" : " not"} be multiple of ${schema.multipleOf}`); + } + + return hints; +}; \ No newline at end of file diff --git a/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/validate.js b/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/validate.js new file mode 100644 index 0000000..cb09145 --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/schema-utils/dist/validate.js @@ -0,0 +1,258 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.validate = validate; +exports.enableValidation = enableValidation; +exports.disableValidation = disableValidation; +exports.needValidate = needValidate; +Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function () { + return _ValidationError.default; + } +}); + +var _absolutePath = _interopRequireDefault(require("./keywords/absolutePath")); + +var _undefinedAsNull = _interopRequireDefault(require("./keywords/undefinedAsNull")); + +var _ValidationError = _interopRequireDefault(require("./ValidationError")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @template T + * @param fn {(function(): any) | undefined} + * @returns {function(): T} + */ +const memoize = fn => { + let cache = false; + /** @type {T} */ + + let result; + return () => { + if (cache) { + return result; + } + + result = + /** @type {function(): any} */ + fn(); + cache = true; // Allow to clean up memory for fn + // and all dependent resources + // eslint-disable-next-line no-undefined, no-param-reassign + + fn = undefined; + return result; + }; +}; + +const getAjv = memoize(() => { + // Use CommonJS require for ajv libs so TypeScript consumers aren't locked into esModuleInterop (see #110). + // eslint-disable-next-line global-require + const Ajv = require("ajv"); // eslint-disable-next-line global-require + + + const ajvKeywords = require("ajv-keywords"); + + const ajv = new Ajv({ + allErrors: true, + verbose: true, + $data: true + }); + ajvKeywords(ajv, ["instanceof", "formatMinimum", "formatMaximum", "patternRequired"]); // Custom keywords + + (0, _absolutePath.default)(ajv); + (0, _undefinedAsNull.default)(ajv); + return ajv; +}); +/** @typedef {import("json-schema").JSONSchema4} JSONSchema4 */ + +/** @typedef {import("json-schema").JSONSchema6} JSONSchema6 */ + +/** @typedef {import("json-schema").JSONSchema7} JSONSchema7 */ + +/** @typedef {import("ajv").ErrorObject} ErrorObject */ + +/** @typedef {import("ajv").ValidateFunction} ValidateFunction */ + +/** + * @typedef {Object} Extend + * @property {number=} formatMinimum + * @property {number=} formatMaximum + * @property {boolean=} formatExclusiveMinimum + * @property {boolean=} formatExclusiveMaximum + * @property {string=} link + * @property {boolean=} undefinedAsNull + */ + +/** @typedef {(JSONSchema4 | JSONSchema6 | JSONSchema7) & Extend} Schema */ + +/** @typedef {ErrorObject & { children?: Array}} SchemaUtilErrorObject */ + +/** + * @callback PostFormatter + * @param {string} formattedError + * @param {SchemaUtilErrorObject} error + * @returns {string} + */ + +/** + * @typedef {Object} ValidationErrorConfiguration + * @property {string=} name + * @property {string=} baseDataPath + * @property {PostFormatter=} postFormatter + */ + +/** + * @param {SchemaUtilErrorObject} error + * @param {number} idx + * @returns {SchemaUtilErrorObject} + */ + +function applyPrefix(error, idx) { + // eslint-disable-next-line no-param-reassign + error.dataPath = `[${idx}]${error.dataPath}`; + + if (error.children) { + error.children.forEach(err => applyPrefix(err, idx)); + } + + return error; +} + +let skipValidation = false; // We use `process.env.SKIP_VALIDATION` because you can have multiple `schema-utils` with different version, +// so we want to disable it globally, `process.env` doesn't supported by browsers, so we have the local `skipValidation` variables +// Enable validation + +function enableValidation() { + skipValidation = false; // Disable validation for any versions + + if (process && process.env) { + process.env.SKIP_VALIDATION = "n"; + } +} // Disable validation + + +function disableValidation() { + skipValidation = true; + + if (process && process.env) { + process.env.SKIP_VALIDATION = "y"; + } +} // Check if we need to confirm + + +function needValidate() { + if (skipValidation) { + return false; + } + + if (process && process.env && process.env.SKIP_VALIDATION) { + const value = process.env.SKIP_VALIDATION.trim(); + + if (/^(?:y|yes|true|1|on)$/i.test(value)) { + return false; + } + + if (/^(?:n|no|false|0|off)$/i.test(value)) { + return true; + } + } + + return true; +} +/** + * @param {Schema} schema + * @param {Array | object} options + * @param {ValidationErrorConfiguration=} configuration + * @returns {void} + */ + + +function validate(schema, options, configuration) { + if (!needValidate()) { + return; + } + + let errors = []; + + if (Array.isArray(options)) { + for (let i = 0; i <= options.length - 1; i++) { + errors.push(...validateObject(schema, options[i]).map(err => applyPrefix(err, i))); + } + } else { + errors = validateObject(schema, options); + } + + if (errors.length > 0) { + throw new _ValidationError.default(errors, schema, configuration); + } +} +/** @typedef {WeakMap} */ + + +const schemaCache = new WeakMap(); +/** + * @param {Schema} schema + * @param {Array | object} options + * @returns {Array} + */ + +function validateObject(schema, options) { + let compiledSchema = schemaCache.get(schema); + + if (!compiledSchema) { + compiledSchema = getAjv().compile(schema); + schemaCache.set(schema, compiledSchema); + } + + const valid = compiledSchema(options); + if (valid) return []; + return compiledSchema.errors ? filterErrors(compiledSchema.errors) : []; +} +/** + * @param {Array} errors + * @returns {Array} + */ + + +function filterErrors(errors) { + /** @type {Array} */ + let newErrors = []; + + for (const error of + /** @type {Array} */ + errors) { + const { + dataPath + } = error; + /** @type {Array} */ + + let children = []; + newErrors = newErrors.filter(oldError => { + if (oldError.dataPath.includes(dataPath)) { + if (oldError.children) { + children = children.concat(oldError.children.slice(0)); + } // eslint-disable-next-line no-undefined, no-param-reassign + + + oldError.children = undefined; + children.push(oldError); + return false; + } + + return true; + }); + + if (children.length) { + error.children = children; + } + + newErrors.push(error); + } + + return newErrors; +} \ No newline at end of file diff --git a/node_modules/terser-webpack-plugin/node_modules/schema-utils/package.json b/node_modules/terser-webpack-plugin/node_modules/schema-utils/package.json new file mode 100644 index 0000000..47943ef --- /dev/null +++ b/node_modules/terser-webpack-plugin/node_modules/schema-utils/package.json @@ -0,0 +1,78 @@ +{ + "name": "schema-utils", + "version": "3.3.0", + "description": "webpack Validation Utils", + "license": "MIT", + "repository": "webpack/schema-utils", + "author": "webpack Contrib (https://github.com/webpack-contrib)", + "homepage": "https://github.com/webpack/schema-utils", + "bugs": "https://github.com/webpack/schema-utils/issues", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "main": "dist/index.js", + "types": "declarations/index.d.ts", + "engines": { + "node": ">= 10.13.0" + }, + "scripts": { + "start": "npm run build -- -w", + "clean": "del-cli dist declarations", + "prebuild": "npm run clean", + "build:types": "tsc --declaration --emitDeclarationOnly --outDir declarations && prettier \"declarations/**/*.ts\" --write", + "build:code": "cross-env NODE_ENV=production babel src -d dist --copy-files", + "build": "npm-run-all -p \"build:**\"", + "commitlint": "commitlint --from=master", + "security": "npm audit --production", + "fmt:check": "prettier \"{**/*,*}.{js,json,md,yml,css,ts}\" --list-different", + "lint:js": "eslint --cache .", + "lint:types": "tsc --pretty --noEmit", + "lint": "npm-run-all lint:js lint:types fmt:check", + "fmt": "npm run fmt:check -- --write", + "fix:js": "npm run lint:js -- --fix", + "fix": "npm-run-all fix:js fmt", + "test:only": "cross-env NODE_ENV=test jest", + "test:watch": "npm run test:only -- --watch", + "test:coverage": "npm run test:only -- --collectCoverageFrom=\"src/**/*.js\" --coverage", + "pretest": "npm run lint", + "test": "npm run test:coverage", + "prepare": "npm run build && husky install", + "release": "standard-version" + }, + "files": [ + "dist", + "declarations" + ], + "dependencies": { + "@types/json-schema": "^7.0.8", + "ajv": "^6.12.5", + "ajv-keywords": "^3.5.2" + }, + "devDependencies": { + "@babel/cli": "^7.14.3", + "@babel/core": "^7.14.6", + "@babel/preset-env": "^7.14.7", + "@commitlint/cli": "^12.1.4", + "@commitlint/config-conventional": "^12.1.4", + "@webpack-contrib/eslint-config-webpack": "^3.0.0", + "babel-jest": "^27.0.6", + "cross-env": "^7.0.3", + "del": "^6.0.0", + "del-cli": "^3.0.1", + "eslint": "^7.31.0", + "eslint-config-prettier": "^8.3.0", + "eslint-plugin-import": "^2.23.4", + "husky": "^6.0.0", + "jest": "^27.0.6", + "lint-staged": "^11.0.1", + "npm-run-all": "^4.1.5", + "prettier": "^2.3.2", + "standard-version": "^9.3.1", + "typescript": "^4.3.5", + "webpack": "^5.45.1" + }, + "keywords": [ + "webpack" + ] +} diff --git a/node_modules/terser-webpack-plugin/package.json b/node_modules/terser-webpack-plugin/package.json new file mode 100644 index 0000000..c6fafc3 --- /dev/null +++ b/node_modules/terser-webpack-plugin/package.json @@ -0,0 +1,120 @@ +{ + "name": "terser-webpack-plugin", + "version": "5.3.10", + "description": "Terser plugin for webpack", + "license": "MIT", + "repository": "webpack-contrib/terser-webpack-plugin", + "author": "webpack Contrib Team", + "homepage": "https://github.com/webpack-contrib/terser-webpack-plugin", + "bugs": "https://github.com/webpack-contrib/terser-webpack-plugin/issues", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "main": "dist/index.js", + "types": "types/index.d.ts", + "engines": { + "node": ">= 10.13.0" + }, + "scripts": { + "clean": "del-cli dist types", + "prebuild": "npm run clean", + "build:types": "tsc --declaration --emitDeclarationOnly --outDir types && prettier \"types/**/*.ts\" --write", + "build:code": "cross-env NODE_ENV=production babel src -d dist --copy-files", + "build": "npm-run-all -p \"build:**\"", + "commitlint": "commitlint --from=master", + "security": "npm audit --production", + "lint:prettier": "prettier --list-different .", + "lint:js": "eslint --cache .", + "lint:spelling": "cspell \"**/*.*\"", + "lint:types": "tsc --pretty --noEmit", + "lint": "npm-run-all -l -p \"lint:**\"", + "fix:js": "npm run lint:js -- --fix", + "fix:prettier": "npm run lint:prettier -- --write", + "fix": "npm-run-all -l fix:js fix:prettier", + "test:only": "cross-env NODE_ENV=test jest", + "test:watch": "npm run test:only -- --watch", + "test:coverage": "npm run test:only -- --collectCoverageFrom=\"src/**/*.js\" --coverage", + "pretest": "npm run lint", + "test": "npm run test:coverage", + "prepare": "husky install && npm run build", + "release": "standard-version" + }, + "files": [ + "dist", + "types" + ], + "peerDependencies": { + "webpack": "^5.1.0" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "uglify-js": { + "optional": true + }, + "esbuild": { + "optional": true + } + }, + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.20", + "jest-worker": "^27.4.5", + "schema-utils": "^3.1.1", + "serialize-javascript": "^6.0.1", + "terser": "^5.26.0" + }, + "devDependencies": { + "@babel/cli": "^7.22.15", + "@babel/core": "^7.22.17", + "@babel/preset-env": "^7.22.15", + "@commitlint/cli": "^17.7.1", + "@commitlint/config-conventional": "^17.7.0", + "@swc/core": "^1.3.84", + "@types/node": "^18.15.11", + "@types/serialize-javascript": "^5.0.2", + "@types/uglify-js": "^3.17.1", + "@webpack-contrib/eslint-config-webpack": "^3.0.0", + "babel-jest": "^28.1.2", + "copy-webpack-plugin": "^9.0.1", + "cross-env": "^7.0.3", + "cspell": "^6.31.2", + "del": "^6.0.0", + "del-cli": "^3.0.1", + "esbuild": "^0.19.10", + "eslint": "^7.32.0", + "eslint-config-prettier": "^8.9.0", + "eslint-plugin-import": "^2.28.1", + "file-loader": "^6.2.0", + "husky": "^7.0.2", + "jest": "^27.5.1", + "lint-staged": "^13.2.3", + "memfs": "^3.4.13", + "npm-run-all": "^4.1.5", + "prettier": "^2.8.7", + "standard-version": "^9.3.1", + "typescript": "^4.9.5", + "uglify-js": "^3.17.4", + "webpack": "^5.88.2", + "webpack-cli": "^4.10.0", + "worker-loader": "^3.0.8" + }, + "keywords": [ + "uglify", + "uglify-js", + "uglify-es", + "terser", + "webpack", + "webpack-plugin", + "minification", + "compress", + "compressor", + "min", + "minification", + "minifier", + "minify", + "optimize", + "optimizer" + ] +} diff --git a/node_modules/terser-webpack-plugin/types/index.d.ts b/node_modules/terser-webpack-plugin/types/index.d.ts new file mode 100644 index 0000000..6e80237 --- /dev/null +++ b/node_modules/terser-webpack-plugin/types/index.d.ts @@ -0,0 +1,219 @@ +export = TerserPlugin; +/** + * @template [T=TerserOptions] + */ +declare class TerserPlugin { + /** + * @private + * @param {any} input + * @returns {boolean} + */ + private static isSourceMap; + /** + * @private + * @param {unknown} warning + * @param {string} file + * @returns {Error} + */ + private static buildWarning; + /** + * @private + * @param {any} error + * @param {string} file + * @param {TraceMap} [sourceMap] + * @param {Compilation["requestShortener"]} [requestShortener] + * @returns {Error} + */ + private static buildError; + /** + * @private + * @param {Parallel} parallel + * @returns {number} + */ + private static getAvailableNumberOfCores; + /** + * @private + * @param {any} environment + * @returns {TerserECMA} + */ + private static getEcmaVersion; + /** + * @param {BasePluginOptions & DefinedDefaultMinimizerAndOptions} [options] + */ + constructor( + options?: + | (BasePluginOptions & DefinedDefaultMinimizerAndOptions) + | undefined + ); + /** + * @private + * @type {InternalPluginOptions} + */ + private options; + /** + * @private + * @param {Compiler} compiler + * @param {Compilation} compilation + * @param {Record} assets + * @param {{availableNumberOfCores: number}} optimizeOptions + * @returns {Promise} + */ + private optimize; + /** + * @param {Compiler} compiler + * @returns {void} + */ + apply(compiler: Compiler): void; +} +declare namespace TerserPlugin { + export { + terserMinify, + uglifyJsMinify, + swcMinify, + esbuildMinify, + Schema, + Compiler, + Compilation, + WebpackError, + Asset, + TerserECMA, + TerserOptions, + JestWorker, + SourceMapInput, + TraceMap, + Rule, + Rules, + ExtractCommentsFunction, + ExtractCommentsCondition, + ExtractCommentsFilename, + ExtractCommentsBanner, + ExtractCommentsObject, + ExtractCommentsOptions, + MinimizedResult, + Input, + CustomOptions, + InferDefaultType, + PredefinedOptions, + MinimizerOptions, + BasicMinimizerImplementation, + MinimizeFunctionHelpers, + MinimizerImplementation, + InternalOptions, + MinimizerWorker, + Parallel, + BasePluginOptions, + DefinedDefaultMinimizerAndOptions, + InternalPluginOptions, + }; +} +type Compiler = import("webpack").Compiler; +type BasePluginOptions = { + test?: Rules | undefined; + include?: Rules | undefined; + exclude?: Rules | undefined; + extractComments?: ExtractCommentsOptions | undefined; + parallel?: Parallel; +}; +type DefinedDefaultMinimizerAndOptions = T extends TerserOptions + ? { + minify?: MinimizerImplementation | undefined; + terserOptions?: MinimizerOptions | undefined; + } + : { + minify: MinimizerImplementation; + terserOptions?: MinimizerOptions | undefined; + }; +import { terserMinify } from "./utils"; +import { uglifyJsMinify } from "./utils"; +import { swcMinify } from "./utils"; +import { esbuildMinify } from "./utils"; +type Schema = import("schema-utils/declarations/validate").Schema; +type Compilation = import("webpack").Compilation; +type WebpackError = import("webpack").WebpackError; +type Asset = import("webpack").Asset; +type TerserECMA = import("./utils.js").TerserECMA; +type TerserOptions = import("./utils.js").TerserOptions; +type JestWorker = import("jest-worker").Worker; +type SourceMapInput = import("@jridgewell/trace-mapping").SourceMapInput; +type TraceMap = import("@jridgewell/trace-mapping").TraceMap; +type Rule = RegExp | string; +type Rules = Rule[] | Rule; +type ExtractCommentsFunction = ( + astNode: any, + comment: { + value: string; + type: "comment1" | "comment2" | "comment3" | "comment4"; + pos: number; + line: number; + col: number; + } +) => boolean; +type ExtractCommentsCondition = + | boolean + | "all" + | "some" + | RegExp + | ExtractCommentsFunction; +type ExtractCommentsFilename = string | ((fileData: any) => string); +type ExtractCommentsBanner = + | string + | boolean + | ((commentsFile: string) => string); +type ExtractCommentsObject = { + condition?: ExtractCommentsCondition | undefined; + filename?: ExtractCommentsFilename | undefined; + banner?: ExtractCommentsBanner | undefined; +}; +type ExtractCommentsOptions = ExtractCommentsCondition | ExtractCommentsObject; +type MinimizedResult = { + code: string; + map?: import("@jridgewell/trace-mapping").SourceMapInput | undefined; + errors?: (string | Error)[] | undefined; + warnings?: (string | Error)[] | undefined; + extractedComments?: string[] | undefined; +}; +type Input = { + [file: string]: string; +}; +type CustomOptions = { + [key: string]: any; +}; +type InferDefaultType = T extends infer U ? U : CustomOptions; +type PredefinedOptions = { + module?: boolean | undefined; + ecma?: import("terser").ECMA | undefined; +}; +type MinimizerOptions = PredefinedOptions & InferDefaultType; +type BasicMinimizerImplementation = ( + input: Input, + sourceMap: SourceMapInput | undefined, + minifyOptions: MinimizerOptions, + extractComments: ExtractCommentsOptions | undefined +) => Promise; +type MinimizeFunctionHelpers = { + getMinimizerVersion?: (() => string | undefined) | undefined; +}; +type MinimizerImplementation = BasicMinimizerImplementation & + MinimizeFunctionHelpers; +type InternalOptions = { + name: string; + input: string; + inputSourceMap: SourceMapInput | undefined; + extractComments: ExtractCommentsOptions | undefined; + minimizer: { + implementation: MinimizerImplementation; + options: MinimizerOptions; + }; +}; +type MinimizerWorker = import("jest-worker").Worker & { + transform: (options: string) => MinimizedResult; + minify: (options: InternalOptions) => MinimizedResult; +}; +type Parallel = undefined | boolean | number; +type InternalPluginOptions = BasePluginOptions & { + minimizer: { + implementation: MinimizerImplementation; + options: MinimizerOptions; + }; +}; +import { minify } from "./minify"; diff --git a/node_modules/terser-webpack-plugin/types/minify.d.ts b/node_modules/terser-webpack-plugin/types/minify.d.ts new file mode 100644 index 0000000..0213d74 --- /dev/null +++ b/node_modules/terser-webpack-plugin/types/minify.d.ts @@ -0,0 +1,17 @@ +export type MinimizedResult = import("./index.js").MinimizedResult; +export type CustomOptions = import("./index.js").CustomOptions; +/** @typedef {import("./index.js").MinimizedResult} MinimizedResult */ +/** @typedef {import("./index.js").CustomOptions} CustomOptions */ +/** + * @template T + * @param {import("./index.js").InternalOptions} options + * @returns {Promise} + */ +export function minify( + options: import("./index.js").InternalOptions +): Promise; +/** + * @param {string} options + * @returns {Promise} + */ +export function transform(options: string): Promise; diff --git a/node_modules/terser-webpack-plugin/types/utils.d.ts b/node_modules/terser-webpack-plugin/types/utils.d.ts new file mode 100644 index 0000000..a654e91 --- /dev/null +++ b/node_modules/terser-webpack-plugin/types/utils.d.ts @@ -0,0 +1,107 @@ +export type Task = () => Promise; +export type SourceMapInput = import("@jridgewell/trace-mapping").SourceMapInput; +export type TerserFormatOptions = import("terser").FormatOptions; +export type TerserOptions = import("terser").MinifyOptions; +export type TerserCompressOptions = import("terser").CompressOptions; +export type TerserECMA = import("terser").ECMA; +export type ExtractCommentsOptions = + import("./index.js").ExtractCommentsOptions; +export type ExtractCommentsFunction = + import("./index.js").ExtractCommentsFunction; +export type ExtractCommentsCondition = + import("./index.js").ExtractCommentsCondition; +export type Input = import("./index.js").Input; +export type MinimizedResult = import("./index.js").MinimizedResult; +export type PredefinedOptions = import("./index.js").PredefinedOptions; +export type CustomOptions = import("./index.js").CustomOptions; +export type ExtractedComments = Array; +/** + * @template T + * @typedef {() => Promise} Task + */ +/** + * Run tasks with limited concurrency. + * @template T + * @param {number} limit - Limit of tasks that run at once. + * @param {Task[]} tasks - List of tasks to run. + * @returns {Promise} A promise that fulfills to an array of the results + */ +export function throttleAll(limit: number, tasks: Task[]): Promise; +/** + * @template T + * @param fn {(function(): any) | undefined} + * @returns {function(): T} + */ +export function memoize(fn: (() => any) | undefined): () => T; +/** + * @param {Input} input + * @param {SourceMapInput | undefined} sourceMap + * @param {PredefinedOptions & CustomOptions} minimizerOptions + * @param {ExtractCommentsOptions | undefined} extractComments + * @return {Promise} + */ +export function terserMinify( + input: Input, + sourceMap: SourceMapInput | undefined, + minimizerOptions: PredefinedOptions & CustomOptions, + extractComments: ExtractCommentsOptions | undefined +): Promise; +export namespace terserMinify { + /** + * @returns {string | undefined} + */ + function getMinimizerVersion(): string | undefined; +} +/** + * @param {Input} input + * @param {SourceMapInput | undefined} sourceMap + * @param {PredefinedOptions & CustomOptions} minimizerOptions + * @param {ExtractCommentsOptions | undefined} extractComments + * @return {Promise} + */ +export function uglifyJsMinify( + input: Input, + sourceMap: SourceMapInput | undefined, + minimizerOptions: PredefinedOptions & CustomOptions, + extractComments: ExtractCommentsOptions | undefined +): Promise; +export namespace uglifyJsMinify { + /** + * @returns {string | undefined} + */ + function getMinimizerVersion(): string | undefined; +} +/** + * @param {Input} input + * @param {SourceMapInput | undefined} sourceMap + * @param {PredefinedOptions & CustomOptions} minimizerOptions + * @return {Promise} + */ +export function swcMinify( + input: Input, + sourceMap: SourceMapInput | undefined, + minimizerOptions: PredefinedOptions & CustomOptions +): Promise; +export namespace swcMinify { + /** + * @returns {string | undefined} + */ + function getMinimizerVersion(): string | undefined; +} +/** + * @param {Input} input + * @param {SourceMapInput | undefined} sourceMap + * @param {PredefinedOptions & CustomOptions} minimizerOptions + * @return {Promise} + */ +export function esbuildMinify( + input: Input, + sourceMap: SourceMapInput | undefined, + minimizerOptions: PredefinedOptions & CustomOptions +): Promise; +export namespace esbuildMinify { + /** + * @returns {string | undefined} + */ + function getMinimizerVersion(): string | undefined; +} diff --git a/node_modules/terser/CHANGELOG.md b/node_modules/terser/CHANGELOG.md new file mode 100644 index 0000000..c2a8580 --- /dev/null +++ b/node_modules/terser/CHANGELOG.md @@ -0,0 +1,760 @@ +# Changelog + +## v5.33.0 + + - `reduce_vars` improved when dealing with hoisted function definitions (#1544) + +## v5.32.0 + + - `import("module")` can now be input and output from ESTree AST (#1557) + - `BigInt` literals can now be input and output from ESTree AST (#1555) + - `typeof` an object or array (`typeof {}` and `typeof []`) can now be statically evaluated. (#1546) + +## v5.31.6 + - Retain side effects in a `case` when the expression is a sequence (comma) expression + +## v5.31.5 + - Revert v5.31.4, which created mysterious issues #1548, #1549 + +## v5.31.4 (reverted) + - drop_unused: drop classes which only have side effects in the `extends` part + +## v5.31.3 + - drop_unused: drop unused parameters from IIFEs in some more situations. + +## v5.31.2 + - drop_unused: scan variables in self-referential class declarations that contain side effects. + - Don't add parens to arrow function when it's the default for an argument (#1540) + - Update domprops (#1538) + +## v5.31.1 + - Allow drop-unused to drop the whole assignment (not just the assigned name) in more situations, in order to avoid duplication of long strings. + +## v5.31.0 + - Sync up property mangler exceptions with current contents of Firefox and Chrome environments + - Add more webcomponent properties to property mangler exceptions (#1525) + - Drop non-nullish constants in `...spreads` in objects (#1141) + +## v5.30.4 + - Fix parsing `#private in ...` when next to other operators + +## v5.30.3 + - Fix precedence of `#private in ...` operator + +## v5.30.2 + - Avoid optimizations inside computed keys, because they can cause js-engine-specific bugs. + +## v5.30.1 + - Removed useless `\` escapes for non-ascii characters + - Make modern identifier characters quoted for older environments (#1512) + +## v5.30.0 + - Improve removal of classes referring to themselves + +## v5.29.2 + - Make sure 'computed_props' creates string keys + - Take into account the evaluated size when inlining + +## v5.29.1 + - fix optimisation of all-bits mask check + +## v5.29.0 + - Re-releases previously reverted 5.28.0 + - Fix crash while optimizing some bitwise ops + - (internal) Remove needless wrapper for from_moz (#1499) + +## v5.28.1 +(hotfix release) + - Reverts v5.28.0 + +## v5.28.0 + - Optimise redundant or shrinkable bitwise operations (`|`, `^`, `&`, `>>`, `<<`) + - Evaluate some `BigInt` math operations + +## v5.27.2 + - Recognise `this` as a reference to the surrounding class in `drop_unused`. Closes #1472 + +## v5.27.1 + - Fixed case where `collapse_vars` inlines `await` expressions into non-async functions. + +## v5.27.0 + - Created `minify_sync()` alternative to `minify()` since there's no async code left. + +## v5.26.0 + - Do not take the `/*#__PURE__*/` annotation into account when the `side_effects` compress option is off. + - The `preserve_annotations` option now automatically opts annotation comments in, instead of requiring the `comments` option to be configured for this. + - Refuse to parse empty parenthesized expressions (`()`) + +## v5.25.0 + - Regex properties added to reserved property mangler (#1471) + - `pure_new` option added to drop unused `new` expressions. + +## v5.24.0 + - Improve formatting performance in V8 by keeping a small work string and a large output string + +## v5.23.0 + - When top_retain will keep a variable assignment around, inline the assignee when it's shorter than the name (#1434) + - Remove empty class `static {}` blocks. + +## v5.22.0 + - Do not `unsafe`ly shorten expressions like a?.toString() when they're conditional. + - Avoid running drop_unused in nodes that aren't scopes. Fixes a rare crash. + - When 'module' is enabled, assume strict mode when figuring out scopes. + +## v5.21.0 + - Do not inline functions that would be retained in the toplevel (as this would cause code duplication). + - Fix precedence of arrow function and ternary operator when formatting output. + +## v5.20.0 + - Passing `minify()` zero files will now throw a clean exception (#1450) + - `drop_console` supports passing in an array of `console.*` method names (#1445) + - New DOM properties from the WebGPU API have been added for use in the property mangler (#1436) + - Internal code simplification (#1437) + +## v5.19.4 + - Prevent creating very deeply nested ternaries from a long list of `if..return` + - Prevent inlining classes into other functions, to avoid constructors being compared. + +## v5.19.3 + - Fix side effect detection of `optional?.chains`. + - Add roundRect to domprops.js (#1426) + +## v5.19.2 + - fix performance hit from avoiding HTML comments in the output + +## v5.19.1 + - Better avoid outputting `` and HTML comments. + - Fix unused variables in class static blocks not being dropped correctly. + - Fix sourcemap names of methods that are `async` or `static` + +## v5.19.0 + - Allow `/*@__MANGLE_PROP__*/` annotation in `object.property`, in addition to property declarations. + +## v5.18.2 + - Stop using recursion in hoisted defuns fix. + +## v5.18.1 + - Fix major performance issue caused by hoisted defuns' scopes bugfix. + +## v5.18.0 + - Add new `/*@__MANGLE_PROP__*/` annotation, to mark properties that should be mangled. + +## v5.17.7 + - Update some dependencies + - Add consistent sorting for `v` RegExp flag + - Add `inert` DOM attribute to domprops + +## v5.17.6 + - Fixes to mozilla AST input and output, for class properties, private properties and static blocks + - Fix outputting a shorthand property in quotes when safari10 and ecma=2015 options are enabled + - `configurable` and `enumerable`, used in Object.defineProperty, added to domprops (#1393) + +## v5.17.5 + - Take into account the non-deferred bits of a class, such as static properties, while dropping unused code. + +## v5.17.4 + + - Fix crash when trying to negate a class (`!class{}`) + - Avoid outputting comments between `yield`/`await` and its argument + - Fix detection of left-hand-side of assignment, to avoid optimizing it like any other expression in some edge cases + +## v5.17.3 + + - Fix issue with trimming a static class property's contents accessing the class as `this`. + +## v5.17.2 + - Be less conservative when detecting use-before-definition of `var` in hoisted functions. + - Support unusual (but perfectly valid) initializers of for-in and for-of loops. + - Fix issue where hoisted function would be dropped if it was after a `continue` statement + +## v5.17.1 + - Fix evaluating `.length` when the source array might've been mutated + +## v5.17.0 + - Drop vestigial `= undefined` default argument in IIFE calls (#1366) + - Evaluate known arrays' `.length` property when statically determinable + - Add `@__KEY__` annotation to mangle string literals (#1365) + +## v5.16.9 + - Fix parentheses in output of optional chains (`a?.b`) (#1374) + - More documentation on source maps (#1368) + - New `lhs_constants` option, allowing to stop Terser from swapping comparison operands (#1361) + +## v5.16.8 + + - Become even less conservative around function definitions for `reduce_vars` + - Fix parsing context of `import.meta` expressions such that method calls are allowed + +## v5.16.6 + + - Become less conservative with analyzing function definitions for `reduce_vars` + - Parse `import.meta` as a real AST node and not an `object.property` + +## v5.16.5 + + - Correctly handle AST transform functions that mutate children arrays + - Don't mutate the options object passed to Terser (#1342) + - Do not treat BigInt like a number + +## v5.16.4 + + - Keep `(defaultArg = undefined) => ...`, because default args don't count for function length + - Prevent inlining variables into `?.` optional chains + - Avoid removing unused arguments while transforming + - Optimize iterating AST node lists + - Make sure `catch` and `finally` aren't children of `try` in the AST + - Use modern unicode property escapes (`\p{...}`) to parse identifiers when available + +## v5.16.3 + + - Ensure function definitions, don't assume the values of variables defined after them. + +## v5.16.2 + + - Fix sourcemaps with non-ascii characters (#1318) + - Support string module name and export * as (#1336) + - Do not move `let` out of `for` initializers, as it can change scoping + - Fix a corner case that would generate the invalid syntax `if (something) let x` ("let" in braceless if body) + - Knowledge of more native object properties (#1330) + - Got rid of Travis (#1323) + - Added semi-secret `asObject` sourcemap option to typescript defs (#1321) + +## v5.16.1 + + - Properly handle references in destructurings (`const { [reference]: val } = ...`) + - Allow parsing of `.#privatefield` in nested classes + - Do not evaluate operations that return large strings if that would make the output code larger + - Make `collapse_vars` handle block scope correctly + - Internal improvements: Typos (#1311), more tests, small-scale refactoring + +## v5.16.0 + + - Disallow private fields in object bodies (#1011) + - Parse `#privatefield in object` (#1279) + - Compress `#privatefield in object` + +## v5.15.1 + + - Fixed missing parentheses around optional chains + - Avoid bare `let` or `const` as the bodies of `if` statements (#1253) + - Small internal fixes (#1271) + - Avoid inlining a class twice and creating two equivalent but `!==` classes. + +## v5.15.0 + - Basic support for ES2022 class static initializer blocks. + - Add `AudioWorkletNode` constructor options to domprops list (#1230) + - Make identity function inliner not inline `id(...expandedArgs)` + +## v5.14.2 + + - Security fix for RegExps that should not be evaluated (regexp DDOS) + - Source maps improvements (#1211) + - Performance improvements in long property access evaluation (#1213) + +## v5.14.1 + - keep_numbers option added to TypeScript defs (#1208) + - Fixed parsing of nested template strings (#1204) + +## v5.14.0 + - Switched to @jridgewell/source-map for sourcemap generation (#1190, #1181) + - Fixed source maps with non-terminated segments (#1106) + - Enabled typescript types to be imported from the package (#1194) + - Extra DOM props have been added (#1191) + - Delete the AST while generating code, as a means to save RAM + +## v5.13.1 + - Removed self-assignments (`varname=varname`) (closes #1081) + - Separated inlining code (for inlining things into references, or removing IIFEs) + - Allow multiple identifiers with the same name in `var` destructuring (eg `var { a, a } = x`) (#1176) + +## v5.13.0 + + - All calls to eval() were removed (#1171, #1184) + - `source-map` was updated to 0.8.0-beta.0 (#1164) + - NavigatorUAData was added to domprops to avoid property mangling (#1166) + +## v5.12.1 + + - Fixed an issue with function definitions inside blocks (#1155) + - Fixed parens of `new` in some situations (closes #1159) + +## v5.12.0 + + - `TERSER_DEBUG_DIR` environment variable + - @copyright comments are now preserved with the comments="some" option (#1153) + +## v5.11.0 + + - Unicode code point escapes (`\u{abcde}`) are not emitted inside RegExp literals anymore (#1147) + - acorn is now a regular dependency + +## v5.10.0 + + - Massive optimization to max_line_len (#1109) + - Basic support for import assertions + - Marked ES2022 Object.hasOwn as a pure function + - Fix `delete optional?.property` + - New CI/CD pipeline with github actions (#1057) + - Fix reordering of switch branches (#1092), (#1084) + - Fix error when creating a class property called `get` + - Acorn dependency is now an optional peerDependency + - Fix mangling collision with exported variables (#1072) + - Fix an issue with `return someVariable = (async () => { ... })()` (#1073) + +## v5.9.0 + + - Collapsing switch cases with the same bodies (even if they're not next to each other) (#1070). + - Fix evaluation of optional chain expressions (#1062) + - Fix mangling collision in ESM exports (#1063) + - Fix issue with mutating function objects after a second pass (#1047) + - Fix for inlining object spread `{ ...obj }` (#1071) + - Typescript typings fix (#1069) + +## v5.8.0 + + - Fixed shadowing variables while moving code in some cases (#1065) + - Stop mangling computed & quoted properties when keep_quoted is enabled. + - Fix for mangling private getter/setter and .#private access (#1060, #1068) + - Array.from has a new optimization when the unsafe option is set (#737) + - Mangle/propmangle let you generate your own identifiers through the nth_identifier option (#1061) + - More optimizations to switch statements (#1044) + +## v5.7.2 + + - Fixed issues with compressing functions defined in `global_defs` option (#1036) + - New recipe for using Terser in gulp was added to RECIPES.md (#1035) + - Fixed issues with `??` and `?.` (#1045) + - Future reserved words such as `package` no longer require you to disable strict mode to be used as names. + - Refactored huge compressor file into multiple more focused files. + - Avoided unparenthesized `in` operator in some for loops (it breaks parsing because of for..in loops) + - Improved documentation (#1021, #1025) + - More type definitions (#1021) + +## v5.7.1 + + - Avoided collapsing assignments together if it would place a chain assignment on the left hand side, which is invalid syntax (`a?.b = c`) + - Removed undefined from object expansions (`{ ...void 0 }` -> `{}`) + - Fix crash when checking if something is nullish or undefined (#1009) + - Fixed comparison of private class properties (#1015) + - Minor performance improvements (#993) + - Fixed scope of function defs in strict mode (they are block scoped) + +## v5.7.0 + + - Several compile-time evaluation and inlining fixes + - Allow `reduce_funcs` to be disabled again. + - Add `spidermonkey` options to parse and format (#974) + - Accept `{get = "default val"}` and `{set = "default val"}` in destructuring arguments. + - Change package.json export map to help require.resolve (#971) + - Improve docs + - Fix `export default` of an anonymous class with `extends` + +## v5.6.1 + + - Mark assignments to the `.prototype` of a class as pure + - Parenthesize `await` on the left of `**` (while accepting legacy non-parenthesised input) + - Avoided outputting NUL bytes in optimized RegExps, to stop the output from breaking other tools + - Added `exports` to domprops (#939) + - Fixed a crash when spreading `...this` + - Fixed the computed size of arrow functions, which improves their inlining + +## v5.6.0 + + - Added top-level await + - Beautify option has been removed in #895 + - Private properties, getters and setters have been added in #913 and some more commits + - Docs improvements: #896, #903, #916 + +## v5.5.1 + + - Fixed object properties with unicode surrogates on safari. + +## v5.5.0 + + - Fixed crash when inlining uninitialized variable into template string. + - The sourcemap for dist was removed for being too large. + +## v5.4.0 + + - Logical assignment + - Change `let x = undefined` to just `let x` + - Removed some optimizations for template strings, placing them behind `unsafe` options. Reason: adding strings is not equivalent to template strings, due to valueOf differences. + - The AST_Token class was slimmed down in order to use less memory. + +## v5.3.8 + + - Restore node 13 support + +## v5.3.7 + +Hotfix release, fixes package.json "engines" syntax + +## v5.3.6 + + - Fixed parentheses when outputting `??` mixed with `||` and `&&` + - Improved hygiene of the symbol generator + +## v5.3.5 + + - Avoid moving named functions into default exports. + - Enabled transform() for chain expressions. This allows AST transformers to reach inside chain expressions. + +## v5.3.4 + + - Fixed a crash when hoisting (with `hoist_vars`) a destructuring variable declaration + +## v5.3.3 + + - `source-map` library has been updated, bringing memory usage and CPU time improvements when reading input source maps (the SourceMapConsumer is now WASM based). + - The `wrap_func_args` option now also wraps arrow functions, as opposed to only function expressions. + +## v5.3.2 + + - Prevented spread operations from being expanded when the expanded array/object contains getters, setters, or array holes. + - Fixed _very_ slow self-recursion in some cases of removing extraneous parentheses from `+` operations. + +## v5.3.1 + + - An issue with destructuring declarations when `pure_getters` is enabled has been fixed + - Fixed a crash when chain expressions need to be shallowly compared + - Made inlining functions more conservative to make sure a function that contains a reference to itself isn't moved into a place that can create multiple instances of itself. + +## v5.3.0 + + - Fixed a crash when compressing object spreads in some cases + - Fixed compiletime evaluation of optional chains (caused typeof a?.b to always return "object") + - domprops has been updated to contain every single possible prop + +## v5.2.1 + + - The parse step now doesn't accept an `ecma` option, so that all ES code is accepted. + - Optional dotted chains now accept keywords, just like dotted expressions (`foo?.default`) + +## v5.2.0 + + - Optional chaining syntax is now supported. + - Consecutive await expressions don't have unnecessary parens + - Taking the variable name's length (after mangling) into consideration when deciding to inline + +## v5.1.0 + + - `import.meta` is now supported + - Typescript typings have been improved + +## v5.0.0 + + - `in` operator now taken into account during property mangle. + - Fixed infinite loop in face of a reference loop in some situations. + - Kept exports and imports around even if there's something which will throw before them. + - The main exported bundle for commonjs, dist/bundle.min.js is no longer minified. + +## v5.0.0-beta.0 + + - BREAKING: `minify()` is now async and rejects a promise instead of returning an error. + - BREAKING: Internal AST is no longer exposed, so that it can be improved without releasing breaking changes. + - BREAKING: Lowest supported node version is 10 + - BREAKING: There are no more warnings being emitted + - Module is now distributed as a dual package - You can `import` and `require()` too. + - Inline improvements were made + + +----- + +## v4.8.1 (backport) + + - Security fix for RegExps that should not be evaluated (regexp DDOS) + +## v4.8.0 + + - Support for numeric separators (`million = 1_000_000`) was added. + - Assigning properties to a class is now assumed to be pure. + - Fixed bug where `yield` wasn't considered a valid property key in generators. + +## v4.7.0 + + - A bug was fixed where an arrow function would have the wrong size + - `arguments` object is now considered safe to retrieve properties from (useful for `length`, or `0`) even when `pure_getters` is not set. + - Fixed erroneous `const` declarations without value (which is invalid) in some corner cases when using `collapse_vars`. + +## v4.6.13 + + - Fixed issue where ES5 object properties were being turned into ES6 object properties due to more lax unicode rules. + - Fixed parsing of BigInt with lowercase `e` in them. + +## v4.6.12 + + - Fixed subtree comparison code, making it see that `[1,[2, 3]]` is different from `[1, 2, [3]]` + - Printing of unicode identifiers has been improved + +## v4.6.11 + + - Read unused classes' properties and method keys, to figure out if they use other variables. + - Prevent inlining into block scopes when there are name collisions + - Functions are no longer inlined into parameter defaults, because they live in their own special scope. + - When inlining identity functions, take into account the fact they may be used to drop `this` in function calls. + - Nullish coalescing operator (`x ?? y`), plus basic optimization for it. + - Template literals in binary expressions such as `+` have been further optimized + +## v4.6.10 + + - Do not use reduce_vars when classes are present + +## v4.6.9 + + - Check if block scopes actually exist in blocks + +## v4.6.8 + + - Take into account "executed bits" of classes like static properties or computed keys, when checking if a class evaluation might throw or have side effects. + +## v4.6.7 + + - Some new performance gains through a `AST_Node.size()` method which measures a node's source code length without printing it to a string first. + - An issue with setting `--comments` to `false` in the CLI has been fixed. + - Fixed some issues with inlining + - `unsafe_symbols` compress option was added, which turns `Symbol("name")` into just `Symbol()` + - Brought back compress performance improvement through the `AST_Node.equivalent_to(other)` method (which was reverted in v4.6.6). + +## v4.6.6 + +(hotfix release) + + - Reverted code to 4.6.4 to allow for more time to investigate an issue. + +## v4.6.5 (REVERTED) + + - Improved compress performance through using a new method to see if two nodes are equivalent, instead of printing them to a string. + +## v4.6.4 + + - The `"some"` value in the `comments` output option now preserves `@lic` and other important comments when using `//` + - `` is now better escaped in regex, and in comments, when using the `inline_script` output option + - Fixed an issue when transforming `new RegExp` into `/.../` when slashes are included in the source + - `AST_Node.prototype.constructor` now exists, allowing for easier debugging of crashes + - Multiple if statements with the same consequents are now collapsed + - Typescript typings improvements + - Optimizations while looking for surrogate pairs in strings + +## v4.6.3 + + - Annotations such as `/*#__NOINLINE__*/` and `/*#__PURE__*/` may now be preserved using the `preserve_annotations` output option + - A TypeScript definition update for the `keep_quoted` output option. + +## v4.6.2 + + - A bug where functions were inlined into other functions with scope conflicts has been fixed. + - `/*#__NOINLINE__*/` annotation fixed for more use cases where inlining happens. + +## v4.6.1 + + - Fixed an issue where a class is duplicated by reduce_vars when there's a recursive reference to the class. + +## v4.6.0 + + - Fixed issues with recursive class references. + - BigInt evaluation has been prevented, stopping Terser from evaluating BigInts like it would do regular numbers. + - Class property support has been added + +## v4.5.1 + +(hotfix release) + + - Fixed issue where `() => ({})[something]` was not parenthesised correctly. + +## v4.5.0 + + - Inlining has been improved + - An issue where keep_fnames combined with functions declared through variables was causing name shadowing has been fixed + - You can now set the ES version through their year + - The output option `keep_numbers` has been added, which prevents Terser from turning `1000` into `1e3` and such + - Internal small optimisations and refactors + +## v4.4.3 + + - Number and BigInt parsing has been fixed + - `/*#__INLINE__*/` annotation fixed for arrow functions with non-block bodies. + - Functional tests have been added, using [this repository](https://github.com/terser/terser-functional-tests). + - A memory leak, where the entire AST lives on after compression, has been plugged. + +## v4.4.2 + + - Fixed a problem with inlining identity functions + +## v4.4.1 + +*note:* This introduced a feature, therefore it should have been a minor release. + + - Fixed a crash when `unsafe` was enabled. + - An issue has been fixed where `let` statements might be collapsed out of their scope. + - Some error messages have been improved by adding quotes around variable names. + +## v4.4.0 + + - Added `/*#__INLINE__*/` and `/*#__NOINLINE__*/` annotations for calls. If a call has one of these, it either forces or forbids inlining. + +## v4.3.11 + + - Fixed a problem where `window` was considered safe to access, even though there are situations where it isn't (Node.js, workers...) + - Fixed an error where `++` and `--` were considered side-effect free + - `Number(x)` now needs both `unsafe` and and `unsafe_math` to be compressed into `+x` because `x` might be a `BigInt` + - `keep_fnames` now correctly supports regexes when the function is in a variable declaration + +## v4.3.10 + + - Fixed syntax error when repeated semicolons were encountered in classes + - Fixed invalid output caused by the creation of empty sequences internally + - Scopes are now updated when scopes are inlined into them + +## v4.3.9 + - Fixed issue with mangle's `keep_fnames` option, introduced when adding code to keep variable names of anonymous functions + +## v4.3.8 + + - Typescript typings fix + +## v4.3.7 + + - Parsing of regex options in the CLI (which broke in v4.3.5) was fixed. + - typescript definition updates + +## v4.3.6 + +(crash hotfix) + +## v4.3.5 + + - Fixed an issue with DOS line endings strings separated by `\` and a new line. + - Improved fix for the output size regression related to unused references within the extends section of a class. + - Variable names of anonymous functions (eg: `const x = () => { ... }` or `var func = function () {...}`) are now preserved when keep_fnames is true. + - Fixed performance degradation introduced for large payloads in v4.2.0 + +## v4.3.4 + + - Fixed a regression where the output size was increased when unused classes were referred to in the extends clause of a class. + - Small typescript typings fixes. + - Comments with `@preserve`, `@license`, `@cc_on` as well as comments starting with `/*!` and `/**!` are now preserved by default. + +## v4.3.3 + + - Fixed a problem where parsing template strings would mix up octal notation and a slash followed by a zero representing a null character. + - Started accepting the name `async` in destructuring arguments with default value. + - Now Terser takes into account side effects inside class `extends` clauses. + - Added parens whenever there's a comment between a return statement and the returned value, to prevent issues with ASI. + - Stopped using raw RegExp objects, since the spec is going to continue to evolve. This ensures Terser is able to process new, unknown RegExp flags and features. This is a breaking change in the AST node AST_RegExp. + +## v4.3.2 + + - Typescript typing fix + - Ensure that functions can't be inlined, by reduce_vars, into places where they're accessing variables with the same name, but from somewhere else. + +## v4.3.1 + + - Fixed an issue from 4.3.0 where any block scope within a for loop erroneously had its parent set to the function scopee + - Fixed an issue where compressing IIFEs with argument expansions would result in some parameters becoming undefined + - addEventListener options argument's properties are now part of the DOM properties list. + +## v4.3.0 + + - Do not drop computed object keys with side effects + - Functions passed to other functions in calls are now wrapped in parentheses by default, which speeds up loading most modules + - Objects with computed properties are now less likely to be hoisted + - Speed and memory efficiency optimizations + - Fixed scoping issues with `try` and `switch` + +## v4.2.1 + + - Minor refactors + - Fixed a bug similar to #369 in collapse_vars + - Functions can no longer be inlined into a place where they're going to be compared with themselves. + - reduce_funcs option is now legacy, as using reduce_vars without reduce_funcs caused some weird corner cases. As a result, it is now implied in reduce_vars and can't be turned off without turning off reduce_vars. + - Bug which would cause a random stack overflow has now been fixed. + +## v4.2.0 + + - When the source map URL is `inline`, don't write it to a file. + - Fixed output parens when a lambda literal is the tag on a tagged template string. + - The `mangle.properties.undeclared` option was added. This enables the property mangler to mangle properties of variables which can be found in the name cache, but whose properties are not known to this Terser run. + - The v8 bug where the toString and source representations of regexes like `RegExp("\\\n")` includes an actual newline is now fixed. + - Now we're guaranteed to not have duplicate comments in the output + - Domprops updates + +## v4.1.4 + + - Fixed a crash when inlining a function into somewhere else when it has interdependent, non-removable variables. + +## v4.1.3 + + - Several issues with the `reduce_vars` option were fixed. + - Starting this version, we only have a dist/bundle.min.js + +## v4.1.2 + + - The hotfix was hotfixed + +## v4.1.1 + + - Fixed a bug where toplevel scopes were being mixed up with lambda scopes + +## v4.1.0 + + - Internal functions were replaced by `Object.assign`, `Array.prototype.some`, `Array.prototype.find` and `Array.prototype.every`. + - A serious issue where some ESM-native code was broken was fixed. + - Performance improvements were made. + - Support for BigInt was added. + - Inline efficiency was improved. Functions are now being inlined more proactively instead of being inlined only after another Compressor pass. + +## v4.0.2 + +(Hotfix release. Reverts unmapped segments PR [#342](https://github.com/terser/terser/pull/342), which will be put back on Terser when the upstream issue is resolved) + +## v4.0.1 + + - Collisions between the arguments of inlined functions and names in the outer scope are now being avoided while inlining + - Unmapped segments are now preserved when compressing a file which has source maps + - Default values of functions are now correctly converted from Mozilla AST to Terser AST + - JSON ⊂ ECMAScript spec (if you don't know what this is you don't need to) + - Export AST_* classes to library users + - Fixed issue with `collapse_vars` when functions are created with the same name as a variable which already exists + - Added `MutationObserverInit` (Object with options for initialising a mutation observer) properties to the DOM property list + - Custom `Error` subclasses are now internally used instead of old-school Error inheritance hacks. + - Documentation fixes + - Performance optimizations + +## v4.0.0 + + - **breaking change**: The `variables` property of all scopes has become a standard JavaScript `Map` as opposed to the old bespoke `Dictionary` object. + - Typescript definitions were fixed + - `terser --help` was fixed + - The public interface was cleaned up + - Fixed optimisation of `Array` and `new Array` + - Added the `keep_quoted=strict` mode to mangle_props, which behaves more like Google Closure Compiler by mangling all unquoted property names, instead of reserving quoted property names automatically. + - Fixed parent functions' parameters being shadowed in some cases + - Allowed Terser to run in a situation where there are custom functions attached to Object.prototype + - And more bug fixes, optimisations and internal changes + +## v3.17.0 + + - More DOM properties added to --mangle-properties's DOM property list + - Closed issue where if 2 functions had the same argument name, Terser would not inline them together properly + - Fixed issue with `hasOwnProperty.call` + - You can now list files to minify in a Terser config file + - Started replacing `new Array()` with an array literal + - Started using ES6 capabilities like `Set` and the `includes` method for strings and arrays + +## v3.16.1 + + - Fixed issue where Terser being imported with `import` would cause it not to work due to the `__esModule` property. (PR #254 was submitted, which was nice, but since it wasn't a pure commonJS approach I decided to go with my own solution) + +## v3.16.0 + + - No longer leaves names like Array or Object or window as a SimpleStatement (statement which is just a single expression). + - Add support for sections sourcemaps (IndexedSourceMapConsumer) + - Drops node.js v4 and starts using commonJS + - Is now built with rollup + +## v3.15.0 + + - Inlined spread syntax (`[...[1, 2, 3], 4, 5] => [1, 2, 3, 4, 5]`) in arrays and objects. + - Fixed typo in compressor warning + - Fixed inline source map input bug + - Fixed parsing of template literals with unnecessary escapes (Like `\\a`) diff --git a/node_modules/terser/LICENSE b/node_modules/terser/LICENSE new file mode 100644 index 0000000..3b07e94 --- /dev/null +++ b/node_modules/terser/LICENSE @@ -0,0 +1,27 @@ +Copyright 2012-2018 (c) Mihai Bazon + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, +OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. diff --git a/node_modules/terser/PATRONS.md b/node_modules/terser/PATRONS.md new file mode 100644 index 0000000..3df7715 --- /dev/null +++ b/node_modules/terser/PATRONS.md @@ -0,0 +1,15 @@ +# Our patrons + +These are the first-tier patrons from Patreon (notice: **The Terser Patreon is shutting down in favor of opencollective**). My appreciation goes to everyone on this list for supporting the project! + + * 38elements + * Alan Orozco + * Aria Buckles + * CKEditor + * Mariusz Nowak + * Nakshatra Mukhopadhyay + * Philippe Léger + * Piotrek Koszuliński + * Serhiy Shyyko + * Viktor Hubert + * 龙腾道 diff --git a/node_modules/terser/README.md b/node_modules/terser/README.md new file mode 100644 index 0000000..84541c8 --- /dev/null +++ b/node_modules/terser/README.md @@ -0,0 +1,1421 @@ +

Terser

+ + [![NPM Version][npm-image]][npm-url] + [![NPM Downloads][downloads-image]][downloads-url] + [![CI pipeline][ci-image]][ci-url] + [![Opencollective financial contributors][opencollective-contributors]][opencollective-url] + +A JavaScript mangler/compressor toolkit for ES6+. + +*note*: You can support this project on patreon: [link] **The Terser Patreon is shutting down in favor of opencollective**. Check out [PATRONS.md](https://github.com/terser/terser/blob/master/PATRONS.md) for our first-tier patrons. + +Terser recommends you use RollupJS to bundle your modules, as that produces smaller code overall. + +*Beautification* has been undocumented and is *being removed* from terser, we recommend you use [prettier](https://npmjs.com/package/prettier). + +Find the changelog in [CHANGELOG.md](https://github.com/terser/terser/blob/master/CHANGELOG.md) + + + +[npm-image]: https://img.shields.io/npm/v/terser.svg +[npm-url]: https://npmjs.org/package/terser +[downloads-image]: https://img.shields.io/npm/dm/terser.svg +[downloads-url]: https://npmjs.org/package/terser +[ci-image]: https://github.com/terser/terser/actions/workflows/ci.yml/badge.svg +[ci-url]: https://github.com/terser/terser/actions/workflows/ci.yml +[opencollective-contributors]: https://opencollective.com/terser/tiers/badge.svg +[opencollective-url]: https://opencollective.com/terser + +Why choose terser? +------------------ + +`uglify-es` is [no longer maintained](https://github.com/mishoo/UglifyJS2/issues/3156#issuecomment-392943058) and `uglify-js` does not support ES6+. + +**`terser`** is a fork of `uglify-es` that mostly retains API and CLI compatibility +with `uglify-es` and `uglify-js@3`. + +Install +------- + +First make sure you have installed the latest version of [node.js](http://nodejs.org/) +(You may need to restart your computer after this step). + +From NPM for use as a command line app: + + npm install terser -g + +From NPM for programmatic use: + + npm install terser + +# Command line usage + + + +``` +terser [input files] [options] +``` + +Terser can take multiple input files. It's recommended that you pass the +input files first, then pass the options. Terser will parse input files +in sequence and apply any compression options. The files are parsed in the +same global scope, that is, a reference from a file to some +variable/function declared in another file will be matched properly. + +Command line arguments that take options (like --parse, --compress, --mangle and +--format) can take in a comma-separated list of default option overrides. For +instance: + + terser input.js --compress ecma=2015,computed_props=false + +If no input file is specified, Terser will read from STDIN. + +If you wish to pass your options before the input files, separate the two with +a double dash to prevent input files being used as option arguments: + + terser --compress --mangle -- input.js + +### Command line options + +``` + -h, --help Print usage information. + `--help options` for details on available options. + -V, --version Print version number. + -p, --parse Specify parser options: + `acorn` Use Acorn for parsing. + `bare_returns` Allow return outside of functions. + Useful when minifying CommonJS + modules and Userscripts that may + be anonymous function wrapped (IIFE) + by the .user.js engine `caller`. + `expression` Parse a single expression, rather than + a program (for parsing JSON). + `spidermonkey` Assume input files are SpiderMonkey + AST format (as JSON). + -c, --compress [options] Enable compressor/specify compressor options: + `pure_funcs` List of functions that can be safely + removed when their return values are + not used. + -m, --mangle [options] Mangle names/specify mangler options: + `reserved` List of names that should not be mangled. + --mangle-props [options] Mangle properties/specify mangler options: + `builtins` Mangle property names that overlaps + with standard JavaScript globals and DOM + API props. + `debug` Add debug prefix and suffix. + `keep_quoted` Only mangle unquoted properties, quoted + properties are automatically reserved. + `strict` disables quoted properties + being automatically reserved. + `regex` Only mangle matched property names. + `only_annotated` Only mangle properties defined with /*@__MANGLE_PROP__*/. + `reserved` List of names that should not be mangled. + -f, --format [options] Specify format options. + `preamble` Preamble to prepend to the output. You + can use this to insert a comment, for + example for licensing information. + This will not be parsed, but the source + map will adjust for its presence. + `quote_style` Quote style: + 0 - auto + 1 - single + 2 - double + 3 - original + `wrap_iife` Wrap IIFEs in parenthesis. Note: you may + want to disable `negate_iife` under + compressor options. + `wrap_func_args` Wrap function arguments in parenthesis. + -o, --output Output file path (default STDOUT). Specify `ast` or + `spidermonkey` to write Terser or SpiderMonkey AST + as JSON to STDOUT respectively. + --comments [filter] Preserve copyright comments in the output. By + default this works like Google Closure, keeping + JSDoc-style comments that contain e.g. "@license", + or start with "!". You can optionally pass one of the + following arguments to this flag: + - "all" to keep all comments + - `false` to omit comments in the output + - a valid JS RegExp like `/foo/` or `/^!/` to + keep only matching comments. + Note that currently not *all* comments can be + kept when compression is on, because of dead + code removal or cascading statements into + sequences. + --config-file Read `minify()` options from JSON file. + -d, --define [=value] Global definitions. + --ecma Specify ECMAScript release: 5, 2015, 2016, etc. + -e, --enclose [arg[:value]] Embed output in a big function with configurable + arguments and values. + --ie8 Support non-standard Internet Explorer 8. + Equivalent to setting `ie8: true` in `minify()` + for `compress`, `mangle` and `format` options. + By default Terser will not try to be IE-proof. + --keep-classnames Do not mangle/drop class names. + --keep-fnames Do not mangle/drop function names. Useful for + code relying on Function.prototype.name. + --module Input is an ES6 module. If `compress` or `mangle` is + enabled then the `toplevel` option, as well as strict mode, + will be enabled. + --name-cache File to hold mangled name mappings. + --safari10 Support non-standard Safari 10/11. + Equivalent to setting `safari10: true` in `minify()` + for `mangle` and `format` options. + By default `terser` will not work around + Safari 10/11 bugs. + --source-map [options] Enable source map/specify source map options: + `base` Path to compute relative paths from input files. + `content` Input source map, useful if you're compressing + JS that was generated from some other original + code. Specify "inline" if the source map is + included within the sources. + `filename` Name and/or location of the output source. + `includeSources` Pass this flag if you want to include + the content of source files in the + source map as sourcesContent property. + `root` Path to the original source to be included in + the source map. + `url` If specified, path to the source map to append in + `//# sourceMappingURL`. + --timings Display operations run time on STDERR. + --toplevel Compress and/or mangle variables in top level scope. + --wrap Embed everything in a big function, making the + “exports” and “global” variables available. You + need to pass an argument to this option to + specify the name that your module will take + when included in, say, a browser. +``` + +Specify `--output` (`-o`) to declare the output file. Otherwise the output +goes to STDOUT. + +## CLI source map options + +Terser can generate a source map file, which is highly useful for +debugging your compressed JavaScript. To get a source map, pass +`--source-map --output output.js` (source map will be written out to +`output.js.map`). + +Additional options: + +- `--source-map "filename=''"` to specify the name of the source map. + +- `--source-map "root=''"` to pass the URL where the original files can be found. + +- `--source-map "url=''"` to specify the URL where the source map can be found. + Otherwise Terser assumes HTTP `X-SourceMap` is being used and will omit the + `//# sourceMappingURL=` directive. + +For example: + + terser js/file1.js js/file2.js \ + -o foo.min.js -c -m \ + --source-map "root='http://foo.com/src',url='foo.min.js.map'" + +The above will compress and mangle `file1.js` and `file2.js`, will drop the +output in `foo.min.js` and the source map in `foo.min.js.map`. The source +mapping will refer to `http://foo.com/src/js/file1.js` and +`http://foo.com/src/js/file2.js` (in fact it will list `http://foo.com/src` +as the source map root, and the original files as `js/file1.js` and +`js/file2.js`). + +### Composed source map + +When you're compressing JS code that was output by a compiler such as +CoffeeScript, mapping to the JS code won't be too helpful. Instead, you'd +like to map back to the original code (i.e. CoffeeScript). Terser has an +option to take an input source map. Assuming you have a mapping from +CoffeeScript → compiled JS, Terser can generate a map from CoffeeScript → +compressed JS by mapping every token in the compiled JS to its original +location. + +To use this feature pass `--source-map "content='/path/to/input/source.map'"` +or `--source-map "content=inline"` if the source map is included inline with +the sources. + +## CLI compress options + +You need to pass `--compress` (`-c`) to enable the compressor. Optionally +you can pass a comma-separated list of [compress options](#compress-options). + +Options are in the form `foo=bar`, or just `foo` (the latter implies +a boolean option that you want to set `true`; it's effectively a +shortcut for `foo=true`). + +Example: + + terser file.js -c toplevel,sequences=false + +## CLI mangle options + +To enable the mangler you need to pass `--mangle` (`-m`). The following +(comma-separated) options are supported: + +- `toplevel` (default `false`) -- mangle names declared in the top level scope. + +- `eval` (default `false`) -- mangle names visible in scopes where `eval` or `with` are used. + +When mangling is enabled but you want to prevent certain names from being +mangled, you can declare those names with `--mangle reserved` — pass a +comma-separated list of names. For example: + + terser ... -m reserved=['$','require','exports'] + +to prevent the `require`, `exports` and `$` names from being changed. + +### CLI mangling property names (`--mangle-props`) + +**Note:** THIS **WILL** BREAK YOUR CODE. A good rule of thumb is not to use this unless you know exactly what you're doing and how this works and read this section until the end. + +Mangling property names is a separate step, different from variable name mangling. Pass +`--mangle-props` to enable it. The least dangerous +way to use this is to use the `regex` option like so: + +``` +terser example.js -c -m --mangle-props regex=/_$/ +``` + +This will mangle all properties that end with an +underscore. So you can use it to mangle internal methods. + +By default, it will mangle all properties in the +input code with the exception of built in DOM properties and properties +in core JavaScript classes, which is what will break your code if you don't: + +1. Control all the code you're mangling +2. Avoid using a module bundler, as they usually will call Terser on each file individually, making it impossible to pass mangled objects between modules. +3. Avoid calling functions like `defineProperty` or `hasOwnProperty`, because they refer to object properties using strings and will break your code if you don't know what you are doing. + +An example: + +```javascript +// example.js +var x = { + baz_: 0, + foo_: 1, + calc: function() { + return this.foo_ + this.baz_; + } +}; +x.bar_ = 2; +x["baz_"] = 3; +console.log(x.calc()); +``` +Mangle all properties (except for JavaScript `builtins`) (**very** unsafe): +```bash +$ terser example.js -c passes=2 -m --mangle-props +``` +```javascript +var x={o:3,t:1,i:function(){return this.t+this.o},s:2};console.log(x.i()); +``` +Mangle all properties except for `reserved` properties (still very unsafe): +```bash +$ terser example.js -c passes=2 -m --mangle-props reserved=[foo_,bar_] +``` +```javascript +var x={o:3,foo_:1,t:function(){return this.foo_+this.o},bar_:2};console.log(x.t()); +``` +Mangle all properties matching a `regex` (not as unsafe but still unsafe): +```bash +$ terser example.js -c passes=2 -m --mangle-props regex=/_$/ +``` +```javascript +var x={o:3,t:1,calc:function(){return this.t+this.o},i:2};console.log(x.calc()); +``` + +Combining mangle properties options: +```bash +$ terser example.js -c passes=2 -m --mangle-props regex=/_$/,reserved=[bar_] +``` +```javascript +var x={o:3,t:1,calc:function(){return this.t+this.o},bar_:2};console.log(x.calc()); +``` + +In order for this to be of any use, we avoid mangling standard JS names and DOM +API properties by default (`--mangle-props builtins` to override). + +A regular expression can be used to define which property names should be +mangled. For example, `--mangle-props regex=/^_/` will only mangle property +names that start with an underscore. + +When you compress multiple files using this option, in order for them to +work together in the end we need to ensure somehow that one property gets +mangled to the same name in all of them. For this, pass `--name-cache filename.json` +and Terser will maintain these mappings in a file which can then be reused. +It should be initially empty. Example: + +```bash +$ rm -f /tmp/cache.json # start fresh +$ terser file1.js file2.js --mangle-props --name-cache /tmp/cache.json -o part1.js +$ terser file3.js file4.js --mangle-props --name-cache /tmp/cache.json -o part2.js +``` + +Now, `part1.js` and `part2.js` will be consistent with each other in terms +of mangled property names. + +Using the name cache is not necessary if you compress all your files in a +single call to Terser. + +### Mangling unquoted names (`--mangle-props keep_quoted`) + +Using quoted property name (`o["foo"]`) reserves the property name (`foo`) +so that it is not mangled throughout the entire script even when used in an +unquoted style (`o.foo`). Example: + +```javascript +// stuff.js +var o = { + "foo": 1, + bar: 3 +}; +o.foo += o.bar; +console.log(o.foo); +``` +```bash +$ terser stuff.js --mangle-props keep_quoted -c -m +``` +```javascript +var o={foo:1,o:3};o.foo+=o.o,console.log(o.foo); +``` + +### Debugging property name mangling + +You can also pass `--mangle-props debug` in order to mangle property names +without completely obscuring them. For example the property `o.foo` +would mangle to `o._$foo$_` with this option. This allows property mangling +of a large codebase while still being able to debug the code and identify +where mangling is breaking things. + +```bash +$ terser stuff.js --mangle-props debug -c -m +``` +```javascript +var o={_$foo$_:1,_$bar$_:3};o._$foo$_+=o._$bar$_,console.log(o._$foo$_); +``` + +You can also pass a custom suffix using `--mangle-props debug=XYZ`. This would then +mangle `o.foo` to `o._$foo$XYZ_`. You can change this each time you compile a +script to identify how a property got mangled. One technique is to pass a +random number on every compile to simulate mangling changing with different +inputs (e.g. as you update the input script with new properties), and to help +identify mistakes like writing mangled keys to storage. + + + +# API Reference + + + +Assuming installation via NPM, you can load Terser in your application +like this: + +```javascript +const { minify } = require("terser"); +``` + +Or, + +```javascript +import { minify } from "terser"; +``` + +Browser loading is also supported. It exposes a global variable `Terser` containing a `.minify` property: +```html + + +``` + +There is an async high level function, **`async minify(code, options)`**, +which will perform all minification [phases](#minify-options) in a configurable +manner. By default `minify()` will enable [`compress`](#compress-options) +and [`mangle`](#mangle-options). Example: +```javascript +var code = "function add(first, second) { return first + second; }"; +var result = await minify(code, { sourceMap: true }); +console.log(result.code); // minified output: function add(n,d){return n+d} +console.log(result.map); // source map +``` + +There is also a `minify_sync()` alternative version of it, which returns instantly. + +You can `minify` more than one JavaScript file at a time by using an object +for the first argument where the keys are file names and the values are source +code: +```javascript +var code = { + "file1.js": "function add(first, second) { return first + second; }", + "file2.js": "console.log(add(1 + 2, 3 + 4));" +}; +var result = await minify(code); +console.log(result.code); +// function add(d,n){return d+n}console.log(add(3,7)); +``` + +The `toplevel` option: +```javascript +var code = { + "file1.js": "function add(first, second) { return first + second; }", + "file2.js": "console.log(add(1 + 2, 3 + 4));" +}; +var options = { toplevel: true }; +var result = await minify(code, options); +console.log(result.code); +// console.log(3+7); +``` + +The `nameCache` option: +```javascript +var options = { + mangle: { + toplevel: true, + }, + nameCache: {} +}; +var result1 = await minify({ + "file1.js": "function add(first, second) { return first + second; }" +}, options); +var result2 = await minify({ + "file2.js": "console.log(add(1 + 2, 3 + 4));" +}, options); +console.log(result1.code); +// function n(n,r){return n+r} +console.log(result2.code); +// console.log(n(3,7)); +``` + +You may persist the name cache to the file system in the following way: +```javascript +var cacheFileName = "/tmp/cache.json"; +var options = { + mangle: { + properties: true, + }, + nameCache: JSON.parse(fs.readFileSync(cacheFileName, "utf8")) +}; +fs.writeFileSync("part1.js", await minify({ + "file1.js": fs.readFileSync("file1.js", "utf8"), + "file2.js": fs.readFileSync("file2.js", "utf8") +}, options).code, "utf8"); +fs.writeFileSync("part2.js", await minify({ + "file3.js": fs.readFileSync("file3.js", "utf8"), + "file4.js": fs.readFileSync("file4.js", "utf8") +}, options).code, "utf8"); +fs.writeFileSync(cacheFileName, JSON.stringify(options.nameCache), "utf8"); +``` + +An example of a combination of `minify()` options: +```javascript +var code = { + "file1.js": "function add(first, second) { return first + second; }", + "file2.js": "console.log(add(1 + 2, 3 + 4));" +}; +var options = { + toplevel: true, + compress: { + global_defs: { + "@console.log": "alert" + }, + passes: 2 + }, + format: { + preamble: "/* minified */" + } +}; +var result = await minify(code, options); +console.log(result.code); +// /* minified */ +// alert(10);" +``` + +An error example: +```javascript +try { + const result = await minify({"foo.js" : "if (0) else console.log(1);"}); + // Do something with result +} catch (error) { + const { message, filename, line, col, pos } = error; + // Do something with error +} +``` + +## Minify options + +- `ecma` (default `undefined`) - pass `5`, `2015`, `2016`, etc to override + `compress` and `format`'s `ecma` options. + +- `enclose` (default `false`) - pass `true`, or a string in the format + of `"args[:values]"`, where `args` and `values` are comma-separated + argument names and values, respectively, to embed the output in a big + function with the configurable arguments and values. + +- `parse` (default `{}`) — pass an object if you wish to specify some + additional [parse options](#parse-options). + +- `compress` (default `{}`) — pass `false` to skip compressing entirely. + Pass an object to specify custom [compress options](#compress-options). + +- `mangle` (default `true`) — pass `false` to skip mangling names, or pass + an object to specify [mangle options](#mangle-options) (see below). + + - `mangle.properties` (default `false`) — a subcategory of the mangle option. + Pass an object to specify custom [mangle property options](#mangle-properties-options). + +- `module` (default `false`) — Use when minifying an ES6 module. "use strict" + is implied and names can be mangled on the top scope. If `compress` or + `mangle` is enabled then the `toplevel` option will be enabled. + +- `format` or `output` (default `null`) — pass an object if you wish to specify + additional [format options](#format-options). The defaults are optimized + for best compression. + +- `sourceMap` (default `false`) - pass an object if you wish to specify + [source map options](#source-map-options). + +- `toplevel` (default `false`) - set to `true` if you wish to enable top level + variable and function name mangling and to drop unused variables and functions. + +- `nameCache` (default `null`) - pass an empty object `{}` or a previously + used `nameCache` object if you wish to cache mangled variable and + property names across multiple invocations of `minify()`. Note: this is + a read/write property. `minify()` will read the name cache state of this + object and update it during minification so that it may be + reused or externally persisted by the user. + +- `ie8` (default `false`) - set to `true` to support IE8. + +- `keep_classnames` (default: `undefined`) - pass `true` to prevent discarding or mangling + of class names. Pass a regular expression to only keep class names matching that regex. + +- `keep_fnames` (default: `false`) - pass `true` to prevent discarding or mangling + of function names. Pass a regular expression to only keep function names matching that regex. + Useful for code relying on `Function.prototype.name`. If the top level minify option + `keep_classnames` is `undefined` it will be overridden with the value of the top level + minify option `keep_fnames`. + +- `safari10` (default: `false`) - pass `true` to work around Safari 10/11 bugs in + loop scoping and `await`. See `safari10` options in [`mangle`](#mangle-options) + and [`format`](#format-options) for details. + +## Minify options structure + +```javascript +{ + parse: { + // parse options + }, + compress: { + // compress options + }, + mangle: { + // mangle options + + properties: { + // mangle property options + } + }, + format: { + // format options (can also use `output` for backwards compatibility) + }, + sourceMap: { + // source map options + }, + ecma: 5, // specify one of: 5, 2015, 2016, etc. + enclose: false, // or specify true, or "args:values" + keep_classnames: false, + keep_fnames: false, + ie8: false, + module: false, + nameCache: null, // or specify a name cache object + safari10: false, + toplevel: false +} +``` + +### Source map options + +To generate a source map: +```javascript +var result = await minify({"file1.js": "var a = function() {};"}, { + sourceMap: { + filename: "out.js", + url: "out.js.map" + } +}); +console.log(result.code); // minified output +console.log(result.map); // source map +``` + +Note that the source map is not saved in a file, it's just returned in +`result.map`. The value passed for `sourceMap.url` is only used to set +`//# sourceMappingURL=out.js.map` in `result.code`. The value of +`filename` is only used to set `file` attribute (see [the spec][sm-spec]) +in source map file. + +You can set option `sourceMap.url` to be `"inline"` and source map will +be appended to code. + +You can also specify sourceRoot property to be included in source map: +```javascript +var result = await minify({"file1.js": "var a = function() {};"}, { + sourceMap: { + root: "http://example.com/src", + url: "out.js.map" + } +}); +``` + +If you're compressing compiled JavaScript and have a source map for it, you +can use `sourceMap.content`: +```javascript +var result = await minify({"compiled.js": "compiled code"}, { + sourceMap: { + content: "content from compiled.js.map", + url: "minified.js.map" + } +}); +// same as before, it returns `code` and `map` +``` + +If you're using the `X-SourceMap` header instead, you can just omit `sourceMap.url`. + +If you happen to need the source map as a raw object, set `sourceMap.asObject` to `true`. + + + + + +## Parse options + +- `bare_returns` (default `false`) -- support top level `return` statements + +- `html5_comments` (default `true`) + +- `shebang` (default `true`) -- support `#!command` as the first line + +- `spidermonkey` (default `false`) -- accept a Spidermonkey (Mozilla) AST + +## Compress options + +- `defaults` (default: `true`) -- Pass `false` to disable most default + enabled `compress` transforms. Useful when you only want to enable a few + `compress` options while disabling the rest. + +- `arrows` (default: `true`) -- Class and object literal methods are converted + will also be converted to arrow expressions if the resultant code is shorter: + `m(){return x}` becomes `m:()=>x`. To do this to regular ES5 functions which + don't use `this` or `arguments`, see `unsafe_arrows`. + +- `arguments` (default: `false`) -- replace `arguments[index]` with function + parameter name whenever possible. + +- `booleans` (default: `true`) -- various optimizations for boolean context, + for example `!!a ? b : c → a ? b : c` + +- `booleans_as_integers` (default: `false`) -- Turn booleans into 0 and 1, also + makes comparisons with booleans use `==` and `!=` instead of `===` and `!==`. + +- `collapse_vars` (default: `true`) -- Collapse single-use non-constant variables, + side effects permitting. + +- `comparisons` (default: `true`) -- apply certain optimizations to binary nodes, + e.g. `!(a <= b) → a > b` (only when `unsafe_comps`), attempts to negate binary + nodes, e.g. `a = !b && !c && !d && !e → a=!(b||c||d||e)` etc. Note: `comparisons` + works best with `lhs_constants` enabled. + +- `computed_props` (default: `true`) -- Transforms constant computed properties + into regular ones: `{["computed"]: 1}` is converted to `{computed: 1}`. + +- `conditionals` (default: `true`) -- apply optimizations for `if`-s and conditional + expressions + +- `dead_code` (default: `true`) -- remove unreachable code + +- `directives` (default: `true`) -- remove redundant or non-standard directives + +- `drop_console` (default: `false`) -- Pass `true` to discard calls to + `console.*` functions. If you only want to discard a portion of console, + you can pass an array like this `['log', 'info']`, which will only discard `console.log`、 `console.info`. + +- `drop_debugger` (default: `true`) -- remove `debugger;` statements + +- `ecma` (default: `5`) -- Pass `2015` or greater to enable `compress` options that + will transform ES5 code into smaller ES6+ equivalent forms. + +- `evaluate` (default: `true`) -- attempt to evaluate constant expressions + +- `expression` (default: `false`) -- Pass `true` to preserve completion values + from terminal statements without `return`, e.g. in bookmarklets. + +- `global_defs` (default: `{}`) -- see [conditional compilation](#conditional-compilation) + +- `hoist_funs` (default: `false`) -- hoist function declarations + +- `hoist_props` (default: `true`) -- hoist properties from constant object and + array literals into regular variables subject to a set of constraints. For example: + `var o={p:1, q:2}; f(o.p, o.q);` is converted to `f(1, 2);`. Note: `hoist_props` + works best with `mangle` enabled, the `compress` option `passes` set to `2` or higher, + and the `compress` option `toplevel` enabled. + +- `hoist_vars` (default: `false`) -- hoist `var` declarations (this is `false` + by default because it seems to increase the size of the output in general) + +- `if_return` (default: `true`) -- optimizations for if/return and if/continue + +- `inline` (default: `true`) -- inline calls to function with simple/`return` statement: + - `false` -- same as `0` + - `0` -- disabled inlining + - `1` -- inline simple functions + - `2` -- inline functions with arguments + - `3` -- inline functions with arguments and variables + - `true` -- same as `3` + +- `join_vars` (default: `true`) -- join consecutive `var`, `let` and `const` statements + +- `keep_classnames` (default: `false`) -- Pass `true` to prevent the compressor from + discarding class names. Pass a regular expression to only keep class names matching + that regex. See also: the `keep_classnames` [mangle option](#mangle-options). + +- `keep_fargs` (default: `true`) -- Prevents the compressor from discarding unused + function arguments. You need this for code which relies on `Function.length`. + +- `keep_fnames` (default: `false`) -- Pass `true` to prevent the + compressor from discarding function names. Pass a regular expression to only keep + function names matching that regex. Useful for code relying on `Function.prototype.name`. + See also: the `keep_fnames` [mangle option](#mangle-options). + +- `keep_infinity` (default: `false`) -- Pass `true` to prevent `Infinity` from + being compressed into `1/0`, which may cause performance issues on Chrome. + +- `lhs_constants` (default: `true`) -- Moves constant values to the left-hand side + of binary nodes. `foo == 42 → 42 == foo` + +- `loops` (default: `true`) -- optimizations for `do`, `while` and `for` loops + when we can statically determine the condition. + +- `module` (default `false`) -- Pass `true` when compressing an ES6 module. Strict + mode is implied and the `toplevel` option as well. + +- `negate_iife` (default: `true`) -- negate "Immediately-Called Function Expressions" + where the return value is discarded, to avoid the parens that the + code generator would insert. + +- `passes` (default: `1`) -- The maximum number of times to run compress. + In some cases more than one pass leads to further compressed code. Keep in + mind more passes will take more time. + +- `properties` (default: `true`) -- rewrite property access using the dot notation, for + example `foo["bar"] → foo.bar` + +- `pure_funcs` (default: `null`) -- You can pass an array of names and + Terser will assume that those functions do not produce side + effects. DANGER: will not check if the name is redefined in scope. + An example case here, for instance `var q = Math.floor(a/b)`. If + variable `q` is not used elsewhere, Terser will drop it, but will + still keep the `Math.floor(a/b)`, not knowing what it does. You can + pass `pure_funcs: [ 'Math.floor' ]` to let it know that this + function won't produce any side effect, in which case the whole + statement would get discarded. The current implementation adds some + overhead (compression will be slower). + +- `pure_getters` (default: `"strict"`) -- If you pass `true` for + this, Terser will assume that object property access + (e.g. `foo.bar` or `foo["bar"]`) doesn't have any side effects. + Specify `"strict"` to treat `foo.bar` as side-effect-free only when + `foo` is certain to not throw, i.e. not `null` or `undefined`. + +- `pure_new` (default: `false`) -- Set to `true` to assume `new X()` never has + side effects. + +- `reduce_vars` (default: `true`) -- Improve optimization on variables assigned with and + used as constant values. + +- `reduce_funcs` (default: `true`) -- Inline single-use functions when + possible. Depends on `reduce_vars` being enabled. Disabling this option + sometimes improves performance of the output code. + +- `sequences` (default: `true`) -- join consecutive simple statements using the + comma operator. May be set to a positive integer to specify the maximum number + of consecutive comma sequences that will be generated. If this option is set to + `true` then the default `sequences` limit is `200`. Set option to `false` or `0` + to disable. The smallest `sequences` length is `2`. A `sequences` value of `1` + is grandfathered to be equivalent to `true` and as such means `200`. On rare + occasions the default sequences limit leads to very slow compress times in which + case a value of `20` or less is recommended. + +- `side_effects` (default: `true`) -- Remove expressions which have no side effects + and whose results aren't used. + +- `switches` (default: `true`) -- de-duplicate and remove unreachable `switch` branches + +- `toplevel` (default: `false`) -- drop unreferenced functions (`"funcs"`) and/or + variables (`"vars"`) in the top level scope (`false` by default, `true` to drop + both unreferenced functions and variables) + +- `top_retain` (default: `null`) -- prevent specific toplevel functions and + variables from `unused` removal (can be array, comma-separated, RegExp or + function. Implies `toplevel`) + +- `typeofs` (default: `true`) -- Transforms `typeof foo == "undefined"` into + `foo === void 0`. Note: recommend to set this value to `false` for IE10 and + earlier versions due to known issues. + +- `unsafe` (default: `false`) -- apply "unsafe" transformations + ([details](#the-unsafe-compress-option)). + +- `unsafe_arrows` (default: `false`) -- Convert ES5 style anonymous function + expressions to arrow functions if the function body does not reference `this`. + Note: it is not always safe to perform this conversion if code relies on the + the function having a `prototype`, which arrow functions lack. + This transform requires that the `ecma` compress option is set to `2015` or greater. + +- `unsafe_comps` (default: `false`) -- Reverse `<` and `<=` to `>` and `>=` to + allow improved compression. This might be unsafe when an at least one of two + operands is an object with computed values due the use of methods like `get`, + or `valueOf`. This could cause change in execution order after operands in the + comparison are switching. Compression only works if both `comparisons` and + `unsafe_comps` are both set to true. + +- `unsafe_Function` (default: `false`) -- compress and mangle `Function(args, code)` + when both `args` and `code` are string literals. + +- `unsafe_math` (default: `false`) -- optimize numerical expressions like + `2 * x * 3` into `6 * x`, which may give imprecise floating point results. + +- `unsafe_symbols` (default: `false`) -- removes keys from native Symbol + declarations, e.g `Symbol("kDog")` becomes `Symbol()`. + +- `unsafe_methods` (default: false) -- Converts `{ m: function(){} }` to + `{ m(){} }`. `ecma` must be set to `6` or greater to enable this transform. + If `unsafe_methods` is a RegExp then key/value pairs with keys matching the + RegExp will be converted to concise methods. + Note: if enabled there is a risk of getting a "`` is not a + constructor" TypeError should any code try to `new` the former function. + +- `unsafe_proto` (default: `false`) -- optimize expressions like + `Array.prototype.slice.call(a)` into `[].slice.call(a)` + +- `unsafe_regexp` (default: `false`) -- enable substitutions of variables with + `RegExp` values the same way as if they are constants. + +- `unsafe_undefined` (default: `false`) -- substitute `void 0` if there is a + variable named `undefined` in scope (variable name will be mangled, typically + reduced to a single character) + +- `unused` (default: `true`) -- drop unreferenced functions and variables (simple + direct variable assignments do not count as references unless set to `"keep_assign"`) + +## Mangle options + +- `eval` (default `false`) -- Pass `true` to mangle names visible in scopes + where `eval` or `with` are used. + +- `keep_classnames` (default `false`) -- Pass `true` to not mangle class names. + Pass a regular expression to only keep class names matching that regex. + See also: the `keep_classnames` [compress option](#compress-options). + +- `keep_fnames` (default `false`) -- Pass `true` to not mangle function names. + Pass a regular expression to only keep function names matching that regex. + Useful for code relying on `Function.prototype.name`. See also: the `keep_fnames` + [compress option](#compress-options). + +- `module` (default `false`) -- Pass `true` an ES6 modules, where the toplevel + scope is not the global scope. Implies `toplevel` and assumes input code is strict mode JS. + +- `nth_identifier` (default: an internal mangler that weights based on character + frequency analysis) -- Pass an object with a `get(n)` function that converts an + ordinal into the nth most favored (usually shortest) identifier. + Optionally also provide `reset()`, `sort()`, and `consider(chars, delta)` to + use character frequency analysis of the source code. + +- `reserved` (default `[]`) -- Pass an array of identifiers that should be + excluded from mangling. Example: `["foo", "bar"]`. + +- `toplevel` (default `false`) -- Pass `true` to mangle names declared in the + top level scope. + +- `safari10` (default `false`) -- Pass `true` to work around the Safari 10 loop + iterator [bug](https://bugs.webkit.org/show_bug.cgi?id=171041) + "Cannot declare a let variable twice". + See also: the `safari10` [format option](#format-options). + +Examples: + +```javascript +// test.js +var globalVar; +function funcName(firstLongName, anotherLongName) { + var myVariable = firstLongName + anotherLongName; +} +``` +```javascript +var code = fs.readFileSync("test.js", "utf8"); + +await minify(code).code; +// 'function funcName(a,n){}var globalVar;' + +await minify(code, { mangle: { reserved: ['firstLongName'] } }).code; +// 'function funcName(firstLongName,a){}var globalVar;' + +await minify(code, { mangle: { toplevel: true } }).code; +// 'function n(n,a){}var a;' +``` + +### Mangle properties options + +- `builtins` (default: `false`) — Use `true` to allow the mangling of builtin + DOM properties. Not recommended to override this setting. + +- `debug` (default: `false`) — Mangle names with the original name still present. + Pass an empty string `""` to enable, or a non-empty string to set the debug suffix. + +- `keep_quoted` (default: `false`) — How quoting properties (`{"prop": ...}` and `obj["prop"]`) controls what gets mangled. + - `"strict"` (recommended) -- `obj.prop` is mangled. + - `false` -- `obj["prop"]` is mangled. + - `true` -- `obj.prop` is mangled unless there is `obj["prop"]` elsewhere in the code. + +- `nth_identifer` (default: an internal mangler that weights based on character + frequency analysis) -- Pass an object with a `get(n)` function that converts an + ordinal into the nth most favored (usually shortest) identifier. + Optionally also provide `reset()`, `sort()`, and `consider(chars, delta)` to + use character frequency analysis of the source code. + +- `regex` (default: `null`) — Pass a [RegExp literal or pattern string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) to only mangle property matching the regular expression. + +- `reserved` (default: `[]`) — Do not mangle property names listed in the + `reserved` array. + +- `undeclared` (default: `false`) - Mangle those names when they are accessed + as properties of known top level variables but their declarations are never + found in input code. May be useful when only minifying parts of a project. + See [#397](https://github.com/terser/terser/issues/397) for more details. + + +## Format options + +These options control the format of Terser's output code. Previously known +as "output options". + +- `ascii_only` (default `false`) -- escape Unicode characters in strings and + regexps (affects directives with non-ascii characters becoming invalid) + +- `beautify` (default `false`) -- (DEPRECATED) whether to beautify the output. + When using the legacy `-b` CLI flag, this is set to true by default. + +- `braces` (default `false`) -- always insert braces in `if`, `for`, + `do`, `while` or `with` statements, even if their body is a single + statement. + +- `comments` (default `"some"`) -- by default it keeps JSDoc-style comments + that contain "@license", "@copyright", "@preserve" or start with `!`, pass `true` + or `"all"` to preserve all comments, `false` to omit comments in the output, + a regular expression string (e.g. `/^!/`) or a function. + +- `ecma` (default `5`) -- set desired EcmaScript standard version for output. + Set `ecma` to `2015` or greater to emit shorthand object properties - i.e.: + `{a}` instead of `{a: a}`. The `ecma` option will only change the output in + direct control of the beautifier. Non-compatible features in your input will + still be output as is. For example: an `ecma` setting of `5` will **not** + convert modern code to ES5. + +- `indent_level` (default `4`) + +- `indent_start` (default `0`) -- prefix all lines by that many spaces + +- `inline_script` (default `true`) -- escape HTML comments and the slash in + occurrences of `` in strings + +- `keep_numbers` (default `false`) -- keep number literals as it was in original code + (disables optimizations like converting `1000000` into `1e6`) + +- `keep_quoted_props` (default `false`) -- when turned on, prevents stripping + quotes from property names in object literals. + +- `max_line_len` (default `false`) -- maximum line length (for minified code) + +- `preamble` (default `null`) -- when passed it must be a string and + it will be prepended to the output literally. The source map will + adjust for this text. Can be used to insert a comment containing + licensing information, for example. + +- `quote_keys` (default `false`) -- pass `true` to quote all keys in literal + objects + +- `quote_style` (default `0`) -- preferred quote style for strings (affects + quoted property names and directives as well): + - `0` -- prefers double quotes, switches to single quotes when there are + more double quotes in the string itself. `0` is best for gzip size. + - `1` -- always use single quotes + - `2` -- always use double quotes + - `3` -- always use the original quotes + +- `preserve_annotations` -- (default `false`) -- Preserve [Terser annotations](#annotations) in the output. + +- `safari10` (default `false`) -- set this option to `true` to work around + the [Safari 10/11 await bug](https://bugs.webkit.org/show_bug.cgi?id=176685). + See also: the `safari10` [mangle option](#mangle-options). + +- `semicolons` (default `true`) -- separate statements with semicolons. If + you pass `false` then whenever possible we will use a newline instead of a + semicolon, leading to more readable output of minified code (size before + gzip could be smaller; size after gzip insignificantly larger). + +- `shebang` (default `true`) -- preserve shebang `#!` in preamble (bash scripts) + +- `spidermonkey` (default `false`) -- produce a Spidermonkey (Mozilla) AST + +- `webkit` (default `false`) -- enable workarounds for WebKit bugs. + PhantomJS users should set this option to `true`. + +- `wrap_iife` (default `false`) -- pass `true` to wrap immediately invoked + function expressions. See + [#640](https://github.com/mishoo/UglifyJS2/issues/640) for more details. + +- `wrap_func_args` (default `true`) -- pass `false` if you do not want to wrap + function expressions that are passed as arguments, in parenthesis. See + [OptimizeJS](https://github.com/nolanlawson/optimize-js) for more details. + + + + + +# Miscellaneous + + + +### Keeping copyright notices or other comments + +You can pass `--comments` to retain certain comments in the output. By +default it will keep comments starting with "!" and JSDoc-style comments that +contain "@preserve", "@copyright", "@license" or "@cc_on" (conditional compilation for IE). +You can pass `--comments all` to keep all the comments, or a valid JavaScript regexp to +keep only comments that match this regexp. For example `--comments /^!/` +will keep comments like `/*! Copyright Notice */`. + +Note, however, that there might be situations where comments are lost. For +example: +```javascript +function f() { + /** @preserve Foo Bar */ + function g() { + // this function is never called + } + return something(); +} +``` + +Even though it has "@preserve", the comment will be lost because the inner +function `g` (which is the AST node to which the comment is attached to) is +discarded by the compressor as not referenced. + +The safest comments where to place copyright information (or other info that +needs to be kept in the output) are comments attached to toplevel nodes. + +### The `unsafe` `compress` option + +It enables some transformations that *might* break code logic in certain +contrived cases, but should be fine for most code. It assumes that standard +built-in ECMAScript functions and classes have not been altered or replaced. +You might want to try it on your own code; it should reduce the minified size. +Some examples of the optimizations made when this option is enabled: + +- `new Array(1, 2, 3)` or `Array(1, 2, 3)` → `[ 1, 2, 3 ]` +- `Array.from([1, 2, 3])` → `[1, 2, 3]` +- `new Object()` → `{}` +- `String(exp)` or `exp.toString()` → `"" + exp` +- `new Object/RegExp/Function/Error/Array (...)` → we discard the `new` +- `"foo bar".substr(4)` → `"bar"` + +### Conditional compilation + +You can use the `--define` (`-d`) switch in order to declare global +variables that Terser will assume to be constants (unless defined in +scope). For example if you pass `--define DEBUG=false` then, coupled with +dead code removal Terser will discard the following from the output: +```javascript +if (DEBUG) { + console.log("debug stuff"); +} +``` + +You can specify nested constants in the form of `--define env.DEBUG=false`. + +Another way of doing that is to declare your globals as constants in a +separate file and include it into the build. For example you can have a +`build/defines.js` file with the following: +```javascript +var DEBUG = false; +var PRODUCTION = true; +// etc. +``` + +and build your code like this: + + terser build/defines.js js/foo.js js/bar.js... -c + +Terser will notice the constants and, since they cannot be altered, it +will evaluate references to them to the value itself and drop unreachable +code as usual. The build will contain the `const` declarations if you use +them. If you are targeting < ES6 environments which does not support `const`, +using `var` with `reduce_vars` (enabled by default) should suffice. + +### Conditional compilation API + +You can also use conditional compilation via the programmatic API. With the difference that the +property name is `global_defs` and is a compressor property: + +```javascript +var result = await minify(fs.readFileSync("input.js", "utf8"), { + compress: { + dead_code: true, + global_defs: { + DEBUG: false + } + } +}); +``` + +To replace an identifier with an arbitrary non-constant expression it is +necessary to prefix the `global_defs` key with `"@"` to instruct Terser +to parse the value as an expression: +```javascript +await minify("alert('hello');", { + compress: { + global_defs: { + "@alert": "console.log" + } + } +}).code; +// returns: 'console.log("hello");' +``` + +Otherwise it would be replaced as string literal: +```javascript +await minify("alert('hello');", { + compress: { + global_defs: { + "alert": "console.log" + } + } +}).code; +// returns: '"console.log"("hello");' +``` + +### Annotations + +Annotations in Terser are a way to tell it to treat a certain function call differently. The following annotations are available: + + * `/*@__INLINE__*/` - forces a function to be inlined somewhere. + * `/*@__NOINLINE__*/` - Makes sure the called function is not inlined into the call site. + * `/*@__PURE__*/` - Marks a function call as pure. That means, it can safely be dropped. + * `/*@__KEY__*/` - Marks a string literal as a property to also mangle it when mangling properties. + * `/*@__MANGLE_PROP__*/` - Opts-in an object property (or class field) for mangling, when the property mangler is enabled. + +You can use either a `@` sign at the start, or a `#`. + +Here are some examples on how to use them: + +```javascript +/*@__INLINE__*/ +function_always_inlined_here() + +/*#__NOINLINE__*/ +function_cant_be_inlined_into_here() + +const x = /*#__PURE__*/i_am_dropped_if_x_is_not_used() + +function lookup(object, key) { return object[key]; } +lookup({ i_will_be_mangled_too: "bar" }, /*@__KEY__*/ "i_will_be_mangled_too"); +``` + +### ESTree / SpiderMonkey AST + +Terser has its own abstract syntax tree format; for +[practical reasons](http://lisperator.net/blog/uglifyjs-why-not-switching-to-spidermonkey-ast/) +we can't easily change to using the SpiderMonkey AST internally. However, +Terser now has a converter which can import a SpiderMonkey AST. + +For example [Acorn][acorn] is a super-fast parser that produces a +SpiderMonkey AST. It has a small CLI utility that parses one file and dumps +the AST in JSON on the standard output. To use Terser to mangle and +compress that: + + acorn file.js | terser -p spidermonkey -m -c + +The `-p spidermonkey` option tells Terser that all input files are not +JavaScript, but JS code described in SpiderMonkey AST in JSON. Therefore we +don't use our own parser in this case, but just transform that AST into our +internal AST. + +`spidermonkey` is also available in `minify` as `parse` and `format` options to +accept and/or produce a spidermonkey AST. + +### Use Acorn for parsing + +More for fun, I added the `-p acorn` option which will use Acorn to do all +the parsing. If you pass this option, Terser will `require("acorn")`. + +Acorn is really fast (e.g. 250ms instead of 380ms on some 650K code), but +converting the SpiderMonkey tree that Acorn produces takes another 150ms so +in total it's a bit more than just using Terser's own parser. + +[acorn]: https://github.com/ternjs/acorn +[sm-spec]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k + +### Terser Fast Minify Mode + +It's not well known, but whitespace removal and symbol mangling accounts +for 95% of the size reduction in minified code for most JavaScript - not +elaborate code transforms. One can simply disable `compress` to speed up +Terser builds by 3 to 4 times. + +| d3.js | size | gzip size | time (s) | +| --- | ---: | ---: | ---: | +| original | 451,131 | 108,733 | - | +| terser@3.7.5 mangle=false, compress=false | 316,600 | 85,245 | 0.82 | +| terser@3.7.5 mangle=true, compress=false | 220,216 | 72,730 | 1.45 | +| terser@3.7.5 mangle=true, compress=true | 212,046 | 70,954 | 5.87 | +| babili@0.1.4 | 210,713 | 72,140 | 12.64 | +| babel-minify@0.4.3 | 210,321 | 72,242 | 48.67 | +| babel-minify@0.5.0-alpha.01eac1c3 | 210,421 | 72,238 | 14.17 | + +To enable fast minify mode from the CLI use: +``` +terser file.js -m +``` +To enable fast minify mode with the API use: +```js +await minify(code, { compress: false, mangle: true }); +``` + +#### Source maps and debugging + +Various `compress` transforms that simplify, rearrange, inline and remove code +are known to have an adverse effect on debugging with source maps. This is +expected as code is optimized and mappings are often simply not possible as +some code no longer exists. For highest fidelity in source map debugging +disable the `compress` option and just use `mangle`. + +When debugging, make sure you enable the **"map scopes"** feature to map mangled variable names back to their original names. +Without this, all variable values will be `undefined`. See https://github.com/terser/terser/issues/1367 for more details. +

+ +![image](https://user-images.githubusercontent.com/27283110/230441652-ac5cf6b0-5dc5-4ffc-9d8b-bd02875484f4.png) + +### Compiler assumptions + +To allow for better optimizations, the compiler makes various assumptions: + +- `.toString()` and `.valueOf()` don't have side effects, and for built-in + objects they have not been overridden. +- `undefined`, `NaN` and `Infinity` have not been externally redefined. +- `arguments.callee`, `arguments.caller` and `Function.prototype.caller` are not used. +- The code doesn't expect the contents of `Function.prototype.toString()` or + `Error.prototype.stack` to be anything in particular. +- Getting and setting properties on a plain object does not cause other side effects + (using `.watch()` or `Proxy`). +- Object properties can be added, removed and modified (not prevented with + `Object.defineProperty()`, `Object.defineProperties()`, `Object.freeze()`, + `Object.preventExtensions()` or `Object.seal()`). +- `document.all` is not `== null` +- Assigning properties to a class doesn't have side effects and does not throw. + +### Build Tools and Adaptors using Terser + +https://www.npmjs.com/browse/depended/terser + +### Replacing `uglify-es` with `terser` in a project using `yarn` + +A number of JS bundlers and uglify wrappers are still using buggy versions +of `uglify-es` and have not yet upgraded to `terser`. If you are using `yarn` +you can add the following alias to your project's `package.json` file: + +```js + "resolutions": { + "uglify-es": "npm:terser" + } +``` + +to use `terser` instead of `uglify-es` in all deeply nested dependencies +without changing any code. + +Note: for this change to take effect you must run the following commands +to remove the existing `yarn` lock file and reinstall all packages: + +``` +$ rm -rf node_modules yarn.lock +$ yarn +``` + + + +# Reporting issues + + + +## A minimal, reproducible example + +You're expected to provide a [minimal reproducible example] of input code that will demonstrate your issue. + +To get to this example, you can remove bits of your code and stop if your issue ceases to reproduce. + +## Obtaining the source code given to Terser + +Because users often don't control the call to `await minify()` or its arguments, Terser provides a `TERSER_DEBUG_DIR` environment variable to make terser output some debug logs. + +These logs will contain the input code and options of each `minify()` call. + +```bash +TERSER_DEBUG_DIR=/tmp/terser-log-dir command-that-uses-terser +ls /tmp/terser-log-dir +terser-debug-123456.log +``` + +If you're not sure how to set an environment variable on your shell (the above example works in bash), you can try using cross-env: + +``` +> npx cross-env TERSER_DEBUG_DIR=/path/to/logs command-that-uses-terser +``` + +## Stack traces + +In the terser CLI we use [source-map-support](https://npmjs.com/source-map-support) to produce good error stacks. In your own app, you're expected to enable source-map-support (read their docs) to have nice stack traces that will help you write good issues. + + + +# README.md Patrons: + +*note*: You can support this project on patreon: [link] **The Terser Patreon is shutting down in favor of opencollective**. Check out [PATRONS.md](https://github.com/terser/terser/blob/master/PATRONS.md) for our first-tier patrons. + +These are the second-tier patrons. Great thanks for your support! + + * CKEditor ![](https://c10.patreonusercontent.com/3/eyJoIjoxMDAsInciOjEwMH0%3D/patreon-media/p/user/15452278/f8548dcf48d740619071e8d614459280/1?token-time=2145916800&token-hash=SIQ54PhIPHv3M7CVz9LxS8_8v4sOw4H304HaXsXj8MM%3D) + * 38elements ![](https://c10.patreonusercontent.com/3/eyJ3IjoyMDB9/patreon-media/p/user/12501844/88e7fc5dd62d45c6a5626533bbd48cfb/1?token-time=2145916800&token-hash=c3AsQ5T0IQWic0zKxFHu-bGGQJkXQFvafvJ4bPerFR4%3D) + +## Contributors + +### Code Contributors + +This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)]. + + +### Financial Contributors + +Become a financial contributor and help us sustain our community. [[Contribute](https://opencollective.com/terser/contribute)] + +#### Individuals + + + +#### Organizations + +Support this project with your organization. Your logo will show up here with a link to your website. [[Contribute](https://opencollective.com/terser/contribute)] + + + + + + + + + + + diff --git a/node_modules/terser/bin/package.json b/node_modules/terser/bin/package.json new file mode 100644 index 0000000..d937a6f --- /dev/null +++ b/node_modules/terser/bin/package.json @@ -0,0 +1,10 @@ +{ + "name": "bin", + "private": true, + "version": "1.0.0", + "main": "terser", + "type": "commonjs", + "author": "", + "license": "BSD-2-Clause", + "description": "A package to hold the Terser bin bundle as commonjs while keeping the rest of it ESM." +} diff --git a/node_modules/terser/bin/terser b/node_modules/terser/bin/terser new file mode 100755 index 0000000..b0cdc7c --- /dev/null +++ b/node_modules/terser/bin/terser @@ -0,0 +1,21 @@ +#!/usr/bin/env node + +"use strict"; + +require("../tools/exit.cjs"); + +try { + require("source-map-support").install(); +} catch (err) {} + +const fs = require("fs"); +const path = require("path"); +const program = require("commander"); + +const packageJson = require("../package.json"); +const { _run_cli: run_cli } = require(".."); + +run_cli({ program, packageJson, fs, path }).catch((error) => { + console.error(error); + process.exitCode = 1; +}); diff --git a/node_modules/terser/bin/uglifyjs b/node_modules/terser/bin/uglifyjs new file mode 100755 index 0000000..f193025 --- /dev/null +++ b/node_modules/terser/bin/uglifyjs @@ -0,0 +1,10 @@ +#!/usr/bin/env node +// -*- js -*- +/* eslint-env node */ + +"use strict"; + +process.stderr.write( "DEPRECATION WARNING: uglifyjs binary will soon be discontinued!\n"); +process.stderr.write("Please use \"terser\" instead.\n\n"); + +require("./terser"); diff --git a/node_modules/terser/dist/.gitkeep b/node_modules/terser/dist/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/terser/dist/bundle.min.js b/node_modules/terser/dist/bundle.min.js new file mode 100644 index 0000000..aaf2d5e --- /dev/null +++ b/node_modules/terser/dist/bundle.min.js @@ -0,0 +1,32619 @@ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@jridgewell/source-map')) : +typeof define === 'function' && define.amd ? define(['exports', '@jridgewell/source-map'], factory) : +(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Terser = {}, global.sourceMap)); +}(this, (function (exports, sourceMap) { 'use strict'; + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +function characters(str) { + return str.split(""); +} + +function member(name, array) { + return array.includes(name); +} + +class DefaultsError extends Error { + constructor(msg, defs) { + super(); + + this.name = "DefaultsError"; + this.message = msg; + this.defs = defs; + } +} + +function defaults(args, defs, croak) { + if (args === true) { + args = {}; + } else if (args != null && typeof args === "object") { + args = {...args}; + } + + const ret = args || {}; + + if (croak) for (const i in ret) if (HOP(ret, i) && !HOP(defs, i)) { + throw new DefaultsError("`" + i + "` is not a supported option", defs); + } + + for (const i in defs) if (HOP(defs, i)) { + if (!args || !HOP(args, i)) { + ret[i] = defs[i]; + } else if (i === "ecma") { + let ecma = args[i] | 0; + if (ecma > 5 && ecma < 2015) ecma += 2009; + ret[i] = ecma; + } else { + ret[i] = (args && HOP(args, i)) ? args[i] : defs[i]; + } + } + + return ret; +} + +function noop() {} +function return_false() { return false; } +function return_true() { return true; } +function return_this() { return this; } +function return_null() { return null; } + +var MAP = (function() { + function MAP(a, tw, allow_splicing = true) { + const new_a = []; + + for (let i = 0; i < a.length; ++i) { + let item = a[i]; + let ret = item.transform(tw, allow_splicing); + + if (ret instanceof AST_Node) { + new_a.push(ret); + } else if (ret instanceof Splice) { + new_a.push(...ret.v); + } + } + + return new_a; + } + + MAP.splice = function(val) { return new Splice(val); }; + MAP.skip = {}; + function Splice(val) { this.v = val; } + return MAP; +})(); + +function make_node(ctor, orig, props) { + if (!props) props = {}; + if (orig) { + if (!props.start) props.start = orig.start; + if (!props.end) props.end = orig.end; + } + return new ctor(props); +} + +function push_uniq(array, el) { + if (!array.includes(el)) + array.push(el); +} + +function string_template(text, props) { + return text.replace(/{(.+?)}/g, function(str, p) { + return props && props[p]; + }); +} + +function remove(array, el) { + for (var i = array.length; --i >= 0;) { + if (array[i] === el) array.splice(i, 1); + } +} + +function mergeSort(array, cmp) { + if (array.length < 2) return array.slice(); + function merge(a, b) { + var r = [], ai = 0, bi = 0, i = 0; + while (ai < a.length && bi < b.length) { + cmp(a[ai], b[bi]) <= 0 + ? r[i++] = a[ai++] + : r[i++] = b[bi++]; + } + if (ai < a.length) r.push.apply(r, a.slice(ai)); + if (bi < b.length) r.push.apply(r, b.slice(bi)); + return r; + } + function _ms(a) { + if (a.length <= 1) + return a; + var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m); + left = _ms(left); + right = _ms(right); + return merge(left, right); + } + return _ms(array); +} + +function makePredicate(words) { + if (!Array.isArray(words)) words = words.split(" "); + + return new Set(words.sort()); +} + +function map_add(map, key, value) { + if (map.has(key)) { + map.get(key).push(value); + } else { + map.set(key, [ value ]); + } +} + +function map_from_object(obj) { + var map = new Map(); + for (var key in obj) { + if (HOP(obj, key) && key.charAt(0) === "$") { + map.set(key.substr(1), obj[key]); + } + } + return map; +} + +function map_to_object(map) { + var obj = Object.create(null); + map.forEach(function (value, key) { + obj["$" + key] = value; + }); + return obj; +} + +function HOP(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +function keep_name(keep_setting, name) { + return keep_setting === true + || (keep_setting instanceof RegExp && keep_setting.test(name)); +} + +var lineTerminatorEscape = { + "\0": "0", + "\n": "n", + "\r": "r", + "\u2028": "u2028", + "\u2029": "u2029", +}; +function regexp_source_fix(source) { + // V8 does not escape line terminators in regexp patterns in node 12 + // We'll also remove literal \0 + return source.replace(/[\0\n\r\u2028\u2029]/g, function (match, offset) { + var escaped = source[offset - 1] == "\\" + && (source[offset - 2] != "\\" + || /(?:^|[^\\])(?:\\{2})*$/.test(source.slice(0, offset - 1))); + return (escaped ? "" : "\\") + lineTerminatorEscape[match]; + }); +} + +// Subset of regexps that is not going to cause regexp based DDOS +// https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS +const re_safe_regexp = /^[\\/|\0\s\w^$.[\]()]*$/; + +/** Check if the regexp is safe for Terser to create without risking a RegExp DOS */ +const regexp_is_safe = (source) => re_safe_regexp.test(source); + +const all_flags = "dgimsuyv"; +function sort_regexp_flags(flags) { + const existing_flags = new Set(flags.split("")); + let out = ""; + for (const flag of all_flags) { + if (existing_flags.has(flag)) { + out += flag; + existing_flags.delete(flag); + } + } + if (existing_flags.size) { + // Flags Terser doesn't know about + existing_flags.forEach(flag => { out += flag; }); + } + return out; +} + +function has_annotation(node, annotation) { + return node._annotations & annotation; +} + +function set_annotation(node, annotation) { + node._annotations |= annotation; +} + +function clear_annotation(node, annotation) { + node._annotations &= ~annotation; +} + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + Parser based on parse-js (http://marijn.haverbeke.nl/parse-js/). + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +var LATEST_RAW = ""; // Only used for numbers and template strings +var TEMPLATE_RAWS = new Map(); // Raw template strings + +var KEYWORDS = "break case catch class const continue debugger default delete do else export extends finally for function if in instanceof let new return switch throw try typeof var void while with"; +var KEYWORDS_ATOM = "false null true"; +var RESERVED_WORDS = "enum import super this " + KEYWORDS_ATOM + " " + KEYWORDS; +var ALL_RESERVED_WORDS = "implements interface package private protected public static " + RESERVED_WORDS; +var KEYWORDS_BEFORE_EXPRESSION = "return new delete throw else case yield await"; + +KEYWORDS = makePredicate(KEYWORDS); +RESERVED_WORDS = makePredicate(RESERVED_WORDS); +KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION); +KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM); +ALL_RESERVED_WORDS = makePredicate(ALL_RESERVED_WORDS); + +var OPERATOR_CHARS = makePredicate(characters("+-*&%=<>!?|~^")); + +var RE_NUM_LITERAL = /[0-9a-f]/i; +var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i; +var RE_OCT_NUMBER = /^0[0-7]+$/; +var RE_ES6_OCT_NUMBER = /^0o[0-7]+$/i; +var RE_BIN_NUMBER = /^0b[01]+$/i; +var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i; +var RE_BIG_INT = /^(0[xob])?[0-9a-f]+n$/i; + +var OPERATORS = makePredicate([ + "in", + "instanceof", + "typeof", + "new", + "void", + "delete", + "++", + "--", + "+", + "-", + "!", + "~", + "&", + "|", + "^", + "*", + "**", + "/", + "%", + ">>", + "<<", + ">>>", + "<", + ">", + "<=", + ">=", + "==", + "===", + "!=", + "!==", + "?", + "=", + "+=", + "-=", + "||=", + "&&=", + "??=", + "/=", + "*=", + "**=", + "%=", + ">>=", + "<<=", + ">>>=", + "|=", + "^=", + "&=", + "&&", + "??", + "||", +]); + +var WHITESPACE_CHARS = makePredicate(characters(" \u00a0\n\r\t\f\u000b\u200b\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\uFEFF")); + +var NEWLINE_CHARS = makePredicate(characters("\n\r\u2028\u2029")); + +var PUNC_AFTER_EXPRESSION = makePredicate(characters(";]),:")); + +var PUNC_BEFORE_EXPRESSION = makePredicate(characters("[{(,;:")); + +var PUNC_CHARS = makePredicate(characters("[]{}(),;:")); + +/* -----[ Tokenizer ]----- */ + +// surrogate safe regexps adapted from https://github.com/mathiasbynens/unicode-8.0.0/tree/89b412d8a71ecca9ed593d9e9fa073ab64acfebe/Binary_Property +var UNICODE = { + ID_Start: /[$A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/, + ID_Continue: /(?:[$0-9A-Z_a-z\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8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u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF])+/, +}; + +function get_full_char(str, pos) { + if (is_surrogate_pair_head(str.charCodeAt(pos))) { + if (is_surrogate_pair_tail(str.charCodeAt(pos + 1))) { + return str.charAt(pos) + str.charAt(pos + 1); + } + } else if (is_surrogate_pair_tail(str.charCodeAt(pos))) { + if (is_surrogate_pair_head(str.charCodeAt(pos - 1))) { + return str.charAt(pos - 1) + str.charAt(pos); + } + } + return str.charAt(pos); +} + +function get_full_char_code(str, pos) { + // https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates + if (is_surrogate_pair_head(str.charCodeAt(pos))) { + return 0x10000 + (str.charCodeAt(pos) - 0xd800 << 10) + str.charCodeAt(pos + 1) - 0xdc00; + } + return str.charCodeAt(pos); +} + +function get_full_char_length(str) { + var surrogates = 0; + + for (var i = 0; i < str.length; i++) { + if (is_surrogate_pair_head(str.charCodeAt(i)) && is_surrogate_pair_tail(str.charCodeAt(i + 1))) { + surrogates++; + i++; + } + } + + return str.length - surrogates; +} + +function from_char_code(code) { + // Based on https://github.com/mathiasbynens/String.fromCodePoint/blob/master/fromcodepoint.js + if (code > 0xFFFF) { + code -= 0x10000; + return (String.fromCharCode((code >> 10) + 0xD800) + + String.fromCharCode((code % 0x400) + 0xDC00)); + } + return String.fromCharCode(code); +} + +function is_surrogate_pair_head(code) { + return code >= 0xd800 && code <= 0xdbff; +} + +function is_surrogate_pair_tail(code) { + return code >= 0xdc00 && code <= 0xdfff; +} + +function is_digit(code) { + return code >= 48 && code <= 57; +} + +function is_identifier_start(ch) { + return UNICODE.ID_Start.test(ch); +} + +function is_identifier_char(ch) { + return UNICODE.ID_Continue.test(ch); +} + +const BASIC_IDENT = /^[a-z_$][a-z0-9_$]*$/i; + +function is_basic_identifier_string(str) { + return BASIC_IDENT.test(str); +} + +function is_identifier_string(str, allow_surrogates) { + if (BASIC_IDENT.test(str)) { + return true; + } + if (!allow_surrogates && /[\ud800-\udfff]/.test(str)) { + return false; + } + var match = UNICODE.ID_Start.exec(str); + if (!match || match.index !== 0) { + return false; + } + + str = str.slice(match[0].length); + if (!str) { + return true; + } + + match = UNICODE.ID_Continue.exec(str); + return !!match && match[0].length === str.length; +} + +function parse_js_number(num, allow_e = true) { + if (!allow_e && num.includes("e")) { + return NaN; + } + if (RE_HEX_NUMBER.test(num)) { + return parseInt(num.substr(2), 16); + } else if (RE_OCT_NUMBER.test(num)) { + return parseInt(num.substr(1), 8); + } else if (RE_ES6_OCT_NUMBER.test(num)) { + return parseInt(num.substr(2), 8); + } else if (RE_BIN_NUMBER.test(num)) { + return parseInt(num.substr(2), 2); + } else if (RE_DEC_NUMBER.test(num)) { + return parseFloat(num); + } else { + var val = parseFloat(num); + if (val == num) return val; + } +} + +class JS_Parse_Error extends Error { + constructor(message, filename, line, col, pos) { + super(); + + this.name = "SyntaxError"; + this.message = message; + this.filename = filename; + this.line = line; + this.col = col; + this.pos = pos; + } +} + +function js_error(message, filename, line, col, pos) { + throw new JS_Parse_Error(message, filename, line, col, pos); +} + +function is_token(token, type, val) { + return token.type == type && (val == null || token.value == val); +} + +var EX_EOF = {}; + +function tokenizer($TEXT, filename, html5_comments, shebang) { + var S = { + text : $TEXT, + filename : filename, + pos : 0, + tokpos : 0, + line : 1, + tokline : 0, + col : 0, + tokcol : 0, + newline_before : false, + regex_allowed : false, + brace_counter : 0, + template_braces : [], + comments_before : [], + directives : {}, + directive_stack : [] + }; + + function peek() { return get_full_char(S.text, S.pos); } + + // Used because parsing ?. involves a lookahead for a digit + function is_option_chain_op() { + const must_be_dot = S.text.charCodeAt(S.pos + 1) === 46; + if (!must_be_dot) return false; + + const cannot_be_digit = S.text.charCodeAt(S.pos + 2); + return cannot_be_digit < 48 || cannot_be_digit > 57; + } + + function next(signal_eof, in_string) { + var ch = get_full_char(S.text, S.pos++); + if (signal_eof && !ch) + throw EX_EOF; + if (NEWLINE_CHARS.has(ch)) { + S.newline_before = S.newline_before || !in_string; + ++S.line; + S.col = 0; + if (ch == "\r" && peek() == "\n") { + // treat a \r\n sequence as a single \n + ++S.pos; + ch = "\n"; + } + } else { + if (ch.length > 1) { + ++S.pos; + ++S.col; + } + ++S.col; + } + return ch; + } + + function forward(i) { + while (i--) next(); + } + + function looking_at(str) { + return S.text.substr(S.pos, str.length) == str; + } + + function find_eol() { + var text = S.text; + for (var i = S.pos, n = S.text.length; i < n; ++i) { + var ch = text[i]; + if (NEWLINE_CHARS.has(ch)) + return i; + } + return -1; + } + + function find(what, signal_eof) { + var pos = S.text.indexOf(what, S.pos); + if (signal_eof && pos == -1) throw EX_EOF; + return pos; + } + + function start_token() { + S.tokline = S.line; + S.tokcol = S.col; + S.tokpos = S.pos; + } + + var prev_was_dot = false; + var previous_token = null; + function token(type, value, is_comment) { + S.regex_allowed = ((type == "operator" && !UNARY_POSTFIX.has(value)) || + (type == "keyword" && KEYWORDS_BEFORE_EXPRESSION.has(value)) || + (type == "punc" && PUNC_BEFORE_EXPRESSION.has(value))) || + (type == "arrow"); + if (type == "punc" && (value == "." || value == "?.")) { + prev_was_dot = true; + } else if (!is_comment) { + prev_was_dot = false; + } + const line = S.tokline; + const col = S.tokcol; + const pos = S.tokpos; + const nlb = S.newline_before; + const file = filename; + let comments_before = []; + let comments_after = []; + + if (!is_comment) { + comments_before = S.comments_before; + comments_after = S.comments_before = []; + } + S.newline_before = false; + const tok = new AST_Token(type, value, line, col, pos, nlb, comments_before, comments_after, file); + + if (!is_comment) previous_token = tok; + return tok; + } + + function skip_whitespace() { + while (WHITESPACE_CHARS.has(peek())) + next(); + } + + function read_while(pred) { + var ret = "", ch, i = 0; + while ((ch = peek()) && pred(ch, i++)) + ret += next(); + return ret; + } + + function parse_error(err) { + js_error(err, filename, S.tokline, S.tokcol, S.tokpos); + } + + function read_num(prefix) { + var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".", is_big_int = false, numeric_separator = false; + var num = read_while(function(ch, i) { + if (is_big_int) return false; + + var code = ch.charCodeAt(0); + switch (code) { + case 95: // _ + return (numeric_separator = true); + case 98: case 66: // bB + return (has_x = true); // Can occur in hex sequence, don't return false yet + case 111: case 79: // oO + case 120: case 88: // xX + return has_x ? false : (has_x = true); + case 101: case 69: // eE + return has_x ? true : has_e ? false : (has_e = after_e = true); + case 45: // - + return after_e || (i == 0 && !prefix); + case 43: // + + return after_e; + case (after_e = false, 46): // . + return (!has_dot && !has_x && !has_e) ? (has_dot = true) : false; + } + + if (ch === "n") { + is_big_int = true; + + return true; + } + + return RE_NUM_LITERAL.test(ch); + }); + if (prefix) num = prefix + num; + + LATEST_RAW = num; + + if (RE_OCT_NUMBER.test(num) && next_token.has_directive("use strict")) { + parse_error("Legacy octal literals are not allowed in strict mode"); + } + if (numeric_separator) { + if (num.endsWith("_")) { + parse_error("Numeric separators are not allowed at the end of numeric literals"); + } else if (num.includes("__")) { + parse_error("Only one underscore is allowed as numeric separator"); + } + num = num.replace(/_/g, ""); + } + if (num.endsWith("n")) { + const without_n = num.slice(0, -1); + const allow_e = RE_HEX_NUMBER.test(without_n); + const valid = parse_js_number(without_n, allow_e); + if (!has_dot && RE_BIG_INT.test(num) && !isNaN(valid)) + return token("big_int", without_n); + parse_error("Invalid or unexpected token"); + } + var valid = parse_js_number(num); + if (!isNaN(valid)) { + return token("num", valid); + } else { + parse_error("Invalid syntax: " + num); + } + } + + function is_octal(ch) { + return ch >= "0" && ch <= "7"; + } + + function read_escaped_char(in_string, strict_hex, template_string) { + var ch = next(true, in_string); + switch (ch.charCodeAt(0)) { + case 110 : return "\n"; + case 114 : return "\r"; + case 116 : return "\t"; + case 98 : return "\b"; + case 118 : return "\u000b"; // \v + case 102 : return "\f"; + case 120 : return String.fromCharCode(hex_bytes(2, strict_hex)); // \x + case 117 : // \u + if (peek() == "{") { + next(true); + if (peek() === "}") + parse_error("Expecting hex-character between {}"); + while (peek() == "0") next(true); // No significance + var result, length = find("}", true) - S.pos; + // Avoid 32 bit integer overflow (1 << 32 === 1) + // We know first character isn't 0 and thus out of range anyway + if (length > 6 || (result = hex_bytes(length, strict_hex)) > 0x10FFFF) { + parse_error("Unicode reference out of bounds"); + } + next(true); + return from_char_code(result); + } + return String.fromCharCode(hex_bytes(4, strict_hex)); + case 10 : return ""; // newline + case 13 : // \r + if (peek() == "\n") { // DOS newline + next(true, in_string); + return ""; + } + } + if (is_octal(ch)) { + if (template_string && strict_hex) { + const represents_null_character = ch === "0" && !is_octal(peek()); + if (!represents_null_character) { + parse_error("Octal escape sequences are not allowed in template strings"); + } + } + return read_octal_escape_sequence(ch, strict_hex); + } + return ch; + } + + function read_octal_escape_sequence(ch, strict_octal) { + // Read + var p = peek(); + if (p >= "0" && p <= "7") { + ch += next(true); + if (ch[0] <= "3" && (p = peek()) >= "0" && p <= "7") + ch += next(true); + } + + // Parse + if (ch === "0") return "\0"; + if (ch.length > 0 && next_token.has_directive("use strict") && strict_octal) + parse_error("Legacy octal escape sequences are not allowed in strict mode"); + return String.fromCharCode(parseInt(ch, 8)); + } + + function hex_bytes(n, strict_hex) { + var num = 0; + for (; n > 0; --n) { + if (!strict_hex && isNaN(parseInt(peek(), 16))) { + return parseInt(num, 16) || ""; + } + var digit = next(true); + if (isNaN(parseInt(digit, 16))) + parse_error("Invalid hex-character pattern in string"); + num += digit; + } + return parseInt(num, 16); + } + + var read_string = with_eof_error("Unterminated string constant", function() { + const start_pos = S.pos; + var quote = next(), ret = []; + for (;;) { + var ch = next(true, true); + if (ch == "\\") ch = read_escaped_char(true, true); + else if (ch == "\r" || ch == "\n") parse_error("Unterminated string constant"); + else if (ch == quote) break; + ret.push(ch); + } + var tok = token("string", ret.join("")); + LATEST_RAW = S.text.slice(start_pos, S.pos); + tok.quote = quote; + return tok; + }); + + var read_template_characters = with_eof_error("Unterminated template", function(begin) { + if (begin) { + S.template_braces.push(S.brace_counter); + } + var content = "", raw = "", ch, tok; + next(true, true); + while ((ch = next(true, true)) != "`") { + if (ch == "\r") { + if (peek() == "\n") ++S.pos; + ch = "\n"; + } else if (ch == "$" && peek() == "{") { + next(true, true); + S.brace_counter++; + tok = token(begin ? "template_head" : "template_substitution", content); + TEMPLATE_RAWS.set(tok, raw); + tok.template_end = false; + return tok; + } + + raw += ch; + if (ch == "\\") { + var tmp = S.pos; + var prev_is_tag = previous_token && (previous_token.type === "name" || previous_token.type === "punc" && (previous_token.value === ")" || previous_token.value === "]")); + ch = read_escaped_char(true, !prev_is_tag, true); + raw += S.text.substr(tmp, S.pos - tmp); + } + + content += ch; + } + S.template_braces.pop(); + tok = token(begin ? "template_head" : "template_substitution", content); + TEMPLATE_RAWS.set(tok, raw); + tok.template_end = true; + return tok; + }); + + function skip_line_comment(type) { + var regex_allowed = S.regex_allowed; + var i = find_eol(), ret; + if (i == -1) { + ret = S.text.substr(S.pos); + S.pos = S.text.length; + } else { + ret = S.text.substring(S.pos, i); + S.pos = i; + } + S.col = S.tokcol + (S.pos - S.tokpos); + S.comments_before.push(token(type, ret, true)); + S.regex_allowed = regex_allowed; + return next_token; + } + + var skip_multiline_comment = with_eof_error("Unterminated multiline comment", function() { + var regex_allowed = S.regex_allowed; + var i = find("*/", true); + var text = S.text.substring(S.pos, i).replace(/\r\n|\r|\u2028|\u2029/g, "\n"); + // update stream position + forward(get_full_char_length(text) /* text length doesn't count \r\n as 2 char while S.pos - i does */ + 2); + S.comments_before.push(token("comment2", text, true)); + S.newline_before = S.newline_before || text.includes("\n"); + S.regex_allowed = regex_allowed; + return next_token; + }); + + var read_name = with_eof_error("Unterminated identifier name", function() { + var name = [], ch, escaped = false; + var read_escaped_identifier_char = function() { + escaped = true; + next(); + if (peek() !== "u") { + parse_error("Expecting UnicodeEscapeSequence -- uXXXX or u{XXXX}"); + } + return read_escaped_char(false, true); + }; + + // Read first character (ID_Start) + if ((ch = peek()) === "\\") { + ch = read_escaped_identifier_char(); + if (!is_identifier_start(ch)) { + parse_error("First identifier char is an invalid identifier char"); + } + } else if (is_identifier_start(ch)) { + next(); + } else { + return ""; + } + + name.push(ch); + + // Read ID_Continue + while ((ch = peek()) != null) { + if ((ch = peek()) === "\\") { + ch = read_escaped_identifier_char(); + if (!is_identifier_char(ch)) { + parse_error("Invalid escaped identifier char"); + } + } else { + if (!is_identifier_char(ch)) { + break; + } + next(); + } + name.push(ch); + } + const name_str = name.join(""); + if (RESERVED_WORDS.has(name_str) && escaped) { + parse_error("Escaped characters are not allowed in keywords"); + } + return name_str; + }); + + var read_regexp = with_eof_error("Unterminated regular expression", function(source) { + var prev_backslash = false, ch, in_class = false; + while ((ch = next(true))) if (NEWLINE_CHARS.has(ch)) { + parse_error("Unexpected line terminator"); + } else if (prev_backslash) { + if (/^[\u0000-\u007F]$/.test(ch)) { + source += "\\" + ch; + } else { + // Remove the useless slash before the escape, but only for characters that won't be added to regexp syntax + source += ch; + } + prev_backslash = false; + } else if (ch == "[") { + in_class = true; + source += ch; + } else if (ch == "]" && in_class) { + in_class = false; + source += ch; + } else if (ch == "/" && !in_class) { + break; + } else if (ch == "\\") { + prev_backslash = true; + } else { + source += ch; + } + const flags = read_name(); + return token("regexp", "/" + source + "/" + flags); + }); + + function read_operator(prefix) { + function grow(op) { + if (!peek()) return op; + var bigger = op + peek(); + if (OPERATORS.has(bigger)) { + next(); + return grow(bigger); + } else { + return op; + } + } + return token("operator", grow(prefix || next())); + } + + function handle_slash() { + next(); + switch (peek()) { + case "/": + next(); + return skip_line_comment("comment1"); + case "*": + next(); + return skip_multiline_comment(); + } + return S.regex_allowed ? read_regexp("") : read_operator("/"); + } + + function handle_eq_sign() { + next(); + if (peek() === ">") { + next(); + return token("arrow", "=>"); + } else { + return read_operator("="); + } + } + + function handle_dot() { + next(); + if (is_digit(peek().charCodeAt(0))) { + return read_num("."); + } + if (peek() === ".") { + next(); // Consume second dot + next(); // Consume third dot + return token("expand", "..."); + } + + return token("punc", "."); + } + + function read_word() { + var word = read_name(); + if (prev_was_dot) return token("name", word); + return KEYWORDS_ATOM.has(word) ? token("atom", word) + : !KEYWORDS.has(word) ? token("name", word) + : OPERATORS.has(word) ? token("operator", word) + : token("keyword", word); + } + + function read_private_word() { + next(); + return token("privatename", read_name()); + } + + function with_eof_error(eof_error, cont) { + return function(x) { + try { + return cont(x); + } catch(ex) { + if (ex === EX_EOF) parse_error(eof_error); + else throw ex; + } + }; + } + + function next_token(force_regexp) { + if (force_regexp != null) + return read_regexp(force_regexp); + if (shebang && S.pos == 0 && looking_at("#!")) { + start_token(); + forward(2); + skip_line_comment("comment5"); + } + for (;;) { + skip_whitespace(); + start_token(); + if (html5_comments) { + if (looking_at("") && S.newline_before) { + forward(3); + skip_line_comment("comment4"); + continue; + } + } + var ch = peek(); + if (!ch) return token("eof"); + var code = ch.charCodeAt(0); + switch (code) { + case 34: case 39: return read_string(); + case 46: return handle_dot(); + case 47: { + var tok = handle_slash(); + if (tok === next_token) continue; + return tok; + } + case 61: return handle_eq_sign(); + case 63: { + if (!is_option_chain_op()) break; // Handled below + + next(); // ? + next(); // . + + return token("punc", "?."); + } + case 96: return read_template_characters(true); + case 123: + S.brace_counter++; + break; + case 125: + S.brace_counter--; + if (S.template_braces.length > 0 + && S.template_braces[S.template_braces.length - 1] === S.brace_counter) + return read_template_characters(false); + break; + } + if (is_digit(code)) return read_num(); + if (PUNC_CHARS.has(ch)) return token("punc", next()); + if (OPERATOR_CHARS.has(ch)) return read_operator(); + if (code == 92 || is_identifier_start(ch)) return read_word(); + if (code == 35) return read_private_word(); + break; + } + parse_error("Unexpected character '" + ch + "'"); + } + + next_token.next = next; + next_token.peek = peek; + + next_token.context = function(nc) { + if (nc) S = nc; + return S; + }; + + next_token.add_directive = function(directive) { + S.directive_stack[S.directive_stack.length - 1].push(directive); + + if (S.directives[directive] === undefined) { + S.directives[directive] = 1; + } else { + S.directives[directive]++; + } + }; + + next_token.push_directives_stack = function() { + S.directive_stack.push([]); + }; + + next_token.pop_directives_stack = function() { + var directives = S.directive_stack[S.directive_stack.length - 1]; + + for (var i = 0; i < directives.length; i++) { + S.directives[directives[i]]--; + } + + S.directive_stack.pop(); + }; + + next_token.has_directive = function(directive) { + return S.directives[directive] > 0; + }; + + return next_token; + +} + +/* -----[ Parser (constants) ]----- */ + +var UNARY_PREFIX = makePredicate([ + "typeof", + "void", + "delete", + "--", + "++", + "!", + "~", + "-", + "+" +]); + +var UNARY_POSTFIX = makePredicate([ "--", "++" ]); + +var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "??=", "&&=", "||=", "/=", "*=", "**=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]); + +var LOGICAL_ASSIGNMENT = makePredicate([ "??=", "&&=", "||=" ]); + +var PRECEDENCE = (function(a, ret) { + for (var i = 0; i < a.length; ++i) { + for (const op of a[i]) { + ret[op] = i + 1; + } + } + return ret; +})( + [ + ["||"], + ["??"], + ["&&"], + ["|"], + ["^"], + ["&"], + ["==", "===", "!=", "!=="], + ["<", ">", "<=", ">=", "in", "instanceof"], + [">>", "<<", ">>>"], + ["+", "-"], + ["*", "/", "%"], + ["**"] + ], + {} +); + +var ATOMIC_START_TOKEN = makePredicate([ "atom", "num", "big_int", "string", "regexp", "name"]); + +/* -----[ Parser ]----- */ + +function parse($TEXT, options) { + // maps start tokens to count of comments found outside of their parens + // Example: /* I count */ ( /* I don't */ foo() ) + // Useful because comments_before property of call with parens outside + // contains both comments inside and outside these parens. Used to find the + + const outer_comments_before_counts = new WeakMap(); + + options = defaults(options, { + bare_returns : false, + ecma : null, // Legacy + expression : false, + filename : null, + html5_comments : true, + module : false, + shebang : true, + strict : false, + toplevel : null, + }, true); + + var S = { + input : (typeof $TEXT == "string" + ? tokenizer($TEXT, options.filename, + options.html5_comments, options.shebang) + : $TEXT), + token : null, + prev : null, + peeked : null, + in_function : 0, + in_async : -1, + in_generator : -1, + in_directives : true, + in_loop : 0, + labels : [] + }; + + S.token = next(); + + function is(type, value) { + return is_token(S.token, type, value); + } + + function peek() { return S.peeked || (S.peeked = S.input()); } + + function next() { + S.prev = S.token; + + if (!S.peeked) peek(); + S.token = S.peeked; + S.peeked = null; + S.in_directives = S.in_directives && ( + S.token.type == "string" || is("punc", ";") + ); + return S.token; + } + + function prev() { + return S.prev; + } + + function croak(msg, line, col, pos) { + var ctx = S.input.context(); + js_error(msg, + ctx.filename, + line != null ? line : ctx.tokline, + col != null ? col : ctx.tokcol, + pos != null ? pos : ctx.tokpos); + } + + function token_error(token, msg) { + croak(msg, token.line, token.col); + } + + function unexpected(token) { + if (token == null) + token = S.token; + token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")"); + } + + function expect_token(type, val) { + if (is(type, val)) { + return next(); + } + token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»"); + } + + function expect(punc) { return expect_token("punc", punc); } + + function has_newline_before(token) { + return token.nlb || !token.comments_before.every((comment) => !comment.nlb); + } + + function can_insert_semicolon() { + return !options.strict + && (is("eof") || is("punc", "}") || has_newline_before(S.token)); + } + + function is_in_generator() { + return S.in_generator === S.in_function; + } + + function is_in_async() { + return S.in_async === S.in_function; + } + + function can_await() { + return ( + S.in_async === S.in_function + || S.in_function === 0 && S.input.has_directive("use strict") + ); + } + + function semicolon(optional) { + if (is("punc", ";")) next(); + else if (!optional && !can_insert_semicolon()) unexpected(); + } + + function parenthesised() { + expect("("); + var exp = expression(true); + expect(")"); + return exp; + } + + function embed_tokens(parser) { + return function _embed_tokens_wrapper(...args) { + const start = S.token; + const expr = parser(...args); + expr.start = start; + expr.end = prev(); + return expr; + }; + } + + function handle_regexp() { + if (is("operator", "/") || is("operator", "/=")) { + S.peeked = null; + S.token = S.input(S.token.value.substr(1)); // force regexp + } + } + + var statement = embed_tokens(function statement(is_export_default, is_for_body, is_if_body) { + handle_regexp(); + switch (S.token.type) { + case "string": + if (S.in_directives) { + var token = peek(); + if (!LATEST_RAW.includes("\\") + && (is_token(token, "punc", ";") + || is_token(token, "punc", "}") + || has_newline_before(token) + || is_token(token, "eof"))) { + S.input.add_directive(S.token.value); + } else { + S.in_directives = false; + } + } + var dir = S.in_directives, stat = simple_statement(); + return dir && stat.body instanceof AST_String ? new AST_Directive(stat.body) : stat; + case "template_head": + case "num": + case "big_int": + case "regexp": + case "operator": + case "atom": + return simple_statement(); + + case "name": + case "privatename": + if(is("privatename") && !S.in_class) + croak("Private field must be used in an enclosing class"); + + if (S.token.value == "async" && is_token(peek(), "keyword", "function")) { + next(); + next(); + if (is_for_body) { + croak("functions are not allowed as the body of a loop"); + } + return function_(AST_Defun, false, true, is_export_default); + } + if (S.token.value == "import" && !is_token(peek(), "punc", "(") && !is_token(peek(), "punc", ".")) { + next(); + var node = import_statement(); + semicolon(); + return node; + } + return is_token(peek(), "punc", ":") + ? labeled_statement() + : simple_statement(); + + case "punc": + switch (S.token.value) { + case "{": + return new AST_BlockStatement({ + start : S.token, + body : block_(), + end : prev() + }); + case "[": + case "(": + return simple_statement(); + case ";": + S.in_directives = false; + next(); + return new AST_EmptyStatement(); + default: + unexpected(); + } + + case "keyword": + switch (S.token.value) { + case "break": + next(); + return break_cont(AST_Break); + + case "continue": + next(); + return break_cont(AST_Continue); + + case "debugger": + next(); + semicolon(); + return new AST_Debugger(); + + case "do": + next(); + var body = in_loop(statement); + expect_token("keyword", "while"); + var condition = parenthesised(); + semicolon(true); + return new AST_Do({ + body : body, + condition : condition + }); + + case "while": + next(); + return new AST_While({ + condition : parenthesised(), + body : in_loop(function() { return statement(false, true); }) + }); + + case "for": + next(); + return for_(); + + case "class": + next(); + if (is_for_body) { + croak("classes are not allowed as the body of a loop"); + } + if (is_if_body) { + croak("classes are not allowed as the body of an if"); + } + return class_(AST_DefClass, is_export_default); + + case "function": + next(); + if (is_for_body) { + croak("functions are not allowed as the body of a loop"); + } + return function_(AST_Defun, false, false, is_export_default); + + case "if": + next(); + return if_(); + + case "return": + if (S.in_function == 0 && !options.bare_returns) + croak("'return' outside of function"); + next(); + var value = null; + if (is("punc", ";")) { + next(); + } else if (!can_insert_semicolon()) { + value = expression(true); + semicolon(); + } + return new AST_Return({ + value: value + }); + + case "switch": + next(); + return new AST_Switch({ + expression : parenthesised(), + body : in_loop(switch_body_) + }); + + case "throw": + next(); + if (has_newline_before(S.token)) + croak("Illegal newline after 'throw'"); + var value = expression(true); + semicolon(); + return new AST_Throw({ + value: value + }); + + case "try": + next(); + return try_(); + + case "var": + next(); + var node = var_(); + semicolon(); + return node; + + case "let": + next(); + var node = let_(); + semicolon(); + return node; + + case "const": + next(); + var node = const_(); + semicolon(); + return node; + + case "with": + if (S.input.has_directive("use strict")) { + croak("Strict mode may not include a with statement"); + } + next(); + return new AST_With({ + expression : parenthesised(), + body : statement() + }); + + case "export": + if (!is_token(peek(), "punc", "(")) { + next(); + var node = export_statement(); + if (is("punc", ";")) semicolon(); + return node; + } + } + } + unexpected(); + }); + + function labeled_statement() { + var label = as_symbol(AST_Label); + if (label.name === "await" && is_in_async()) { + token_error(S.prev, "await cannot be used as label inside async function"); + } + if (S.labels.some((l) => l.name === label.name)) { + // ECMA-262, 12.12: An ECMAScript program is considered + // syntactically incorrect if it contains a + // LabelledStatement that is enclosed by a + // LabelledStatement with the same Identifier as label. + croak("Label " + label.name + " defined twice"); + } + expect(":"); + S.labels.push(label); + var stat = statement(); + S.labels.pop(); + if (!(stat instanceof AST_IterationStatement)) { + // check for `continue` that refers to this label. + // those should be reported as syntax errors. + // https://github.com/mishoo/UglifyJS2/issues/287 + label.references.forEach(function(ref) { + if (ref instanceof AST_Continue) { + ref = ref.label.start; + croak("Continue label `" + label.name + "` refers to non-IterationStatement.", + ref.line, ref.col, ref.pos); + } + }); + } + return new AST_LabeledStatement({ body: stat, label: label }); + } + + function simple_statement(tmp) { + return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) }); + } + + function break_cont(type) { + var label = null, ldef; + if (!can_insert_semicolon()) { + label = as_symbol(AST_LabelRef, true); + } + if (label != null) { + ldef = S.labels.find((l) => l.name === label.name); + if (!ldef) + croak("Undefined label " + label.name); + label.thedef = ldef; + } else if (S.in_loop == 0) + croak(type.TYPE + " not inside a loop or switch"); + semicolon(); + var stat = new type({ label: label }); + if (ldef) ldef.references.push(stat); + return stat; + } + + function for_() { + var for_await_error = "`for await` invalid in this context"; + var await_tok = S.token; + if (await_tok.type == "name" && await_tok.value == "await") { + if (!can_await()) { + token_error(await_tok, for_await_error); + } + next(); + } else { + await_tok = false; + } + expect("("); + var init = null; + if (!is("punc", ";")) { + init = + is("keyword", "var") ? (next(), var_(true)) : + is("keyword", "let") ? (next(), let_(true)) : + is("keyword", "const") ? (next(), const_(true)) : + expression(true, true); + var is_in = is("operator", "in"); + var is_of = is("name", "of"); + if (await_tok && !is_of) { + token_error(await_tok, for_await_error); + } + if (is_in || is_of) { + if (init instanceof AST_Definitions) { + if (init.definitions.length > 1) + token_error(init.start, "Only one variable declaration allowed in for..in loop"); + } else if (!(is_assignable(init) || (init = to_destructuring(init)) instanceof AST_Destructuring)) { + token_error(init.start, "Invalid left-hand side in for..in loop"); + } + next(); + if (is_in) { + return for_in(init); + } else { + return for_of(init, !!await_tok); + } + } + } else if (await_tok) { + token_error(await_tok, for_await_error); + } + return regular_for(init); + } + + function regular_for(init) { + expect(";"); + var test = is("punc", ";") ? null : expression(true); + expect(";"); + var step = is("punc", ")") ? null : expression(true); + expect(")"); + return new AST_For({ + init : init, + condition : test, + step : step, + body : in_loop(function() { return statement(false, true); }) + }); + } + + function for_of(init, is_await) { + var lhs = init instanceof AST_Definitions ? init.definitions[0].name : null; + var obj = expression(true); + expect(")"); + return new AST_ForOf({ + await : is_await, + init : init, + name : lhs, + object : obj, + body : in_loop(function() { return statement(false, true); }) + }); + } + + function for_in(init) { + var obj = expression(true); + expect(")"); + return new AST_ForIn({ + init : init, + object : obj, + body : in_loop(function() { return statement(false, true); }) + }); + } + + var arrow_function = function(start, argnames, is_async) { + if (has_newline_before(S.token)) { + croak("Unexpected newline before arrow (=>)"); + } + + expect_token("arrow", "=>"); + + var body = _function_body(is("punc", "{"), false, is_async); + + var end = + body instanceof Array && body.length ? body[body.length - 1].end : + body instanceof Array ? start : + body.end; + + return new AST_Arrow({ + start : start, + end : end, + async : is_async, + argnames : argnames, + body : body + }); + }; + + var function_ = function(ctor, is_generator_property, is_async, is_export_default) { + var in_statement = ctor === AST_Defun; + var is_generator = is("operator", "*"); + if (is_generator) { + next(); + } + + var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null; + if (in_statement && !name) { + if (is_export_default) { + ctor = AST_Function; + } else { + unexpected(); + } + } + + if (name && ctor !== AST_Accessor && !(name instanceof AST_SymbolDeclaration)) + unexpected(prev()); + + var args = []; + var body = _function_body(true, is_generator || is_generator_property, is_async, name, args); + return new ctor({ + start : args.start, + end : body.end, + is_generator: is_generator, + async : is_async, + name : name, + argnames: args, + body : body + }); + }; + + class UsedParametersTracker { + constructor(is_parameter, strict, duplicates_ok = false) { + this.is_parameter = is_parameter; + this.duplicates_ok = duplicates_ok; + this.parameters = new Set(); + this.duplicate = null; + this.default_assignment = false; + this.spread = false; + this.strict_mode = !!strict; + } + add_parameter(token) { + if (this.parameters.has(token.value)) { + if (this.duplicate === null) { + this.duplicate = token; + } + this.check_strict(); + } else { + this.parameters.add(token.value); + if (this.is_parameter) { + switch (token.value) { + case "arguments": + case "eval": + case "yield": + if (this.strict_mode) { + token_error(token, "Unexpected " + token.value + " identifier as parameter inside strict mode"); + } + break; + default: + if (RESERVED_WORDS.has(token.value)) { + unexpected(); + } + } + } + } + } + mark_default_assignment(token) { + if (this.default_assignment === false) { + this.default_assignment = token; + } + } + mark_spread(token) { + if (this.spread === false) { + this.spread = token; + } + } + mark_strict_mode() { + this.strict_mode = true; + } + is_strict() { + return this.default_assignment !== false || this.spread !== false || this.strict_mode; + } + check_strict() { + if (this.is_strict() && this.duplicate !== null && !this.duplicates_ok) { + token_error(this.duplicate, "Parameter " + this.duplicate.value + " was used already"); + } + } + } + + function parameters(params) { + var used_parameters = new UsedParametersTracker(true, S.input.has_directive("use strict")); + + expect("("); + + while (!is("punc", ")")) { + var param = parameter(used_parameters); + params.push(param); + + if (!is("punc", ")")) { + expect(","); + } + + if (param instanceof AST_Expansion) { + break; + } + } + + next(); + } + + function parameter(used_parameters, symbol_type) { + var param; + var expand = false; + if (used_parameters === undefined) { + used_parameters = new UsedParametersTracker(true, S.input.has_directive("use strict")); + } + if (is("expand", "...")) { + expand = S.token; + used_parameters.mark_spread(S.token); + next(); + } + param = binding_element(used_parameters, symbol_type); + + if (is("operator", "=") && expand === false) { + used_parameters.mark_default_assignment(S.token); + next(); + param = new AST_DefaultAssign({ + start: param.start, + left: param, + operator: "=", + right: expression(false), + end: S.token + }); + } + + if (expand !== false) { + if (!is("punc", ")")) { + unexpected(); + } + param = new AST_Expansion({ + start: expand, + expression: param, + end: expand + }); + } + used_parameters.check_strict(); + + return param; + } + + function binding_element(used_parameters, symbol_type) { + var elements = []; + var first = true; + var is_expand = false; + var expand_token; + var first_token = S.token; + if (used_parameters === undefined) { + const strict = S.input.has_directive("use strict"); + const duplicates_ok = symbol_type === AST_SymbolVar; + used_parameters = new UsedParametersTracker(false, strict, duplicates_ok); + } + symbol_type = symbol_type === undefined ? AST_SymbolFunarg : symbol_type; + if (is("punc", "[")) { + next(); + while (!is("punc", "]")) { + if (first) { + first = false; + } else { + expect(","); + } + + if (is("expand", "...")) { + is_expand = true; + expand_token = S.token; + used_parameters.mark_spread(S.token); + next(); + } + if (is("punc")) { + switch (S.token.value) { + case ",": + elements.push(new AST_Hole({ + start: S.token, + end: S.token + })); + continue; + case "]": // Trailing comma after last element + break; + case "[": + case "{": + elements.push(binding_element(used_parameters, symbol_type)); + break; + default: + unexpected(); + } + } else if (is("name")) { + used_parameters.add_parameter(S.token); + elements.push(as_symbol(symbol_type)); + } else { + croak("Invalid function parameter"); + } + if (is("operator", "=") && is_expand === false) { + used_parameters.mark_default_assignment(S.token); + next(); + elements[elements.length - 1] = new AST_DefaultAssign({ + start: elements[elements.length - 1].start, + left: elements[elements.length - 1], + operator: "=", + right: expression(false), + end: S.token + }); + } + if (is_expand) { + if (!is("punc", "]")) { + croak("Rest element must be last element"); + } + elements[elements.length - 1] = new AST_Expansion({ + start: expand_token, + expression: elements[elements.length - 1], + end: expand_token + }); + } + } + expect("]"); + used_parameters.check_strict(); + return new AST_Destructuring({ + start: first_token, + names: elements, + is_array: true, + end: prev() + }); + } else if (is("punc", "{")) { + next(); + while (!is("punc", "}")) { + if (first) { + first = false; + } else { + expect(","); + } + if (is("expand", "...")) { + is_expand = true; + expand_token = S.token; + used_parameters.mark_spread(S.token); + next(); + } + if (is("name") && (is_token(peek(), "punc") || is_token(peek(), "operator")) && [",", "}", "="].includes(peek().value)) { + used_parameters.add_parameter(S.token); + var start = prev(); + var value = as_symbol(symbol_type); + if (is_expand) { + elements.push(new AST_Expansion({ + start: expand_token, + expression: value, + end: value.end, + })); + } else { + elements.push(new AST_ObjectKeyVal({ + start: start, + key: value.name, + value: value, + end: value.end, + })); + } + } else if (is("punc", "}")) { + continue; // Allow trailing hole + } else { + var property_token = S.token; + var property = as_property_name(); + if (property === null) { + unexpected(prev()); + } else if (prev().type === "name" && !is("punc", ":")) { + elements.push(new AST_ObjectKeyVal({ + start: prev(), + key: property, + value: new symbol_type({ + start: prev(), + name: property, + end: prev() + }), + end: prev() + })); + } else { + expect(":"); + elements.push(new AST_ObjectKeyVal({ + start: property_token, + quote: property_token.quote, + key: property, + value: binding_element(used_parameters, symbol_type), + end: prev() + })); + } + } + if (is_expand) { + if (!is("punc", "}")) { + croak("Rest element must be last element"); + } + } else if (is("operator", "=")) { + used_parameters.mark_default_assignment(S.token); + next(); + elements[elements.length - 1].value = new AST_DefaultAssign({ + start: elements[elements.length - 1].value.start, + left: elements[elements.length - 1].value, + operator: "=", + right: expression(false), + end: S.token + }); + } + } + expect("}"); + used_parameters.check_strict(); + return new AST_Destructuring({ + start: first_token, + names: elements, + is_array: false, + end: prev() + }); + } else if (is("name")) { + used_parameters.add_parameter(S.token); + return as_symbol(symbol_type); + } else { + croak("Invalid function parameter"); + } + } + + function params_or_seq_(allow_arrows, maybe_sequence) { + var spread_token; + var invalid_sequence; + var trailing_comma; + var a = []; + expect("("); + while (!is("punc", ")")) { + if (spread_token) unexpected(spread_token); + if (is("expand", "...")) { + spread_token = S.token; + if (maybe_sequence) invalid_sequence = S.token; + next(); + a.push(new AST_Expansion({ + start: prev(), + expression: expression(), + end: S.token, + })); + } else { + a.push(expression()); + } + if (!is("punc", ")")) { + expect(","); + if (is("punc", ")")) { + trailing_comma = prev(); + if (maybe_sequence) invalid_sequence = trailing_comma; + } + } + } + expect(")"); + if (allow_arrows && is("arrow", "=>")) { + if (spread_token && trailing_comma) unexpected(trailing_comma); + } else if (invalid_sequence) { + unexpected(invalid_sequence); + } + return a; + } + + function _function_body(block, generator, is_async, name, args) { + var loop = S.in_loop; + var labels = S.labels; + var current_generator = S.in_generator; + var current_async = S.in_async; + ++S.in_function; + if (generator) + S.in_generator = S.in_function; + if (is_async) + S.in_async = S.in_function; + if (args) parameters(args); + if (block) + S.in_directives = true; + S.in_loop = 0; + S.labels = []; + if (block) { + S.input.push_directives_stack(); + var a = block_(); + if (name) _verify_symbol(name); + if (args) args.forEach(_verify_symbol); + S.input.pop_directives_stack(); + } else { + var a = [new AST_Return({ + start: S.token, + value: expression(false), + end: S.token + })]; + } + --S.in_function; + S.in_loop = loop; + S.labels = labels; + S.in_generator = current_generator; + S.in_async = current_async; + return a; + } + + function _await_expression() { + // Previous token must be "await" and not be interpreted as an identifier + if (!can_await()) { + croak("Unexpected await expression outside async function", + S.prev.line, S.prev.col, S.prev.pos); + } + // the await expression is parsed as a unary expression in Babel + return new AST_Await({ + start: prev(), + end: S.token, + expression : maybe_unary(true), + }); + } + + function _yield_expression() { + // Previous token must be keyword yield and not be interpret as an identifier + if (!is_in_generator()) { + croak("Unexpected yield expression outside generator function", + S.prev.line, S.prev.col, S.prev.pos); + } + var start = S.token; + var star = false; + var has_expression = true; + + // Attempt to get expression or star (and then the mandatory expression) + // behind yield on the same line. + // + // If nothing follows on the same line of the yieldExpression, + // it should default to the value `undefined` for yield to return. + // In that case, the `undefined` stored as `null` in ast. + // + // Note 1: It isn't allowed for yield* to close without an expression + // Note 2: If there is a nlb between yield and star, it is interpret as + // yield * + if (can_insert_semicolon() || + (is("punc") && PUNC_AFTER_EXPRESSION.has(S.token.value))) { + has_expression = false; + + } else if (is("operator", "*")) { + star = true; + next(); + } + + return new AST_Yield({ + start : start, + is_star : star, + expression : has_expression ? expression() : null, + end : prev() + }); + } + + function if_() { + var cond = parenthesised(), body = statement(false, false, true), belse = null; + if (is("keyword", "else")) { + next(); + belse = statement(false, false, true); + } + return new AST_If({ + condition : cond, + body : body, + alternative : belse + }); + } + + function block_() { + expect("{"); + var a = []; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + a.push(statement()); + } + next(); + return a; + } + + function switch_body_() { + expect("{"); + var a = [], cur = null, branch = null, tmp; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + if (is("keyword", "case")) { + if (branch) branch.end = prev(); + cur = []; + branch = new AST_Case({ + start : (tmp = S.token, next(), tmp), + expression : expression(true), + body : cur + }); + a.push(branch); + expect(":"); + } else if (is("keyword", "default")) { + if (branch) branch.end = prev(); + cur = []; + branch = new AST_Default({ + start : (tmp = S.token, next(), expect(":"), tmp), + body : cur + }); + a.push(branch); + } else { + if (!cur) unexpected(); + cur.push(statement()); + } + } + if (branch) branch.end = prev(); + next(); + return a; + } + + function try_() { + var body, bcatch = null, bfinally = null; + body = new AST_TryBlock({ + start : S.token, + body : block_(), + end : prev(), + }); + if (is("keyword", "catch")) { + var start = S.token; + next(); + if (is("punc", "{")) { + var name = null; + } else { + expect("("); + var name = parameter(undefined, AST_SymbolCatch); + expect(")"); + } + bcatch = new AST_Catch({ + start : start, + argname : name, + body : block_(), + end : prev() + }); + } + if (is("keyword", "finally")) { + var start = S.token; + next(); + bfinally = new AST_Finally({ + start : start, + body : block_(), + end : prev() + }); + } + if (!bcatch && !bfinally) + croak("Missing catch/finally blocks"); + return new AST_Try({ + body : body, + bcatch : bcatch, + bfinally : bfinally + }); + } + + /** + * var + * vardef1 = 2, + * vardef2 = 3; + */ + function vardefs(no_in, kind) { + var var_defs = []; + var def; + for (;;) { + var sym_type = + kind === "var" ? AST_SymbolVar : + kind === "const" ? AST_SymbolConst : + kind === "let" ? AST_SymbolLet : null; + // var { a } = b + if (is("punc", "{") || is("punc", "[")) { + def = new AST_VarDef({ + start: S.token, + name: binding_element(undefined, sym_type), + value: is("operator", "=") ? (expect_token("operator", "="), expression(false, no_in)) : null, + end: prev() + }); + } else { + def = new AST_VarDef({ + start : S.token, + name : as_symbol(sym_type), + value : is("operator", "=") + ? (next(), expression(false, no_in)) + : !no_in && kind === "const" + ? croak("Missing initializer in const declaration") : null, + end : prev() + }); + if (def.name.name == "import") croak("Unexpected token: import"); + } + var_defs.push(def); + if (!is("punc", ",")) + break; + next(); + } + return var_defs; + } + + var var_ = function(no_in) { + return new AST_Var({ + start : prev(), + definitions : vardefs(no_in, "var"), + end : prev() + }); + }; + + var let_ = function(no_in) { + return new AST_Let({ + start : prev(), + definitions : vardefs(no_in, "let"), + end : prev() + }); + }; + + var const_ = function(no_in) { + return new AST_Const({ + start : prev(), + definitions : vardefs(no_in, "const"), + end : prev() + }); + }; + + var new_ = function(allow_calls) { + var start = S.token; + expect_token("operator", "new"); + if (is("punc", ".")) { + next(); + expect_token("name", "target"); + return subscripts(new AST_NewTarget({ + start : start, + end : prev() + }), allow_calls); + } + var newexp = expr_atom(false), args; + if (is("punc", "(")) { + next(); + args = expr_list(")", true); + } else { + args = []; + } + var call = new AST_New({ + start : start, + expression : newexp, + args : args, + end : prev() + }); + annotate(call); + return subscripts(call, allow_calls); + }; + + function as_atom_node() { + var tok = S.token, ret; + switch (tok.type) { + case "name": + ret = _make_symbol(AST_SymbolRef); + break; + case "num": + ret = new AST_Number({ + start: tok, + end: tok, + value: tok.value, + raw: LATEST_RAW + }); + break; + case "big_int": + ret = new AST_BigInt({ start: tok, end: tok, value: tok.value }); + break; + case "string": + ret = new AST_String({ + start : tok, + end : tok, + value : tok.value, + quote : tok.quote + }); + annotate(ret); + break; + case "regexp": + const [_, source, flags] = tok.value.match(/^\/(.*)\/(\w*)$/); + + ret = new AST_RegExp({ start: tok, end: tok, value: { source, flags } }); + break; + case "atom": + switch (tok.value) { + case "false": + ret = new AST_False({ start: tok, end: tok }); + break; + case "true": + ret = new AST_True({ start: tok, end: tok }); + break; + case "null": + ret = new AST_Null({ start: tok, end: tok }); + break; + } + break; + } + next(); + return ret; + } + + function to_fun_args(ex, default_seen_above) { + var insert_default = function(ex, default_value) { + if (default_value) { + return new AST_DefaultAssign({ + start: ex.start, + left: ex, + operator: "=", + right: default_value, + end: default_value.end + }); + } + return ex; + }; + if (ex instanceof AST_Object) { + return insert_default(new AST_Destructuring({ + start: ex.start, + end: ex.end, + is_array: false, + names: ex.properties.map(prop => to_fun_args(prop)) + }), default_seen_above); + } else if (ex instanceof AST_ObjectKeyVal) { + ex.value = to_fun_args(ex.value); + return insert_default(ex, default_seen_above); + } else if (ex instanceof AST_Hole) { + return ex; + } else if (ex instanceof AST_Destructuring) { + ex.names = ex.names.map(name => to_fun_args(name)); + return insert_default(ex, default_seen_above); + } else if (ex instanceof AST_SymbolRef) { + return insert_default(new AST_SymbolFunarg({ + name: ex.name, + start: ex.start, + end: ex.end + }), default_seen_above); + } else if (ex instanceof AST_Expansion) { + ex.expression = to_fun_args(ex.expression); + return insert_default(ex, default_seen_above); + } else if (ex instanceof AST_Array) { + return insert_default(new AST_Destructuring({ + start: ex.start, + end: ex.end, + is_array: true, + names: ex.elements.map(elm => to_fun_args(elm)) + }), default_seen_above); + } else if (ex instanceof AST_Assign) { + return insert_default(to_fun_args(ex.left, ex.right), default_seen_above); + } else if (ex instanceof AST_DefaultAssign) { + ex.left = to_fun_args(ex.left); + return ex; + } else { + croak("Invalid function parameter", ex.start.line, ex.start.col); + } + } + + var expr_atom = function(allow_calls, allow_arrows) { + if (is("operator", "new")) { + return new_(allow_calls); + } + if (is("name", "import") && is_token(peek(), "punc", ".")) { + return import_meta(allow_calls); + } + var start = S.token; + var peeked; + var async = is("name", "async") + && (peeked = peek()).value != "[" + && peeked.type != "arrow" + && as_atom_node(); + if (is("punc")) { + switch (S.token.value) { + case "(": + if (async && !allow_calls) break; + var exprs = params_or_seq_(allow_arrows, !async); + if (allow_arrows && is("arrow", "=>")) { + return arrow_function(start, exprs.map(e => to_fun_args(e)), !!async); + } + var ex = async ? new AST_Call({ + expression: async, + args: exprs + }) : to_expr_or_sequence(start, exprs); + if (ex.start) { + const outer_comments_before = start.comments_before.length; + outer_comments_before_counts.set(start, outer_comments_before); + ex.start.comments_before.unshift(...start.comments_before); + start.comments_before = ex.start.comments_before; + if (outer_comments_before == 0 && start.comments_before.length > 0) { + var comment = start.comments_before[0]; + if (!comment.nlb) { + comment.nlb = start.nlb; + start.nlb = false; + } + } + start.comments_after = ex.start.comments_after; + } + ex.start = start; + var end = prev(); + if (ex.end) { + end.comments_before = ex.end.comments_before; + ex.end.comments_after.push(...end.comments_after); + end.comments_after = ex.end.comments_after; + } + ex.end = end; + if (ex instanceof AST_Call) annotate(ex); + return subscripts(ex, allow_calls); + case "[": + return subscripts(array_(), allow_calls); + case "{": + return subscripts(object_or_destructuring_(), allow_calls); + } + if (!async) unexpected(); + } + if (allow_arrows && is("name") && is_token(peek(), "arrow")) { + var param = new AST_SymbolFunarg({ + name: S.token.value, + start: start, + end: start, + }); + next(); + return arrow_function(start, [param], !!async); + } + if (is("keyword", "function")) { + next(); + var func = function_(AST_Function, false, !!async); + func.start = start; + func.end = prev(); + return subscripts(func, allow_calls); + } + if (async) return subscripts(async, allow_calls); + if (is("keyword", "class")) { + next(); + var cls = class_(AST_ClassExpression); + cls.start = start; + cls.end = prev(); + return subscripts(cls, allow_calls); + } + if (is("template_head")) { + return subscripts(template_string(), allow_calls); + } + if (ATOMIC_START_TOKEN.has(S.token.type)) { + return subscripts(as_atom_node(), allow_calls); + } + unexpected(); + }; + + function template_string() { + var segments = [], start = S.token; + + segments.push(new AST_TemplateSegment({ + start: S.token, + raw: TEMPLATE_RAWS.get(S.token), + value: S.token.value, + end: S.token + })); + + while (!S.token.template_end) { + next(); + handle_regexp(); + segments.push(expression(true)); + + segments.push(new AST_TemplateSegment({ + start: S.token, + raw: TEMPLATE_RAWS.get(S.token), + value: S.token.value, + end: S.token + })); + } + next(); + + return new AST_TemplateString({ + start: start, + segments: segments, + end: S.token + }); + } + + function expr_list(closing, allow_trailing_comma, allow_empty) { + var first = true, a = []; + while (!is("punc", closing)) { + if (first) first = false; else expect(","); + if (allow_trailing_comma && is("punc", closing)) break; + if (is("punc", ",") && allow_empty) { + a.push(new AST_Hole({ start: S.token, end: S.token })); + } else if (is("expand", "...")) { + next(); + a.push(new AST_Expansion({start: prev(), expression: expression(),end: S.token})); + } else { + a.push(expression(false)); + } + } + next(); + return a; + } + + var array_ = embed_tokens(function() { + expect("["); + return new AST_Array({ + elements: expr_list("]", !options.strict, true) + }); + }); + + var create_accessor = embed_tokens((is_generator, is_async) => { + return function_(AST_Accessor, is_generator, is_async); + }); + + var object_or_destructuring_ = embed_tokens(function object_or_destructuring_() { + var start = S.token, first = true, a = []; + expect("{"); + while (!is("punc", "}")) { + if (first) first = false; else expect(","); + if (!options.strict && is("punc", "}")) + // allow trailing comma + break; + + start = S.token; + if (start.type == "expand") { + next(); + a.push(new AST_Expansion({ + start: start, + expression: expression(false), + end: prev(), + })); + continue; + } + if(is("privatename")) { + croak("private fields are not allowed in an object"); + } + var name = as_property_name(); + var value; + + // Check property and fetch value + if (!is("punc", ":")) { + var concise = concise_method_or_getset(name, start); + if (concise) { + a.push(concise); + continue; + } + + value = new AST_SymbolRef({ + start: prev(), + name: name, + end: prev() + }); + } else if (name === null) { + unexpected(prev()); + } else { + next(); // `:` - see first condition + value = expression(false); + } + + // Check for default value and alter value accordingly if necessary + if (is("operator", "=")) { + next(); + value = new AST_Assign({ + start: start, + left: value, + operator: "=", + right: expression(false), + logical: false, + end: prev() + }); + } + + // Create property + const kv = new AST_ObjectKeyVal({ + start: start, + quote: start.quote, + key: name instanceof AST_Node ? name : "" + name, + value: value, + end: prev() + }); + a.push(annotate(kv)); + } + next(); + return new AST_Object({ properties: a }); + }); + + function class_(KindOfClass, is_export_default) { + var start, method, class_name, extends_, a = []; + + S.input.push_directives_stack(); // Push directive stack, but not scope stack + S.input.add_directive("use strict"); + + if (S.token.type == "name" && S.token.value != "extends") { + class_name = as_symbol(KindOfClass === AST_DefClass ? AST_SymbolDefClass : AST_SymbolClass); + } + + if (KindOfClass === AST_DefClass && !class_name) { + if (is_export_default) { + KindOfClass = AST_ClassExpression; + } else { + unexpected(); + } + } + + if (S.token.value == "extends") { + next(); + extends_ = expression(true); + } + + expect("{"); + // mark in class feild, + const save_in_class = S.in_class; + S.in_class = true; + while (is("punc", ";")) { next(); } // Leading semicolons are okay in class bodies. + while (!is("punc", "}")) { + start = S.token; + method = concise_method_or_getset(as_property_name(), start, true); + if (!method) { unexpected(); } + a.push(method); + while (is("punc", ";")) { next(); } + } + // mark in class feild, + S.in_class = save_in_class; + + S.input.pop_directives_stack(); + + next(); + + return new KindOfClass({ + start: start, + name: class_name, + extends: extends_, + properties: a, + end: prev(), + }); + } + + function concise_method_or_getset(name, start, is_class) { + const get_symbol_ast = (name, SymbolClass = AST_SymbolMethod) => { + if (typeof name === "string" || typeof name === "number") { + return new SymbolClass({ + start, + name: "" + name, + end: prev() + }); + } else if (name === null) { + unexpected(); + } + return name; + }; + + const is_not_method_start = () => + !is("punc", "(") && !is("punc", ",") && !is("punc", "}") && !is("punc", ";") && !is("operator", "="); + + var is_async = false; + var is_static = false; + var is_generator = false; + var is_private = false; + var accessor_type = null; + + if (is_class && name === "static" && is_not_method_start()) { + const static_block = class_static_block(); + if (static_block != null) { + return static_block; + } + is_static = true; + name = as_property_name(); + } + if (name === "async" && is_not_method_start()) { + is_async = true; + name = as_property_name(); + } + if (prev().type === "operator" && prev().value === "*") { + is_generator = true; + name = as_property_name(); + } + if ((name === "get" || name === "set") && is_not_method_start()) { + accessor_type = name; + name = as_property_name(); + } + if (prev().type === "privatename") { + is_private = true; + } + + const property_token = prev(); + + if (accessor_type != null) { + if (!is_private) { + const AccessorClass = accessor_type === "get" + ? AST_ObjectGetter + : AST_ObjectSetter; + + name = get_symbol_ast(name); + return annotate(new AccessorClass({ + start, + static: is_static, + key: name, + quote: name instanceof AST_SymbolMethod ? property_token.quote : undefined, + value: create_accessor(), + end: prev() + })); + } else { + const AccessorClass = accessor_type === "get" + ? AST_PrivateGetter + : AST_PrivateSetter; + + return annotate(new AccessorClass({ + start, + static: is_static, + key: get_symbol_ast(name), + value: create_accessor(), + end: prev(), + })); + } + } + + if (is("punc", "(")) { + name = get_symbol_ast(name); + const AST_MethodVariant = is_private + ? AST_PrivateMethod + : AST_ConciseMethod; + var node = new AST_MethodVariant({ + start : start, + static : is_static, + is_generator: is_generator, + async : is_async, + key : name, + quote : name instanceof AST_SymbolMethod ? + property_token.quote : undefined, + value : create_accessor(is_generator, is_async), + end : prev() + }); + return annotate(node); + } + + if (is_class) { + const key = get_symbol_ast(name, AST_SymbolClassProperty); + const quote = key instanceof AST_SymbolClassProperty + ? property_token.quote + : undefined; + const AST_ClassPropertyVariant = is_private + ? AST_ClassPrivateProperty + : AST_ClassProperty; + if (is("operator", "=")) { + next(); + return annotate( + new AST_ClassPropertyVariant({ + start, + static: is_static, + quote, + key, + value: expression(false), + end: prev() + }) + ); + } else if ( + is("name") + || is("privatename") + || is("operator", "*") + || is("punc", ";") + || is("punc", "}") + ) { + return annotate( + new AST_ClassPropertyVariant({ + start, + static: is_static, + quote, + key, + end: prev() + }) + ); + } + } + } + + function class_static_block() { + if (!is("punc", "{")) { + return null; + } + + const start = S.token; + const body = []; + + next(); + + while (!is("punc", "}")) { + body.push(statement()); + } + + next(); + + return new AST_ClassStaticBlock({ start, body, end: prev() }); + } + + function maybe_import_assertion() { + if (is("name", "assert") && !has_newline_before(S.token)) { + next(); + return object_or_destructuring_(); + } + return null; + } + + function import_statement() { + var start = prev(); + + var imported_name; + var imported_names; + if (is("name")) { + imported_name = as_symbol(AST_SymbolImport); + } + + if (is("punc", ",")) { + next(); + } + + imported_names = map_names(true); + + if (imported_names || imported_name) { + expect_token("name", "from"); + } + var mod_str = S.token; + if (mod_str.type !== "string") { + unexpected(); + } + next(); + + const assert_clause = maybe_import_assertion(); + + return new AST_Import({ + start, + imported_name, + imported_names, + module_name: new AST_String({ + start: mod_str, + value: mod_str.value, + quote: mod_str.quote, + end: mod_str, + }), + assert_clause, + end: S.token, + }); + } + + function import_meta(allow_calls) { + var start = S.token; + expect_token("name", "import"); + expect_token("punc", "."); + expect_token("name", "meta"); + return subscripts(new AST_ImportMeta({ + start: start, + end: prev() + }), allow_calls); + } + + function map_name(is_import) { + function make_symbol(type, quote) { + return new type({ + name: as_property_name(), + quote: quote || undefined, + start: prev(), + end: prev() + }); + } + + var foreign_type = is_import ? AST_SymbolImportForeign : AST_SymbolExportForeign; + var type = is_import ? AST_SymbolImport : AST_SymbolExport; + var start = S.token; + var foreign_name; + var name; + + if (is_import) { + foreign_name = make_symbol(foreign_type, start.quote); + } else { + name = make_symbol(type, start.quote); + } + if (is("name", "as")) { + next(); // The "as" word + if (is_import) { + name = make_symbol(type); + } else { + foreign_name = make_symbol(foreign_type, S.token.quote); + } + } else if (is_import) { + name = new type(foreign_name); + } else { + foreign_name = new foreign_type(name); + } + + return new AST_NameMapping({ + start: start, + foreign_name: foreign_name, + name: name, + end: prev(), + }); + } + + function map_nameAsterisk(is_import, import_or_export_foreign_name) { + var foreign_type = is_import ? AST_SymbolImportForeign : AST_SymbolExportForeign; + var type = is_import ? AST_SymbolImport : AST_SymbolExport; + var start = S.token; + var name, foreign_name; + var end = prev(); + + if (is_import) { + name = import_or_export_foreign_name; + } else { + foreign_name = import_or_export_foreign_name; + } + + name = name || new type({ + start: start, + name: "*", + end: end, + }); + + foreign_name = foreign_name || new foreign_type({ + start: start, + name: "*", + end: end, + }); + + return new AST_NameMapping({ + start: start, + foreign_name: foreign_name, + name: name, + end: end, + }); + } + + function map_names(is_import) { + var names; + if (is("punc", "{")) { + next(); + names = []; + while (!is("punc", "}")) { + names.push(map_name(is_import)); + if (is("punc", ",")) { + next(); + } + } + next(); + } else if (is("operator", "*")) { + var name; + next(); + if (is("name", "as")) { + next(); // The "as" word + name = is_import ? as_symbol(AST_SymbolImport) : as_symbol_or_string(AST_SymbolExportForeign); + } + names = [map_nameAsterisk(is_import, name)]; + } + return names; + } + + function export_statement() { + var start = S.token; + var is_default; + var exported_names; + + if (is("keyword", "default")) { + is_default = true; + next(); + } else if (exported_names = map_names(false)) { + if (is("name", "from")) { + next(); + + var mod_str = S.token; + if (mod_str.type !== "string") { + unexpected(); + } + next(); + + const assert_clause = maybe_import_assertion(); + + return new AST_Export({ + start: start, + is_default: is_default, + exported_names: exported_names, + module_name: new AST_String({ + start: mod_str, + value: mod_str.value, + quote: mod_str.quote, + end: mod_str, + }), + end: prev(), + assert_clause + }); + } else { + return new AST_Export({ + start: start, + is_default: is_default, + exported_names: exported_names, + end: prev(), + }); + } + } + + var node; + var exported_value; + var exported_definition; + if (is("punc", "{") + || is_default + && (is("keyword", "class") || is("keyword", "function")) + && is_token(peek(), "punc")) { + exported_value = expression(false); + semicolon(); + } else if ((node = statement(is_default)) instanceof AST_Definitions && is_default) { + unexpected(node.start); + } else if ( + node instanceof AST_Definitions + || node instanceof AST_Defun + || node instanceof AST_DefClass + ) { + exported_definition = node; + } else if ( + node instanceof AST_ClassExpression + || node instanceof AST_Function + ) { + exported_value = node; + } else if (node instanceof AST_SimpleStatement) { + exported_value = node.body; + } else { + unexpected(node.start); + } + + return new AST_Export({ + start: start, + is_default: is_default, + exported_value: exported_value, + exported_definition: exported_definition, + end: prev(), + assert_clause: null + }); + } + + function as_property_name() { + var tmp = S.token; + switch (tmp.type) { + case "punc": + if (tmp.value === "[") { + next(); + var ex = expression(false); + expect("]"); + return ex; + } else unexpected(tmp); + case "operator": + if (tmp.value === "*") { + next(); + return null; + } + if (!["delete", "in", "instanceof", "new", "typeof", "void"].includes(tmp.value)) { + unexpected(tmp); + } + /* falls through */ + case "name": + case "privatename": + case "string": + case "num": + case "big_int": + case "keyword": + case "atom": + next(); + return tmp.value; + default: + unexpected(tmp); + } + } + + function as_name() { + var tmp = S.token; + if (tmp.type != "name" && tmp.type != "privatename") unexpected(); + next(); + return tmp.value; + } + + function _make_symbol(type) { + var name = S.token.value; + return new (name == "this" ? AST_This : + name == "super" ? AST_Super : + type)({ + name : String(name), + start : S.token, + end : S.token + }); + } + + function _verify_symbol(sym) { + var name = sym.name; + if (is_in_generator() && name == "yield") { + token_error(sym.start, "Yield cannot be used as identifier inside generators"); + } + if (S.input.has_directive("use strict")) { + if (name == "yield") { + token_error(sym.start, "Unexpected yield identifier inside strict mode"); + } + if (sym instanceof AST_SymbolDeclaration && (name == "arguments" || name == "eval")) { + token_error(sym.start, "Unexpected " + name + " in strict mode"); + } + } + } + + function as_symbol(type, noerror) { + if (!is("name")) { + if (!noerror) croak("Name expected"); + return null; + } + var sym = _make_symbol(type); + _verify_symbol(sym); + next(); + return sym; + } + + function as_symbol_or_string(type) { + if (!is("name")) { + if (!is("string")) { + croak("Name or string expected"); + } + var tok = S.token; + var ret = new type({ + start : tok, + end : tok, + name : tok.value, + quote : tok.quote + }); + next(); + return ret; + } + var sym = _make_symbol(type); + _verify_symbol(sym); + next(); + return sym; + } + + // Annotate AST_Call, AST_Lambda or AST_New with the special comments + function annotate(node, before_token = node.start) { + var comments = before_token.comments_before; + const comments_outside_parens = outer_comments_before_counts.get(before_token); + var i = comments_outside_parens != null ? comments_outside_parens : comments.length; + while (--i >= 0) { + var comment = comments[i]; + if (/[@#]__/.test(comment.value)) { + if (/[@#]__PURE__/.test(comment.value)) { + set_annotation(node, _PURE); + break; + } + if (/[@#]__INLINE__/.test(comment.value)) { + set_annotation(node, _INLINE); + break; + } + if (/[@#]__NOINLINE__/.test(comment.value)) { + set_annotation(node, _NOINLINE); + break; + } + if (/[@#]__KEY__/.test(comment.value)) { + set_annotation(node, _KEY); + break; + } + if (/[@#]__MANGLE_PROP__/.test(comment.value)) { + set_annotation(node, _MANGLEPROP); + break; + } + } + } + return node; + } + + var subscripts = function(expr, allow_calls, is_chain) { + var start = expr.start; + if (is("punc", ".")) { + next(); + if(is("privatename") && !S.in_class) + croak("Private field must be used in an enclosing class"); + const AST_DotVariant = is("privatename") ? AST_DotHash : AST_Dot; + return annotate(subscripts(new AST_DotVariant({ + start : start, + expression : expr, + optional : false, + property : as_name(), + end : prev() + }), allow_calls, is_chain)); + } + if (is("punc", "[")) { + next(); + var prop = expression(true); + expect("]"); + return annotate(subscripts(new AST_Sub({ + start : start, + expression : expr, + optional : false, + property : prop, + end : prev() + }), allow_calls, is_chain)); + } + if (allow_calls && is("punc", "(")) { + next(); + var call = new AST_Call({ + start : start, + expression : expr, + optional : false, + args : call_args(), + end : prev() + }); + annotate(call); + return subscripts(call, true, is_chain); + } + + if (is("punc", "?.")) { + next(); + + let chain_contents; + + if (allow_calls && is("punc", "(")) { + next(); + + const call = new AST_Call({ + start, + optional: true, + expression: expr, + args: call_args(), + end: prev() + }); + annotate(call); + + chain_contents = subscripts(call, true, true); + } else if (is("name") || is("privatename")) { + if(is("privatename") && !S.in_class) + croak("Private field must be used in an enclosing class"); + const AST_DotVariant = is("privatename") ? AST_DotHash : AST_Dot; + chain_contents = annotate(subscripts(new AST_DotVariant({ + start, + expression: expr, + optional: true, + property: as_name(), + end: prev() + }), allow_calls, true)); + } else if (is("punc", "[")) { + next(); + const property = expression(true); + expect("]"); + chain_contents = annotate(subscripts(new AST_Sub({ + start, + expression: expr, + optional: true, + property, + end: prev() + }), allow_calls, true)); + } + + if (!chain_contents) unexpected(); + + if (chain_contents instanceof AST_Chain) return chain_contents; + + return new AST_Chain({ + start, + expression: chain_contents, + end: prev() + }); + } + + if (is("template_head")) { + if (is_chain) { + // a?.b`c` is a syntax error + unexpected(); + } + + return subscripts(new AST_PrefixedTemplateString({ + start: start, + prefix: expr, + template_string: template_string(), + end: prev() + }), allow_calls); + } + return expr; + }; + + function call_args() { + var args = []; + while (!is("punc", ")")) { + if (is("expand", "...")) { + next(); + args.push(new AST_Expansion({ + start: prev(), + expression: expression(false), + end: prev() + })); + } else { + args.push(expression(false)); + } + if (!is("punc", ")")) { + expect(","); + } + } + next(); + return args; + } + + var maybe_unary = function(allow_calls, allow_arrows) { + var start = S.token; + if (start.type == "name" && start.value == "await" && can_await()) { + next(); + return _await_expression(); + } + if (is("operator") && UNARY_PREFIX.has(start.value)) { + next(); + handle_regexp(); + var ex = make_unary(AST_UnaryPrefix, start, maybe_unary(allow_calls)); + ex.start = start; + ex.end = prev(); + return ex; + } + var val = expr_atom(allow_calls, allow_arrows); + while (is("operator") && UNARY_POSTFIX.has(S.token.value) && !has_newline_before(S.token)) { + if (val instanceof AST_Arrow) unexpected(); + val = make_unary(AST_UnaryPostfix, S.token, val); + val.start = start; + val.end = S.token; + next(); + } + return val; + }; + + function make_unary(ctor, token, expr) { + var op = token.value; + switch (op) { + case "++": + case "--": + if (!is_assignable(expr)) + croak("Invalid use of " + op + " operator", token.line, token.col, token.pos); + break; + case "delete": + if (expr instanceof AST_SymbolRef && S.input.has_directive("use strict")) + croak("Calling delete on expression not allowed in strict mode", expr.start.line, expr.start.col, expr.start.pos); + break; + } + return new ctor({ operator: op, expression: expr }); + } + + var expr_op = function(left, min_prec, no_in) { + var op = is("operator") ? S.token.value : null; + if (op == "in" && no_in) op = null; + if (op == "**" && left instanceof AST_UnaryPrefix + /* unary token in front not allowed - parenthesis required */ + && !is_token(left.start, "punc", "(") + && left.operator !== "--" && left.operator !== "++") + unexpected(left.start); + var prec = op != null ? PRECEDENCE[op] : null; + if (prec != null && (prec > min_prec || (op === "**" && min_prec === prec))) { + next(); + var right = expr_ops(no_in, prec, true); + return expr_op(new AST_Binary({ + start : left.start, + left : left, + operator : op, + right : right, + end : right.end + }), min_prec, no_in); + } + return left; + }; + + function expr_ops(no_in, min_prec, allow_calls, allow_arrows) { + // maybe_unary won't return us a AST_SymbolPrivateProperty + if (!no_in && min_prec < PRECEDENCE["in"] && is("privatename")) { + if(!S.in_class) { + croak("Private field must be used in an enclosing class"); + } + + const start = S.token; + const key = new AST_SymbolPrivateProperty({ + start, + name: start.value, + end: start + }); + next(); + expect_token("operator", "in"); + + const private_in = new AST_PrivateIn({ + start, + key, + value: expr_ops(no_in, PRECEDENCE["in"], true), + end: prev() + }); + + return expr_op(private_in, 0, no_in); + } else { + return expr_op(maybe_unary(allow_calls, allow_arrows), min_prec, no_in); + } + } + + var maybe_conditional = function(no_in) { + var start = S.token; + var expr = expr_ops(no_in, 0, true, true); + if (is("operator", "?")) { + next(); + var yes = expression(false); + expect(":"); + return new AST_Conditional({ + start : start, + condition : expr, + consequent : yes, + alternative : expression(false, no_in), + end : prev() + }); + } + return expr; + }; + + function is_assignable(expr) { + return expr instanceof AST_PropAccess || expr instanceof AST_SymbolRef; + } + + function to_destructuring(node) { + if (node instanceof AST_Object) { + node = new AST_Destructuring({ + start: node.start, + names: node.properties.map(to_destructuring), + is_array: false, + end: node.end + }); + } else if (node instanceof AST_Array) { + var names = []; + + for (var i = 0; i < node.elements.length; i++) { + // Only allow expansion as last element + if (node.elements[i] instanceof AST_Expansion) { + if (i + 1 !== node.elements.length) { + token_error(node.elements[i].start, "Spread must the be last element in destructuring array"); + } + node.elements[i].expression = to_destructuring(node.elements[i].expression); + } + + names.push(to_destructuring(node.elements[i])); + } + + node = new AST_Destructuring({ + start: node.start, + names: names, + is_array: true, + end: node.end + }); + } else if (node instanceof AST_ObjectProperty) { + node.value = to_destructuring(node.value); + } else if (node instanceof AST_Assign) { + node = new AST_DefaultAssign({ + start: node.start, + left: node.left, + operator: "=", + right: node.right, + end: node.end + }); + } + return node; + } + + // In ES6, AssignmentExpression can also be an ArrowFunction + var maybe_assign = function(no_in) { + handle_regexp(); + var start = S.token; + + if (start.type == "name" && start.value == "yield") { + if (is_in_generator()) { + next(); + return _yield_expression(); + } else if (S.input.has_directive("use strict")) { + token_error(S.token, "Unexpected yield identifier inside strict mode"); + } + } + + var left = maybe_conditional(no_in); + var val = S.token.value; + + if (is("operator") && ASSIGNMENT.has(val)) { + if (is_assignable(left) || (left = to_destructuring(left)) instanceof AST_Destructuring) { + next(); + + return new AST_Assign({ + start : start, + left : left, + operator : val, + right : maybe_assign(no_in), + logical : LOGICAL_ASSIGNMENT.has(val), + end : prev() + }); + } + croak("Invalid assignment"); + } + return left; + }; + + var to_expr_or_sequence = function(start, exprs) { + if (exprs.length === 1) { + return exprs[0]; + } else if (exprs.length > 1) { + return new AST_Sequence({ start, expressions: exprs, end: peek() }); + } else { + croak("Invalid parenthesized expression"); + } + }; + + var expression = function(commas, no_in) { + var start = S.token; + var exprs = []; + while (true) { + exprs.push(maybe_assign(no_in)); + if (!commas || !is("punc", ",")) break; + next(); + commas = true; + } + return to_expr_or_sequence(start, exprs); + }; + + function in_loop(cont) { + ++S.in_loop; + var ret = cont(); + --S.in_loop; + return ret; + } + + if (options.expression) { + return expression(true); + } + + return (function parse_toplevel() { + var start = S.token; + var body = []; + S.input.push_directives_stack(); + if (options.module) S.input.add_directive("use strict"); + while (!is("eof")) { + body.push(statement()); + } + S.input.pop_directives_stack(); + var end = prev(); + var toplevel = options.toplevel; + if (toplevel) { + toplevel.body = toplevel.body.concat(body); + toplevel.end = end; + } else { + toplevel = new AST_Toplevel({ start: start, body: body, end: end }); + } + TEMPLATE_RAWS = new Map(); + return toplevel; + })(); + +} + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +function DEFNODE(type, props, ctor, methods, base = AST_Node) { + if (!props) props = []; + else props = props.split(/\s+/); + var self_props = props; + if (base && base.PROPS) + props = props.concat(base.PROPS); + const proto = base && Object.create(base.prototype); + if (proto) { + ctor.prototype = proto; + ctor.BASE = base; + } + if (base) base.SUBCLASSES.push(ctor); + ctor.prototype.CTOR = ctor; + ctor.prototype.constructor = ctor; + ctor.PROPS = props || null; + ctor.SELF_PROPS = self_props; + ctor.SUBCLASSES = []; + if (type) { + ctor.prototype.TYPE = ctor.TYPE = type; + } + if (methods) for (let i in methods) if (HOP(methods, i)) { + if (i[0] === "$") { + ctor[i.substr(1)] = methods[i]; + } else { + ctor.prototype[i] = methods[i]; + } + } + ctor.DEFMETHOD = function(name, method) { + this.prototype[name] = method; + }; + return ctor; +} + +const has_tok_flag = (tok, flag) => Boolean(tok.flags & flag); +const set_tok_flag = (tok, flag, truth) => { + if (truth) { + tok.flags |= flag; + } else { + tok.flags &= ~flag; + } +}; + +const TOK_FLAG_NLB = 0b0001; +const TOK_FLAG_QUOTE_SINGLE = 0b0010; +const TOK_FLAG_QUOTE_EXISTS = 0b0100; +const TOK_FLAG_TEMPLATE_END = 0b1000; + +class AST_Token { + constructor(type, value, line, col, pos, nlb, comments_before, comments_after, file) { + this.flags = (nlb ? 1 : 0); + + this.type = type; + this.value = value; + this.line = line; + this.col = col; + this.pos = pos; + this.comments_before = comments_before; + this.comments_after = comments_after; + this.file = file; + + Object.seal(this); + } + + // Return a string summary of the token for node.js console.log + [Symbol.for("nodejs.util.inspect.custom")](_depth, options) { + const special = str => options.stylize(str, "special"); + const quote = typeof this.value === "string" && this.value.includes("`") ? "'" : "`"; + const value = `${quote}${this.value}${quote}`; + return `${special("[AST_Token")} ${value} at ${this.line}:${this.col}${special("]")}`; + } + + get nlb() { + return has_tok_flag(this, TOK_FLAG_NLB); + } + + set nlb(new_nlb) { + set_tok_flag(this, TOK_FLAG_NLB, new_nlb); + } + + get quote() { + return !has_tok_flag(this, TOK_FLAG_QUOTE_EXISTS) + ? "" + : (has_tok_flag(this, TOK_FLAG_QUOTE_SINGLE) ? "'" : '"'); + } + + set quote(quote_type) { + set_tok_flag(this, TOK_FLAG_QUOTE_SINGLE, quote_type === "'"); + set_tok_flag(this, TOK_FLAG_QUOTE_EXISTS, !!quote_type); + } + + get template_end() { + return has_tok_flag(this, TOK_FLAG_TEMPLATE_END); + } + + set template_end(new_template_end) { + set_tok_flag(this, TOK_FLAG_TEMPLATE_END, new_template_end); + } +} + +var AST_Node = DEFNODE("Node", "start end", function AST_Node(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + _clone: function(deep) { + if (deep) { + var self = this.clone(); + return self.transform(new TreeTransformer(function(node) { + if (node !== self) { + return node.clone(true); + } + })); + } + return new this.CTOR(this); + }, + clone: function(deep) { + return this._clone(deep); + }, + $documentation: "Base class of all AST nodes", + $propdoc: { + start: "[AST_Token] The first token of this node", + end: "[AST_Token] The last token of this node" + }, + _walk: function(visitor) { + return visitor._visit(this); + }, + walk: function(visitor) { + return this._walk(visitor); // not sure the indirection will be any help + }, + _children_backwards: () => {} +}, null); + +/* -----[ statements ]----- */ + +var AST_Statement = DEFNODE("Statement", null, function AST_Statement(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class of all statements", +}); + +var AST_Debugger = DEFNODE("Debugger", null, function AST_Debugger(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Represents a debugger statement", +}, AST_Statement); + +var AST_Directive = DEFNODE("Directive", "value quote", function AST_Directive(props) { + if (props) { + this.value = props.value; + this.quote = props.quote; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Represents a directive, like \"use strict\";", + $propdoc: { + value: "[string] The value of this directive as a plain string (it's not an AST_String!)", + quote: "[string] the original quote character" + }, +}, AST_Statement); + +var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", function AST_SimpleStatement(props) { + if (props) { + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A statement consisting of an expression, i.e. a = 1 + 2", + $propdoc: { + body: "[AST_Node] an expression node (should not be instanceof AST_Statement)" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + } +}, AST_Statement); + +function walk_body(node, visitor) { + const body = node.body; + for (var i = 0, len = body.length; i < len; i++) { + body[i]._walk(visitor); + } +} + +function clone_block_scope(deep) { + var clone = this._clone(deep); + if (this.block_scope) { + clone.block_scope = this.block_scope.clone(); + } + return clone; +} + +var AST_Block = DEFNODE("Block", "body block_scope", function AST_Block(props) { + if (props) { + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A body of statements (usually braced)", + $propdoc: { + body: "[AST_Statement*] an array of statements", + block_scope: "[AST_Scope] the block scope" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + }, + clone: clone_block_scope +}, AST_Statement); + +var AST_BlockStatement = DEFNODE("BlockStatement", null, function AST_BlockStatement(props) { + if (props) { + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A block statement", +}, AST_Block); + +var AST_EmptyStatement = DEFNODE("EmptyStatement", null, function AST_EmptyStatement(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The empty statement (empty block or simply a semicolon)" +}, AST_Statement); + +var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", function AST_StatementWithBody(props) { + if (props) { + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`", + $propdoc: { + body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement" + } +}, AST_Statement); + +var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", function AST_LabeledStatement(props) { + if (props) { + this.label = props.label; + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Statement with a label", + $propdoc: { + label: "[AST_Label] a label definition" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.label._walk(visitor); + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + push(this.label); + }, + clone: function(deep) { + var node = this._clone(deep); + if (deep) { + var label = node.label; + var def = this.label; + node.walk(new TreeWalker(function(node) { + if (node instanceof AST_LoopControl + && node.label && node.label.thedef === def) { + node.label.thedef = label; + label.references.push(node); + } + })); + } + return node; + } +}, AST_StatementWithBody); + +var AST_IterationStatement = DEFNODE( + "IterationStatement", + "block_scope", + function AST_IterationStatement(props) { + if (props) { + this.block_scope = props.block_scope; + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; + }, + { + $documentation: "Internal class. All loops inherit from it.", + $propdoc: { + block_scope: "[AST_Scope] the block scope for this iteration statement." + }, + clone: clone_block_scope + }, + AST_StatementWithBody +); + +var AST_DWLoop = DEFNODE("DWLoop", "condition", function AST_DWLoop(props) { + if (props) { + this.condition = props.condition; + this.block_scope = props.block_scope; + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for do/while statements", + $propdoc: { + condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement" + } +}, AST_IterationStatement); + +var AST_Do = DEFNODE("Do", null, function AST_Do(props) { + if (props) { + this.condition = props.condition; + this.block_scope = props.block_scope; + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `do` statement", + _walk: function(visitor) { + return visitor._visit(this, function() { + this.body._walk(visitor); + this.condition._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.condition); + push(this.body); + } +}, AST_DWLoop); + +var AST_While = DEFNODE("While", null, function AST_While(props) { + if (props) { + this.condition = props.condition; + this.block_scope = props.block_scope; + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `while` statement", + _walk: function(visitor) { + return visitor._visit(this, function() { + this.condition._walk(visitor); + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + push(this.condition); + }, +}, AST_DWLoop); + +var AST_For = DEFNODE("For", "init condition step", function AST_For(props) { + if (props) { + this.init = props.init; + this.condition = props.condition; + this.step = props.step; + this.block_scope = props.block_scope; + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `for` statement", + $propdoc: { + init: "[AST_Node?] the `for` initialization code, or null if empty", + condition: "[AST_Node?] the `for` termination clause, or null if empty", + step: "[AST_Node?] the `for` update clause, or null if empty" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.init) this.init._walk(visitor); + if (this.condition) this.condition._walk(visitor); + if (this.step) this.step._walk(visitor); + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + if (this.step) push(this.step); + if (this.condition) push(this.condition); + if (this.init) push(this.init); + }, +}, AST_IterationStatement); + +var AST_ForIn = DEFNODE("ForIn", "init object", function AST_ForIn(props) { + if (props) { + this.init = props.init; + this.object = props.object; + this.block_scope = props.block_scope; + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `for ... in` statement", + $propdoc: { + init: "[AST_Node] the `for/in` initialization code", + object: "[AST_Node] the object that we're looping through" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.init._walk(visitor); + this.object._walk(visitor); + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + if (this.object) push(this.object); + if (this.init) push(this.init); + }, +}, AST_IterationStatement); + +var AST_ForOf = DEFNODE("ForOf", "await", function AST_ForOf(props) { + if (props) { + this.await = props.await; + this.init = props.init; + this.object = props.object; + this.block_scope = props.block_scope; + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `for ... of` statement", +}, AST_ForIn); + +var AST_With = DEFNODE("With", "expression", function AST_With(props) { + if (props) { + this.expression = props.expression; + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `with` statement", + $propdoc: { + expression: "[AST_Node] the `with` expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + push(this.expression); + }, +}, AST_StatementWithBody); + +/* -----[ scope and functions ]----- */ + +var AST_Scope = DEFNODE( + "Scope", + "variables uses_with uses_eval parent_scope enclosed cname", + function AST_Scope(props) { + if (props) { + this.variables = props.variables; + this.uses_with = props.uses_with; + this.uses_eval = props.uses_eval; + this.parent_scope = props.parent_scope; + this.enclosed = props.enclosed; + this.cname = props.cname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; + }, + { + $documentation: "Base class for all statements introducing a lexical scope", + $propdoc: { + variables: "[Map/S] a map of name -> SymbolDef for all variables/functions defined in this scope", + uses_with: "[boolean/S] tells whether this scope uses the `with` statement", + uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`", + parent_scope: "[AST_Scope?/S] link to the parent scope", + enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes", + cname: "[integer/S] current index for mangling variables (used internally by the mangler)", + }, + get_defun_scope: function() { + var self = this; + while (self.is_block_scope()) { + self = self.parent_scope; + } + return self; + }, + clone: function(deep, toplevel) { + var node = this._clone(deep); + if (deep && this.variables && toplevel && !this._block_scope) { + node.figure_out_scope({}, { + toplevel: toplevel, + parent_scope: this.parent_scope + }); + } else { + if (this.variables) node.variables = new Map(this.variables); + if (this.enclosed) node.enclosed = this.enclosed.slice(); + if (this._block_scope) node._block_scope = this._block_scope; + } + return node; + }, + pinned: function() { + return this.uses_eval || this.uses_with; + } + }, + AST_Block +); + +var AST_Toplevel = DEFNODE("Toplevel", "globals", function AST_Toplevel(props) { + if (props) { + this.globals = props.globals; + this.variables = props.variables; + this.uses_with = props.uses_with; + this.uses_eval = props.uses_eval; + this.parent_scope = props.parent_scope; + this.enclosed = props.enclosed; + this.cname = props.cname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The toplevel scope", + $propdoc: { + globals: "[Map/S] a map of name -> SymbolDef for all undeclared names", + }, + wrap_commonjs: function(name) { + var body = this.body; + var wrapped_tl = "(function(exports){'$ORIG';})(typeof " + name + "=='undefined'?(" + name + "={}):" + name + ");"; + wrapped_tl = parse(wrapped_tl); + wrapped_tl = wrapped_tl.transform(new TreeTransformer(function(node) { + if (node instanceof AST_Directive && node.value == "$ORIG") { + return MAP.splice(body); + } + })); + return wrapped_tl; + }, + wrap_enclose: function(args_values) { + if (typeof args_values != "string") args_values = ""; + var index = args_values.indexOf(":"); + if (index < 0) index = args_values.length; + var body = this.body; + return parse([ + "(function(", + args_values.slice(0, index), + '){"$ORIG"})(', + args_values.slice(index + 1), + ")" + ].join("")).transform(new TreeTransformer(function(node) { + if (node instanceof AST_Directive && node.value == "$ORIG") { + return MAP.splice(body); + } + })); + } +}, AST_Scope); + +var AST_Expansion = DEFNODE("Expansion", "expression", function AST_Expansion(props) { + if (props) { + this.expression = props.expression; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "An expandible argument, such as ...rest, a splat, such as [1,2,...all], or an expansion in a variable declaration, such as var [first, ...rest] = list", + $propdoc: { + expression: "[AST_Node] the thing to be expanded" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression.walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}); + +var AST_Lambda = DEFNODE( + "Lambda", + "name argnames uses_arguments is_generator async", + function AST_Lambda(props) { + if (props) { + this.name = props.name; + this.argnames = props.argnames; + this.uses_arguments = props.uses_arguments; + this.is_generator = props.is_generator; + this.async = props.async; + this.variables = props.variables; + this.uses_with = props.uses_with; + this.uses_eval = props.uses_eval; + this.parent_scope = props.parent_scope; + this.enclosed = props.enclosed; + this.cname = props.cname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; + }, + { + $documentation: "Base class for functions", + $propdoc: { + name: "[AST_SymbolDeclaration?] the name of this function", + argnames: "[AST_SymbolFunarg|AST_Destructuring|AST_Expansion|AST_DefaultAssign*] array of function arguments, destructurings, or expanding arguments", + uses_arguments: "[boolean/S] tells whether this function accesses the arguments array", + is_generator: "[boolean] is this a generator method", + async: "[boolean] is this method async", + }, + args_as_names: function () { + var out = []; + for (var i = 0; i < this.argnames.length; i++) { + if (this.argnames[i] instanceof AST_Destructuring) { + out.push(...this.argnames[i].all_symbols()); + } else { + out.push(this.argnames[i]); + } + } + return out; + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.name) this.name._walk(visitor); + var argnames = this.argnames; + for (var i = 0, len = argnames.length; i < len; i++) { + argnames[i]._walk(visitor); + } + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + + i = this.argnames.length; + while (i--) push(this.argnames[i]); + + if (this.name) push(this.name); + }, + is_braceless() { + return this.body[0] instanceof AST_Return && this.body[0].value; + }, + // Default args and expansion don't count, so .argnames.length doesn't cut it + length_property() { + let length = 0; + + for (const arg of this.argnames) { + if (arg instanceof AST_SymbolFunarg || arg instanceof AST_Destructuring) { + length++; + } + } + + return length; + } + }, + AST_Scope +); + +var AST_Accessor = DEFNODE("Accessor", null, function AST_Accessor(props) { + if (props) { + this.name = props.name; + this.argnames = props.argnames; + this.uses_arguments = props.uses_arguments; + this.is_generator = props.is_generator; + this.async = props.async; + this.variables = props.variables; + this.uses_with = props.uses_with; + this.uses_eval = props.uses_eval; + this.parent_scope = props.parent_scope; + this.enclosed = props.enclosed; + this.cname = props.cname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A setter/getter function. The `name` property is always null." +}, AST_Lambda); + +var AST_Function = DEFNODE("Function", null, function AST_Function(props) { + if (props) { + this.name = props.name; + this.argnames = props.argnames; + this.uses_arguments = props.uses_arguments; + this.is_generator = props.is_generator; + this.async = props.async; + this.variables = props.variables; + this.uses_with = props.uses_with; + this.uses_eval = props.uses_eval; + this.parent_scope = props.parent_scope; + this.enclosed = props.enclosed; + this.cname = props.cname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A function expression" +}, AST_Lambda); + +var AST_Arrow = DEFNODE("Arrow", null, function AST_Arrow(props) { + if (props) { + this.name = props.name; + this.argnames = props.argnames; + this.uses_arguments = props.uses_arguments; + this.is_generator = props.is_generator; + this.async = props.async; + this.variables = props.variables; + this.uses_with = props.uses_with; + this.uses_eval = props.uses_eval; + this.parent_scope = props.parent_scope; + this.enclosed = props.enclosed; + this.cname = props.cname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "An ES6 Arrow function ((a) => b)" +}, AST_Lambda); + +var AST_Defun = DEFNODE("Defun", null, function AST_Defun(props) { + if (props) { + this.name = props.name; + this.argnames = props.argnames; + this.uses_arguments = props.uses_arguments; + this.is_generator = props.is_generator; + this.async = props.async; + this.variables = props.variables; + this.uses_with = props.uses_with; + this.uses_eval = props.uses_eval; + this.parent_scope = props.parent_scope; + this.enclosed = props.enclosed; + this.cname = props.cname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A function definition" +}, AST_Lambda); + +/* -----[ DESTRUCTURING ]----- */ +var AST_Destructuring = DEFNODE("Destructuring", "names is_array", function AST_Destructuring(props) { + if (props) { + this.names = props.names; + this.is_array = props.is_array; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A destructuring of several names. Used in destructuring assignment and with destructuring function argument names", + $propdoc: { + "names": "[AST_Node*] Array of properties or elements", + "is_array": "[Boolean] Whether the destructuring represents an object or array" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.names.forEach(function(name) { + name._walk(visitor); + }); + }); + }, + _children_backwards(push) { + let i = this.names.length; + while (i--) push(this.names[i]); + }, + all_symbols: function() { + var out = []; + walk(this, node => { + if (node instanceof AST_SymbolDeclaration) { + out.push(node); + } + if (node instanceof AST_Lambda) { + return true; + } + }); + return out; + } +}); + +var AST_PrefixedTemplateString = DEFNODE( + "PrefixedTemplateString", + "template_string prefix", + function AST_PrefixedTemplateString(props) { + if (props) { + this.template_string = props.template_string; + this.prefix = props.prefix; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; + }, + { + $documentation: "A templatestring with a prefix, such as String.raw`foobarbaz`", + $propdoc: { + template_string: "[AST_TemplateString] The template string", + prefix: "[AST_Node] The prefix, which will get called." + }, + _walk: function(visitor) { + return visitor._visit(this, function () { + this.prefix._walk(visitor); + this.template_string._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.template_string); + push(this.prefix); + }, + } +); + +var AST_TemplateString = DEFNODE("TemplateString", "segments", function AST_TemplateString(props) { + if (props) { + this.segments = props.segments; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A template string literal", + $propdoc: { + segments: "[AST_Node*] One or more segments, starting with AST_TemplateSegment. AST_Node may follow AST_TemplateSegment, but each AST_Node must be followed by AST_TemplateSegment." + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.segments.forEach(function(seg) { + seg._walk(visitor); + }); + }); + }, + _children_backwards(push) { + let i = this.segments.length; + while (i--) push(this.segments[i]); + } +}); + +var AST_TemplateSegment = DEFNODE("TemplateSegment", "value raw", function AST_TemplateSegment(props) { + if (props) { + this.value = props.value; + this.raw = props.raw; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A segment of a template string literal", + $propdoc: { + value: "Content of the segment", + raw: "Raw source of the segment", + } +}); + +/* -----[ JUMPS ]----- */ + +var AST_Jump = DEFNODE("Jump", null, function AST_Jump(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)" +}, AST_Statement); + +/** Base class for “exits” (`return` and `throw`) */ +var AST_Exit = DEFNODE("Exit", "value", function AST_Exit(props) { + if (props) { + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for “exits” (`return` and `throw`)", + $propdoc: { + value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return" + }, + _walk: function(visitor) { + return visitor._visit(this, this.value && function() { + this.value._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.value) push(this.value); + }, +}, AST_Jump); + +var AST_Return = DEFNODE("Return", null, function AST_Return(props) { + if (props) { + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `return` statement" +}, AST_Exit); + +var AST_Throw = DEFNODE("Throw", null, function AST_Throw(props) { + if (props) { + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `throw` statement" +}, AST_Exit); + +var AST_LoopControl = DEFNODE("LoopControl", "label", function AST_LoopControl(props) { + if (props) { + this.label = props.label; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for loop control statements (`break` and `continue`)", + $propdoc: { + label: "[AST_LabelRef?] the label, or null if none", + }, + _walk: function(visitor) { + return visitor._visit(this, this.label && function() { + this.label._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.label) push(this.label); + }, +}, AST_Jump); + +var AST_Break = DEFNODE("Break", null, function AST_Break(props) { + if (props) { + this.label = props.label; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `break` statement" +}, AST_LoopControl); + +var AST_Continue = DEFNODE("Continue", null, function AST_Continue(props) { + if (props) { + this.label = props.label; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `continue` statement" +}, AST_LoopControl); + +var AST_Await = DEFNODE("Await", "expression", function AST_Await(props) { + if (props) { + this.expression = props.expression; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "An `await` statement", + $propdoc: { + expression: "[AST_Node] the mandatory expression being awaited", + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}); + +var AST_Yield = DEFNODE("Yield", "expression is_star", function AST_Yield(props) { + if (props) { + this.expression = props.expression; + this.is_star = props.is_star; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `yield` statement", + $propdoc: { + expression: "[AST_Node?] the value returned or thrown by this statement; could be null (representing undefined) but only when is_star is set to false", + is_star: "[Boolean] Whether this is a yield or yield* statement" + }, + _walk: function(visitor) { + return visitor._visit(this, this.expression && function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.expression) push(this.expression); + } +}); + +/* -----[ IF ]----- */ + +var AST_If = DEFNODE("If", "condition alternative", function AST_If(props) { + if (props) { + this.condition = props.condition; + this.alternative = props.alternative; + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `if` statement", + $propdoc: { + condition: "[AST_Node] the `if` condition", + alternative: "[AST_Statement?] the `else` part, or null if not present" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.condition._walk(visitor); + this.body._walk(visitor); + if (this.alternative) this.alternative._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.alternative) { + push(this.alternative); + } + push(this.body); + push(this.condition); + } +}, AST_StatementWithBody); + +/* -----[ SWITCH ]----- */ + +var AST_Switch = DEFNODE("Switch", "expression", function AST_Switch(props) { + if (props) { + this.expression = props.expression; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `switch` statement", + $propdoc: { + expression: "[AST_Node] the `switch` “discriminant”" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + push(this.expression); + } +}, AST_Block); + +var AST_SwitchBranch = DEFNODE("SwitchBranch", null, function AST_SwitchBranch(props) { + if (props) { + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for `switch` branches", +}, AST_Block); + +var AST_Default = DEFNODE("Default", null, function AST_Default(props) { + if (props) { + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `default` switch branch", +}, AST_SwitchBranch); + +var AST_Case = DEFNODE("Case", "expression", function AST_Case(props) { + if (props) { + this.expression = props.expression; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `case` switch branch", + $propdoc: { + expression: "[AST_Node] the `case` expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + push(this.expression); + }, +}, AST_SwitchBranch); + +/* -----[ EXCEPTIONS ]----- */ + +var AST_Try = DEFNODE("Try", "body bcatch bfinally", function AST_Try(props) { + if (props) { + this.body = props.body; + this.bcatch = props.bcatch; + this.bfinally = props.bfinally; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `try` statement", + $propdoc: { + body: "[AST_TryBlock] the try block", + bcatch: "[AST_Catch?] the catch block, or null if not present", + bfinally: "[AST_Finally?] the finally block, or null if not present" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.body._walk(visitor); + if (this.bcatch) this.bcatch._walk(visitor); + if (this.bfinally) this.bfinally._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.bfinally) push(this.bfinally); + if (this.bcatch) push(this.bcatch); + push(this.body); + }, +}, AST_Statement); + +var AST_TryBlock = DEFNODE("TryBlock", null, function AST_TryBlock(props) { + if (props) { + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The `try` block of a try statement" +}, AST_Block); + +var AST_Catch = DEFNODE("Catch", "argname", function AST_Catch(props) { + if (props) { + this.argname = props.argname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `catch` node; only makes sense as part of a `try` statement", + $propdoc: { + argname: "[AST_SymbolCatch|AST_Destructuring|AST_Expansion|AST_DefaultAssign] symbol for the exception" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.argname) this.argname._walk(visitor); + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + if (this.argname) push(this.argname); + }, +}, AST_Block); + +var AST_Finally = DEFNODE("Finally", null, function AST_Finally(props) { + if (props) { + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `finally` node; only makes sense as part of a `try` statement" +}, AST_Block); + +/* -----[ VAR/CONST ]----- */ + +var AST_Definitions = DEFNODE("Definitions", "definitions", function AST_Definitions(props) { + if (props) { + this.definitions = props.definitions; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)", + $propdoc: { + definitions: "[AST_VarDef*] array of variable definitions" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + var definitions = this.definitions; + for (var i = 0, len = definitions.length; i < len; i++) { + definitions[i]._walk(visitor); + } + }); + }, + _children_backwards(push) { + let i = this.definitions.length; + while (i--) push(this.definitions[i]); + }, +}, AST_Statement); + +var AST_Var = DEFNODE("Var", null, function AST_Var(props) { + if (props) { + this.definitions = props.definitions; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `var` statement" +}, AST_Definitions); + +var AST_Let = DEFNODE("Let", null, function AST_Let(props) { + if (props) { + this.definitions = props.definitions; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `let` statement" +}, AST_Definitions); + +var AST_Const = DEFNODE("Const", null, function AST_Const(props) { + if (props) { + this.definitions = props.definitions; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `const` statement" +}, AST_Definitions); + +var AST_VarDef = DEFNODE("VarDef", "name value", function AST_VarDef(props) { + if (props) { + this.name = props.name; + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A variable declaration; only appears in a AST_Definitions node", + $propdoc: { + name: "[AST_Destructuring|AST_SymbolConst|AST_SymbolLet|AST_SymbolVar] name of the variable", + value: "[AST_Node?] initializer, or null of there's no initializer" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.name._walk(visitor); + if (this.value) this.value._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.value) push(this.value); + push(this.name); + }, + declarations_as_names() { + if (this.name instanceof AST_SymbolDeclaration) { + return [this]; + } else { + return this.name.all_symbols(); + } + } +}); + +var AST_NameMapping = DEFNODE("NameMapping", "foreign_name name", function AST_NameMapping(props) { + if (props) { + this.foreign_name = props.foreign_name; + this.name = props.name; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The part of the export/import statement that declare names from a module.", + $propdoc: { + foreign_name: "[AST_SymbolExportForeign|AST_SymbolImportForeign] The name being exported/imported (as specified in the module)", + name: "[AST_SymbolExport|AST_SymbolImport] The name as it is visible to this module." + }, + _walk: function (visitor) { + return visitor._visit(this, function() { + this.foreign_name._walk(visitor); + this.name._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.name); + push(this.foreign_name); + }, +}); + +var AST_Import = DEFNODE( + "Import", + "imported_name imported_names module_name assert_clause", + function AST_Import(props) { + if (props) { + this.imported_name = props.imported_name; + this.imported_names = props.imported_names; + this.module_name = props.module_name; + this.assert_clause = props.assert_clause; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; + }, + { + $documentation: "An `import` statement", + $propdoc: { + imported_name: "[AST_SymbolImport] The name of the variable holding the module's default export.", + imported_names: "[AST_NameMapping*] The names of non-default imported variables", + module_name: "[AST_String] String literal describing where this module came from", + assert_clause: "[AST_Object?] The import assertion" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.imported_name) { + this.imported_name._walk(visitor); + } + if (this.imported_names) { + this.imported_names.forEach(function(name_import) { + name_import._walk(visitor); + }); + } + this.module_name._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.module_name); + if (this.imported_names) { + let i = this.imported_names.length; + while (i--) push(this.imported_names[i]); + } + if (this.imported_name) push(this.imported_name); + }, + } +); + +var AST_ImportMeta = DEFNODE("ImportMeta", null, function AST_ImportMeta(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A reference to import.meta", +}); + +var AST_Export = DEFNODE( + "Export", + "exported_definition exported_value is_default exported_names module_name assert_clause", + function AST_Export(props) { + if (props) { + this.exported_definition = props.exported_definition; + this.exported_value = props.exported_value; + this.is_default = props.is_default; + this.exported_names = props.exported_names; + this.module_name = props.module_name; + this.assert_clause = props.assert_clause; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; + }, + { + $documentation: "An `export` statement", + $propdoc: { + exported_definition: "[AST_Defun|AST_Definitions|AST_DefClass?] An exported definition", + exported_value: "[AST_Node?] An exported value", + exported_names: "[AST_NameMapping*?] List of exported names", + module_name: "[AST_String?] Name of the file to load exports from", + is_default: "[Boolean] Whether this is the default exported value of this module", + assert_clause: "[AST_Object?] The import assertion" + }, + _walk: function (visitor) { + return visitor._visit(this, function () { + if (this.exported_definition) { + this.exported_definition._walk(visitor); + } + if (this.exported_value) { + this.exported_value._walk(visitor); + } + if (this.exported_names) { + this.exported_names.forEach(function(name_export) { + name_export._walk(visitor); + }); + } + if (this.module_name) { + this.module_name._walk(visitor); + } + }); + }, + _children_backwards(push) { + if (this.module_name) push(this.module_name); + if (this.exported_names) { + let i = this.exported_names.length; + while (i--) push(this.exported_names[i]); + } + if (this.exported_value) push(this.exported_value); + if (this.exported_definition) push(this.exported_definition); + } + }, + AST_Statement +); + +/* -----[ OTHER ]----- */ + +var AST_Call = DEFNODE( + "Call", + "expression args optional _annotations", + function AST_Call(props) { + if (props) { + this.expression = props.expression; + this.args = props.args; + this.optional = props.optional; + this._annotations = props._annotations; + this.start = props.start; + this.end = props.end; + this.initialize(); + } + + this.flags = 0; + }, + { + $documentation: "A function call expression", + $propdoc: { + expression: "[AST_Node] expression to invoke as function", + args: "[AST_Node*] array of arguments", + optional: "[boolean] whether this is an optional call (IE ?.() )", + _annotations: "[number] bitfield containing information about the call" + }, + initialize() { + if (this._annotations == null) this._annotations = 0; + }, + _walk(visitor) { + return visitor._visit(this, function() { + var args = this.args; + for (var i = 0, len = args.length; i < len; i++) { + args[i]._walk(visitor); + } + this.expression._walk(visitor); // TODO why do we need to crawl this last? + }); + }, + _children_backwards(push) { + let i = this.args.length; + while (i--) push(this.args[i]); + push(this.expression); + }, + } +); + +var AST_New = DEFNODE("New", null, function AST_New(props) { + if (props) { + this.expression = props.expression; + this.args = props.args; + this.optional = props.optional; + this._annotations = props._annotations; + this.start = props.start; + this.end = props.end; + this.initialize(); + } + + this.flags = 0; +}, { + $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties" +}, AST_Call); + +var AST_Sequence = DEFNODE("Sequence", "expressions", function AST_Sequence(props) { + if (props) { + this.expressions = props.expressions; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A sequence expression (comma-separated expressions)", + $propdoc: { + expressions: "[AST_Node*] array of expressions (at least two)" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expressions.forEach(function(node) { + node._walk(visitor); + }); + }); + }, + _children_backwards(push) { + let i = this.expressions.length; + while (i--) push(this.expressions[i]); + }, +}); + +var AST_PropAccess = DEFNODE( + "PropAccess", + "expression property optional", + function AST_PropAccess(props) { + if (props) { + this.expression = props.expression; + this.property = props.property; + this.optional = props.optional; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; + }, + { + $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`", + $propdoc: { + expression: "[AST_Node] the “container” expression", + property: "[AST_Node|string] the property to access. For AST_Dot & AST_DotHash this is always a plain string, while for AST_Sub it's an arbitrary AST_Node", + + optional: "[boolean] whether this is an optional property access (IE ?.)" + } + } +); + +var AST_Dot = DEFNODE("Dot", "quote", function AST_Dot(props) { + if (props) { + this.quote = props.quote; + this.expression = props.expression; + this.property = props.property; + this.optional = props.optional; + this._annotations = props._annotations; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A dotted property access expression", + $propdoc: { + quote: "[string] the original quote character when transformed from AST_Sub", + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}, AST_PropAccess); + +var AST_DotHash = DEFNODE("DotHash", "", function AST_DotHash(props) { + if (props) { + this.expression = props.expression; + this.property = props.property; + this.optional = props.optional; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A dotted property access to a private property", + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}, AST_PropAccess); + +var AST_Sub = DEFNODE("Sub", null, function AST_Sub(props) { + if (props) { + this.expression = props.expression; + this.property = props.property; + this.optional = props.optional; + this._annotations = props._annotations; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Index-style property access, i.e. `a[\"foo\"]`", + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + this.property._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.property); + push(this.expression); + }, +}, AST_PropAccess); + +var AST_Chain = DEFNODE("Chain", "expression", function AST_Chain(props) { + if (props) { + this.expression = props.expression; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A chain expression like a?.b?.(c)?.[d]", + $propdoc: { + expression: "[AST_Call|AST_Dot|AST_DotHash|AST_Sub] chain element." + }, + _walk: function (visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}); + +var AST_Unary = DEFNODE("Unary", "operator expression", function AST_Unary(props) { + if (props) { + this.operator = props.operator; + this.expression = props.expression; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for unary expressions", + $propdoc: { + operator: "[string] the operator", + expression: "[AST_Node] expression that this unary operator applies to" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}); + +var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, function AST_UnaryPrefix(props) { + if (props) { + this.operator = props.operator; + this.expression = props.expression; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`" +}, AST_Unary); + +var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, function AST_UnaryPostfix(props) { + if (props) { + this.operator = props.operator; + this.expression = props.expression; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Unary postfix expression, i.e. `i++`" +}, AST_Unary); + +var AST_Binary = DEFNODE("Binary", "operator left right", function AST_Binary(props) { + if (props) { + this.operator = props.operator; + this.left = props.left; + this.right = props.right; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Binary expression, i.e. `a + b`", + $propdoc: { + left: "[AST_Node] left-hand side expression", + operator: "[string] the operator", + right: "[AST_Node] right-hand side expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.left._walk(visitor); + this.right._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.right); + push(this.left); + }, +}); + +var AST_Conditional = DEFNODE( + "Conditional", + "condition consequent alternative", + function AST_Conditional(props) { + if (props) { + this.condition = props.condition; + this.consequent = props.consequent; + this.alternative = props.alternative; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; + }, + { + $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`", + $propdoc: { + condition: "[AST_Node]", + consequent: "[AST_Node]", + alternative: "[AST_Node]" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.condition._walk(visitor); + this.consequent._walk(visitor); + this.alternative._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.alternative); + push(this.consequent); + push(this.condition); + }, + } +); + +var AST_Assign = DEFNODE("Assign", "logical", function AST_Assign(props) { + if (props) { + this.logical = props.logical; + this.operator = props.operator; + this.left = props.left; + this.right = props.right; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "An assignment expression — `a = b + 5`", + $propdoc: { + logical: "Whether it's a logical assignment" + } +}, AST_Binary); + +var AST_DefaultAssign = DEFNODE("DefaultAssign", null, function AST_DefaultAssign(props) { + if (props) { + this.operator = props.operator; + this.left = props.left; + this.right = props.right; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A default assignment expression like in `(a = 3) => a`" +}, AST_Binary); + +/* -----[ LITERALS ]----- */ + +var AST_Array = DEFNODE("Array", "elements", function AST_Array(props) { + if (props) { + this.elements = props.elements; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "An array literal", + $propdoc: { + elements: "[AST_Node*] array of elements" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + var elements = this.elements; + for (var i = 0, len = elements.length; i < len; i++) { + elements[i]._walk(visitor); + } + }); + }, + _children_backwards(push) { + let i = this.elements.length; + while (i--) push(this.elements[i]); + }, +}); + +var AST_Object = DEFNODE("Object", "properties", function AST_Object(props) { + if (props) { + this.properties = props.properties; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "An object literal", + $propdoc: { + properties: "[AST_ObjectProperty*] array of properties" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + var properties = this.properties; + for (var i = 0, len = properties.length; i < len; i++) { + properties[i]._walk(visitor); + } + }); + }, + _children_backwards(push) { + let i = this.properties.length; + while (i--) push(this.properties[i]); + }, +}); + +var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", function AST_ObjectProperty(props) { + if (props) { + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + this._annotations = props._annotations; + } + + this.flags = 0; +}, { + $documentation: "Base class for literal object properties", + $propdoc: { + key: "[string|AST_Node] property name. For ObjectKeyVal this is a string. For getters, setters and computed property this is an AST_Node.", + value: "[AST_Node] property value. For getters and setters this is an AST_Accessor." + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.key instanceof AST_Node) + this.key._walk(visitor); + this.value._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.value); + if (this.key instanceof AST_Node) push(this.key); + } +}); + +var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", "quote", function AST_ObjectKeyVal(props) { + if (props) { + this.quote = props.quote; + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + this._annotations = props._annotations; + } + + this.flags = 0; +}, { + $documentation: "A key: value object property", + $propdoc: { + quote: "[string] the original quote character" + }, + computed_key() { + return this.key instanceof AST_Node; + } +}, AST_ObjectProperty); + +var AST_PrivateSetter = DEFNODE("PrivateSetter", "static", function AST_PrivateSetter(props) { + if (props) { + this.static = props.static; + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $propdoc: { + static: "[boolean] whether this is a static private setter" + }, + $documentation: "A private setter property", + computed_key() { + return false; + } +}, AST_ObjectProperty); + +var AST_PrivateGetter = DEFNODE("PrivateGetter", "static", function AST_PrivateGetter(props) { + if (props) { + this.static = props.static; + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $propdoc: { + static: "[boolean] whether this is a static private getter" + }, + $documentation: "A private getter property", + computed_key() { + return false; + } +}, AST_ObjectProperty); + +var AST_ObjectSetter = DEFNODE("ObjectSetter", "quote static", function AST_ObjectSetter(props) { + if (props) { + this.quote = props.quote; + this.static = props.static; + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + this._annotations = props._annotations; + } + + this.flags = 0; +}, { + $propdoc: { + quote: "[string|undefined] the original quote character, if any", + static: "[boolean] whether this is a static setter (classes only)" + }, + $documentation: "An object setter property", + computed_key() { + return !(this.key instanceof AST_SymbolMethod); + } +}, AST_ObjectProperty); + +var AST_ObjectGetter = DEFNODE("ObjectGetter", "quote static", function AST_ObjectGetter(props) { + if (props) { + this.quote = props.quote; + this.static = props.static; + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + this._annotations = props._annotations; + } + + this.flags = 0; +}, { + $propdoc: { + quote: "[string|undefined] the original quote character, if any", + static: "[boolean] whether this is a static getter (classes only)" + }, + $documentation: "An object getter property", + computed_key() { + return !(this.key instanceof AST_SymbolMethod); + } +}, AST_ObjectProperty); + +var AST_ConciseMethod = DEFNODE( + "ConciseMethod", + "quote static is_generator async", + function AST_ConciseMethod(props) { + if (props) { + this.quote = props.quote; + this.static = props.static; + this.is_generator = props.is_generator; + this.async = props.async; + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + this._annotations = props._annotations; + } + + this.flags = 0; + }, + { + $propdoc: { + quote: "[string|undefined] the original quote character, if any", + static: "[boolean] is this method static (classes only)", + is_generator: "[boolean] is this a generator method", + async: "[boolean] is this method async", + }, + $documentation: "An ES6 concise method inside an object or class", + computed_key() { + return !(this.key instanceof AST_SymbolMethod); + } + }, + AST_ObjectProperty +); + +var AST_PrivateMethod = DEFNODE("PrivateMethod", "", function AST_PrivateMethod(props) { + if (props) { + this.quote = props.quote; + this.static = props.static; + this.is_generator = props.is_generator; + this.async = props.async; + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A private class method inside a class", +}, AST_ConciseMethod); + +var AST_Class = DEFNODE("Class", "name extends properties", function AST_Class(props) { + if (props) { + this.name = props.name; + this.extends = props.extends; + this.properties = props.properties; + this.variables = props.variables; + this.uses_with = props.uses_with; + this.uses_eval = props.uses_eval; + this.parent_scope = props.parent_scope; + this.enclosed = props.enclosed; + this.cname = props.cname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $propdoc: { + name: "[AST_SymbolClass|AST_SymbolDefClass?] optional class name.", + extends: "[AST_Node]? optional parent class", + properties: "[AST_ObjectProperty*] array of properties" + }, + $documentation: "An ES6 class", + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.name) { + this.name._walk(visitor); + } + if (this.extends) { + this.extends._walk(visitor); + } + this.properties.forEach((prop) => prop._walk(visitor)); + }); + }, + _children_backwards(push) { + let i = this.properties.length; + while (i--) push(this.properties[i]); + if (this.extends) push(this.extends); + if (this.name) push(this.name); + }, + /** go through the bits that are executed instantly, not when the class is `new`'d. Doesn't walk the name. */ + visit_nondeferred_class_parts(visitor) { + if (this.extends) { + this.extends._walk(visitor); + } + this.properties.forEach((prop) => { + if (prop instanceof AST_ClassStaticBlock) { + prop._walk(visitor); + return; + } + if (prop.computed_key()) { + visitor.push(prop); + prop.key._walk(visitor); + visitor.pop(); + } + if ((prop instanceof AST_ClassPrivateProperty || prop instanceof AST_ClassProperty) && prop.static && prop.value) { + visitor.push(prop); + prop.value._walk(visitor); + visitor.pop(); + } + }); + }, + /** go through the bits that are executed later, when the class is `new`'d or a static method is called */ + visit_deferred_class_parts(visitor) { + this.properties.forEach((prop) => { + if (prop instanceof AST_ConciseMethod) { + prop.walk(visitor); + } else if (prop instanceof AST_ClassProperty && !prop.static && prop.value) { + visitor.push(prop); + prop.value._walk(visitor); + visitor.pop(); + } + }); + }, + is_self_referential: function() { + const this_id = this.name && this.name.definition().id; + let found = false; + let class_this = true; + this.visit_nondeferred_class_parts(new TreeWalker((node, descend) => { + if (found) return true; + if (node instanceof AST_This) return (found = class_this); + if (node instanceof AST_SymbolRef) return (found = node.definition().id === this_id); + if (node instanceof AST_Lambda && !(node instanceof AST_Arrow)) { + const class_this_save = class_this; + class_this = false; + descend(); + class_this = class_this_save; + return true; + } + })); + return found; + }, +}, AST_Scope /* TODO a class might have a scope but it's not a scope */); + +var AST_ClassProperty = DEFNODE("ClassProperty", "static quote", function AST_ClassProperty(props) { + if (props) { + this.static = props.static; + this.quote = props.quote; + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + this._annotations = props._annotations; + } + + this.flags = 0; +}, { + $documentation: "A class property", + $propdoc: { + static: "[boolean] whether this is a static key", + quote: "[string] which quote is being used" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.key instanceof AST_Node) + this.key._walk(visitor); + if (this.value instanceof AST_Node) + this.value._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.value instanceof AST_Node) push(this.value); + if (this.key instanceof AST_Node) push(this.key); + }, + computed_key() { + return !(this.key instanceof AST_SymbolClassProperty); + } +}, AST_ObjectProperty); + +var AST_ClassPrivateProperty = DEFNODE("ClassPrivateProperty", "", function AST_ClassPrivateProperty(props) { + if (props) { + this.static = props.static; + this.quote = props.quote; + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A class property for a private property", +}, AST_ClassProperty); + +var AST_PrivateIn = DEFNODE("PrivateIn", "key value", function AST_PrivateIn(props) { + if (props) { + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "An `in` binop when the key is private, eg #x in this", + _walk: function(visitor) { + return visitor._visit(this, function() { + this.key._walk(visitor); + this.value._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.value); + push(this.key); + }, +}); + +var AST_DefClass = DEFNODE("DefClass", null, function AST_DefClass(props) { + if (props) { + this.name = props.name; + this.extends = props.extends; + this.properties = props.properties; + this.variables = props.variables; + this.uses_with = props.uses_with; + this.uses_eval = props.uses_eval; + this.parent_scope = props.parent_scope; + this.enclosed = props.enclosed; + this.cname = props.cname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A class definition", +}, AST_Class); + +var AST_ClassStaticBlock = DEFNODE("ClassStaticBlock", "body block_scope", function AST_ClassStaticBlock (props) { + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; +}, { + $documentation: "A block containing statements to be executed in the context of the class", + $propdoc: { + body: "[AST_Statement*] an array of statements", + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + }, + clone: clone_block_scope, + computed_key: () => false +}, AST_Scope); + +var AST_ClassExpression = DEFNODE("ClassExpression", null, function AST_ClassExpression(props) { + if (props) { + this.name = props.name; + this.extends = props.extends; + this.properties = props.properties; + this.variables = props.variables; + this.uses_with = props.uses_with; + this.uses_eval = props.uses_eval; + this.parent_scope = props.parent_scope; + this.enclosed = props.enclosed; + this.cname = props.cname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A class expression." +}, AST_Class); + +var AST_Symbol = DEFNODE("Symbol", "scope name thedef", function AST_Symbol(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $propdoc: { + name: "[string] name of this symbol", + scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)", + thedef: "[SymbolDef/S] the definition of this symbol" + }, + $documentation: "Base class for all symbols" +}); + +var AST_NewTarget = DEFNODE("NewTarget", null, function AST_NewTarget(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A reference to new.target" +}); + +var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", function AST_SymbolDeclaration(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)", +}, AST_Symbol); + +var AST_SymbolVar = DEFNODE("SymbolVar", null, function AST_SymbolVar(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol defining a variable", +}, AST_SymbolDeclaration); + +var AST_SymbolBlockDeclaration = DEFNODE( + "SymbolBlockDeclaration", + null, + function AST_SymbolBlockDeclaration(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; + }, + { + $documentation: "Base class for block-scoped declaration symbols" + }, + AST_SymbolDeclaration +); + +var AST_SymbolConst = DEFNODE("SymbolConst", null, function AST_SymbolConst(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A constant declaration" +}, AST_SymbolBlockDeclaration); + +var AST_SymbolLet = DEFNODE("SymbolLet", null, function AST_SymbolLet(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A block-scoped `let` declaration" +}, AST_SymbolBlockDeclaration); + +var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, function AST_SymbolFunarg(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol naming a function argument", +}, AST_SymbolVar); + +var AST_SymbolDefun = DEFNODE("SymbolDefun", null, function AST_SymbolDefun(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol defining a function", +}, AST_SymbolDeclaration); + +var AST_SymbolMethod = DEFNODE("SymbolMethod", null, function AST_SymbolMethod(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol in an object defining a method", +}, AST_Symbol); + +var AST_SymbolClassProperty = DEFNODE("SymbolClassProperty", null, function AST_SymbolClassProperty(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol for a class property", +}, AST_Symbol); + +var AST_SymbolLambda = DEFNODE("SymbolLambda", null, function AST_SymbolLambda(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol naming a function expression", +}, AST_SymbolDeclaration); + +var AST_SymbolDefClass = DEFNODE("SymbolDefClass", null, function AST_SymbolDefClass(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol naming a class's name in a class declaration. Lexically scoped to its containing scope, and accessible within the class." +}, AST_SymbolBlockDeclaration); + +var AST_SymbolClass = DEFNODE("SymbolClass", null, function AST_SymbolClass(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol naming a class's name. Lexically scoped to the class." +}, AST_SymbolDeclaration); + +var AST_SymbolCatch = DEFNODE("SymbolCatch", null, function AST_SymbolCatch(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol naming the exception in catch", +}, AST_SymbolBlockDeclaration); + +var AST_SymbolImport = DEFNODE("SymbolImport", null, function AST_SymbolImport(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol referring to an imported name", +}, AST_SymbolBlockDeclaration); + +var AST_SymbolImportForeign = DEFNODE("SymbolImportForeign", null, function AST_SymbolImportForeign(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.quote = props.quote; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A symbol imported from a module, but it is defined in the other module, and its real name is irrelevant for this module's purposes", +}, AST_Symbol); + +var AST_Label = DEFNODE("Label", "references", function AST_Label(props) { + if (props) { + this.references = props.references; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + this.initialize(); + } + + this.flags = 0; +}, { + $documentation: "Symbol naming a label (declaration)", + $propdoc: { + references: "[AST_LoopControl*] a list of nodes referring to this label" + }, + initialize: function() { + this.references = []; + this.thedef = this; + } +}, AST_Symbol); + +var AST_SymbolRef = DEFNODE("SymbolRef", null, function AST_SymbolRef(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Reference to some symbol (not definition/declaration)", +}, AST_Symbol); + +var AST_SymbolExport = DEFNODE("SymbolExport", null, function AST_SymbolExport(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.quote = props.quote; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol referring to a name to export", +}, AST_SymbolRef); + +var AST_SymbolExportForeign = DEFNODE("SymbolExportForeign", null, function AST_SymbolExportForeign(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.quote = props.quote; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A symbol exported from this module, but it is used in the other module, and its real name is irrelevant for this module's purposes", +}, AST_Symbol); + +var AST_LabelRef = DEFNODE("LabelRef", null, function AST_LabelRef(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Reference to a label symbol", +}, AST_Symbol); + +var AST_SymbolPrivateProperty = DEFNODE("SymbolPrivateProperty", null, function AST_SymbolPrivateProperty(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A symbol that refers to a private property", +}, AST_Symbol); + +var AST_This = DEFNODE("This", null, function AST_This(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The `this` symbol", +}, AST_Symbol); + +var AST_Super = DEFNODE("Super", null, function AST_Super(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The `super` symbol", +}, AST_This); + +var AST_Constant = DEFNODE("Constant", null, function AST_Constant(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for all constants", + getValue: function() { + return this.value; + } +}); + +var AST_String = DEFNODE("String", "value quote", function AST_String(props) { + if (props) { + this.value = props.value; + this.quote = props.quote; + this.start = props.start; + this.end = props.end; + this._annotations = props._annotations; + } + + this.flags = 0; +}, { + $documentation: "A string literal", + $propdoc: { + value: "[string] the contents of this string", + quote: "[string] the original quote character" + } +}, AST_Constant); + +var AST_Number = DEFNODE("Number", "value raw", function AST_Number(props) { + if (props) { + this.value = props.value; + this.raw = props.raw; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A number literal", + $propdoc: { + value: "[number] the numeric value", + raw: "[string] numeric value as string" + } +}, AST_Constant); + +var AST_BigInt = DEFNODE("BigInt", "value", function AST_BigInt(props) { + if (props) { + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A big int literal", + $propdoc: { + value: "[string] big int value" + } +}, AST_Constant); + +var AST_RegExp = DEFNODE("RegExp", "value", function AST_RegExp(props) { + if (props) { + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A regexp literal", + $propdoc: { + value: "[RegExp] the actual regexp", + } +}, AST_Constant); + +var AST_Atom = DEFNODE("Atom", null, function AST_Atom(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for atoms", +}, AST_Constant); + +var AST_Null = DEFNODE("Null", null, function AST_Null(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The `null` atom", + value: null +}, AST_Atom); + +var AST_NaN = DEFNODE("NaN", null, function AST_NaN(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The impossible value", + value: 0/0 +}, AST_Atom); + +var AST_Undefined = DEFNODE("Undefined", null, function AST_Undefined(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The `undefined` value", + value: (function() {}()) +}, AST_Atom); + +var AST_Hole = DEFNODE("Hole", null, function AST_Hole(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A hole in an array", + value: (function() {}()) +}, AST_Atom); + +var AST_Infinity = DEFNODE("Infinity", null, function AST_Infinity(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The `Infinity` value", + value: 1/0 +}, AST_Atom); + +var AST_Boolean = DEFNODE("Boolean", null, function AST_Boolean(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for booleans", +}, AST_Atom); + +var AST_False = DEFNODE("False", null, function AST_False(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The `false` atom", + value: false +}, AST_Boolean); + +var AST_True = DEFNODE("True", null, function AST_True(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The `true` atom", + value: true +}, AST_Boolean); + +/* -----[ Walk function ]---- */ + +/** + * Walk nodes in depth-first search fashion. + * Callback can return `walk_abort` symbol to stop iteration. + * It can also return `true` to stop iteration just for child nodes. + * Iteration can be stopped and continued by passing the `to_visit` argument, + * which is given to the callback in the second argument. + **/ +function walk(node, cb, to_visit = [node]) { + const push = to_visit.push.bind(to_visit); + while (to_visit.length) { + const node = to_visit.pop(); + const ret = cb(node, to_visit); + + if (ret) { + if (ret === walk_abort) return true; + continue; + } + + node._children_backwards(push); + } + return false; +} + +/** + * Walks an AST node and its children. + * + * {cb} can return `walk_abort` to interrupt the walk. + * + * @param node + * @param cb {(node, info: { parent: (nth) => any }) => (boolean | undefined)} + * + * @returns {boolean} whether the walk was aborted + * + * @example + * const found_some_cond = walk_parent(my_ast_node, (node, { parent }) => { + * if (some_cond(node, parent())) return walk_abort + * }); + */ +function walk_parent(node, cb, initial_stack) { + const to_visit = [node]; + const push = to_visit.push.bind(to_visit); + const stack = initial_stack ? initial_stack.slice() : []; + const parent_pop_indices = []; + + let current; + + const info = { + parent: (n = 0) => { + if (n === -1) { + return current; + } + + // [ p1 p0 ] [ 1 0 ] + if (initial_stack && n >= stack.length) { + n -= stack.length; + return initial_stack[ + initial_stack.length - (n + 1) + ]; + } + + return stack[stack.length - (1 + n)]; + }, + }; + + while (to_visit.length) { + current = to_visit.pop(); + + while ( + parent_pop_indices.length && + to_visit.length == parent_pop_indices[parent_pop_indices.length - 1] + ) { + stack.pop(); + parent_pop_indices.pop(); + } + + const ret = cb(current, info); + + if (ret) { + if (ret === walk_abort) return true; + continue; + } + + const visit_length = to_visit.length; + + current._children_backwards(push); + + // Push only if we're going to traverse the children + if (to_visit.length > visit_length) { + stack.push(current); + parent_pop_indices.push(visit_length - 1); + } + } + + return false; +} + +const walk_abort = Symbol("abort walk"); + +/* -----[ TreeWalker ]----- */ + +class TreeWalker { + constructor(callback) { + this.visit = callback; + this.stack = []; + this.directives = Object.create(null); + } + + _visit(node, descend) { + this.push(node); + var ret = this.visit(node, descend ? function() { + descend.call(node); + } : noop); + if (!ret && descend) { + descend.call(node); + } + this.pop(); + return ret; + } + + parent(n) { + return this.stack[this.stack.length - 2 - (n || 0)]; + } + + push(node) { + if (node instanceof AST_Lambda) { + this.directives = Object.create(this.directives); + } else if (node instanceof AST_Directive && !this.directives[node.value]) { + this.directives[node.value] = node; + } else if (node instanceof AST_Class) { + this.directives = Object.create(this.directives); + if (!this.directives["use strict"]) { + this.directives["use strict"] = node; + } + } + this.stack.push(node); + } + + pop() { + var node = this.stack.pop(); + if (node instanceof AST_Lambda || node instanceof AST_Class) { + this.directives = Object.getPrototypeOf(this.directives); + } + } + + self() { + return this.stack[this.stack.length - 1]; + } + + find_parent(type) { + var stack = this.stack; + for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof type) return x; + } + } + + find_scope() { + var stack = this.stack; + for (var i = stack.length; --i >= 0;) { + const p = stack[i]; + if (p instanceof AST_Toplevel) return p; + if (p instanceof AST_Lambda) return p; + if (p.block_scope) return p.block_scope; + } + } + + has_directive(type) { + var dir = this.directives[type]; + if (dir) return dir; + var node = this.stack[this.stack.length - 1]; + if (node instanceof AST_Scope && node.body) { + for (var i = 0; i < node.body.length; ++i) { + var st = node.body[i]; + if (!(st instanceof AST_Directive)) break; + if (st.value == type) return st; + } + } + } + + loopcontrol_target(node) { + var stack = this.stack; + if (node.label) for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof AST_LabeledStatement && x.label.name == node.label.name) + return x.body; + } else for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof AST_IterationStatement + || node instanceof AST_Break && x instanceof AST_Switch) + return x; + } + } +} + +// Tree transformer helpers. +class TreeTransformer extends TreeWalker { + constructor(before, after) { + super(); + this.before = before; + this.after = after; + } +} + +const _PURE = 0b00000001; +const _INLINE = 0b00000010; +const _NOINLINE = 0b00000100; +const _KEY = 0b00001000; +const _MANGLEPROP = 0b00010000; + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +function def_transform(node, descend) { + node.DEFMETHOD("transform", function(tw, in_list) { + let transformed = undefined; + tw.push(this); + if (tw.before) transformed = tw.before(this, descend, in_list); + if (transformed === undefined) { + transformed = this; + descend(transformed, tw); + if (tw.after) { + const after_ret = tw.after(transformed, in_list); + if (after_ret !== undefined) transformed = after_ret; + } + } + tw.pop(); + return transformed; + }); +} + +def_transform(AST_Node, noop); + +def_transform(AST_LabeledStatement, function(self, tw) { + self.label = self.label.transform(tw); + self.body = self.body.transform(tw); +}); + +def_transform(AST_SimpleStatement, function(self, tw) { + self.body = self.body.transform(tw); +}); + +def_transform(AST_Block, function(self, tw) { + self.body = MAP(self.body, tw); +}); + +def_transform(AST_Do, function(self, tw) { + self.body = self.body.transform(tw); + self.condition = self.condition.transform(tw); +}); + +def_transform(AST_While, function(self, tw) { + self.condition = self.condition.transform(tw); + self.body = self.body.transform(tw); +}); + +def_transform(AST_For, function(self, tw) { + if (self.init) self.init = self.init.transform(tw); + if (self.condition) self.condition = self.condition.transform(tw); + if (self.step) self.step = self.step.transform(tw); + self.body = self.body.transform(tw); +}); + +def_transform(AST_ForIn, function(self, tw) { + self.init = self.init.transform(tw); + self.object = self.object.transform(tw); + self.body = self.body.transform(tw); +}); + +def_transform(AST_With, function(self, tw) { + self.expression = self.expression.transform(tw); + self.body = self.body.transform(tw); +}); + +def_transform(AST_Exit, function(self, tw) { + if (self.value) self.value = self.value.transform(tw); +}); + +def_transform(AST_LoopControl, function(self, tw) { + if (self.label) self.label = self.label.transform(tw); +}); + +def_transform(AST_If, function(self, tw) { + self.condition = self.condition.transform(tw); + self.body = self.body.transform(tw); + if (self.alternative) self.alternative = self.alternative.transform(tw); +}); + +def_transform(AST_Switch, function(self, tw) { + self.expression = self.expression.transform(tw); + self.body = MAP(self.body, tw); +}); + +def_transform(AST_Case, function(self, tw) { + self.expression = self.expression.transform(tw); + self.body = MAP(self.body, tw); +}); + +def_transform(AST_Try, function(self, tw) { + self.body = self.body.transform(tw); + if (self.bcatch) self.bcatch = self.bcatch.transform(tw); + if (self.bfinally) self.bfinally = self.bfinally.transform(tw); +}); + +def_transform(AST_Catch, function(self, tw) { + if (self.argname) self.argname = self.argname.transform(tw); + self.body = MAP(self.body, tw); +}); + +def_transform(AST_Definitions, function(self, tw) { + self.definitions = MAP(self.definitions, tw); +}); + +def_transform(AST_VarDef, function(self, tw) { + self.name = self.name.transform(tw); + if (self.value) self.value = self.value.transform(tw); +}); + +def_transform(AST_Destructuring, function(self, tw) { + self.names = MAP(self.names, tw); +}); + +def_transform(AST_Lambda, function(self, tw) { + if (self.name) self.name = self.name.transform(tw); + self.argnames = MAP(self.argnames, tw, /* allow_splicing */ false); + if (self.body instanceof AST_Node) { + self.body = self.body.transform(tw); + } else { + self.body = MAP(self.body, tw); + } +}); + +def_transform(AST_Call, function(self, tw) { + self.expression = self.expression.transform(tw); + self.args = MAP(self.args, tw, /* allow_splicing */ false); +}); + +def_transform(AST_Sequence, function(self, tw) { + const result = MAP(self.expressions, tw); + self.expressions = result.length + ? result + : [new AST_Number({ value: 0 })]; +}); + +def_transform(AST_PropAccess, function(self, tw) { + self.expression = self.expression.transform(tw); +}); + +def_transform(AST_Sub, function(self, tw) { + self.expression = self.expression.transform(tw); + self.property = self.property.transform(tw); +}); + +def_transform(AST_Chain, function(self, tw) { + self.expression = self.expression.transform(tw); +}); + +def_transform(AST_Yield, function(self, tw) { + if (self.expression) self.expression = self.expression.transform(tw); +}); + +def_transform(AST_Await, function(self, tw) { + self.expression = self.expression.transform(tw); +}); + +def_transform(AST_Unary, function(self, tw) { + self.expression = self.expression.transform(tw); +}); + +def_transform(AST_Binary, function(self, tw) { + self.left = self.left.transform(tw); + self.right = self.right.transform(tw); +}); + +def_transform(AST_PrivateIn, function(self, tw) { + self.key = self.key.transform(tw); + self.value = self.value.transform(tw); +}); + +def_transform(AST_Conditional, function(self, tw) { + self.condition = self.condition.transform(tw); + self.consequent = self.consequent.transform(tw); + self.alternative = self.alternative.transform(tw); +}); + +def_transform(AST_Array, function(self, tw) { + self.elements = MAP(self.elements, tw); +}); + +def_transform(AST_Object, function(self, tw) { + self.properties = MAP(self.properties, tw); +}); + +def_transform(AST_ObjectProperty, function(self, tw) { + if (self.key instanceof AST_Node) { + self.key = self.key.transform(tw); + } + if (self.value) self.value = self.value.transform(tw); +}); + +def_transform(AST_Class, function(self, tw) { + if (self.name) self.name = self.name.transform(tw); + if (self.extends) self.extends = self.extends.transform(tw); + self.properties = MAP(self.properties, tw); +}); + +def_transform(AST_ClassStaticBlock, function(self, tw) { + self.body = MAP(self.body, tw); +}); + +def_transform(AST_Expansion, function(self, tw) { + self.expression = self.expression.transform(tw); +}); + +def_transform(AST_NameMapping, function(self, tw) { + self.foreign_name = self.foreign_name.transform(tw); + self.name = self.name.transform(tw); +}); + +def_transform(AST_Import, function(self, tw) { + if (self.imported_name) self.imported_name = self.imported_name.transform(tw); + if (self.imported_names) MAP(self.imported_names, tw); + self.module_name = self.module_name.transform(tw); +}); + +def_transform(AST_Export, function(self, tw) { + if (self.exported_definition) self.exported_definition = self.exported_definition.transform(tw); + if (self.exported_value) self.exported_value = self.exported_value.transform(tw); + if (self.exported_names) MAP(self.exported_names, tw); + if (self.module_name) self.module_name = self.module_name.transform(tw); +}); + +def_transform(AST_TemplateString, function(self, tw) { + self.segments = MAP(self.segments, tw); +}); + +def_transform(AST_PrefixedTemplateString, function(self, tw) { + self.prefix = self.prefix.transform(tw); + self.template_string = self.template_string.transform(tw); +}); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +(function() { + + var normalize_directives = function(body) { + for (var i = 0; i < body.length; i++) { + if (body[i] instanceof AST_Statement && body[i].body instanceof AST_String) { + body[i] = new AST_Directive({ + start: body[i].start, + end: body[i].end, + value: body[i].body.value + }); + } else { + return body; + } + } + + return body; + }; + + const assert_clause_from_moz = (assertions) => { + if (assertions && assertions.length > 0) { + return new AST_Object({ + start: my_start_token(assertions), + end: my_end_token(assertions), + properties: assertions.map((assertion_kv) => + new AST_ObjectKeyVal({ + start: my_start_token(assertion_kv), + end: my_end_token(assertion_kv), + key: assertion_kv.key.name || assertion_kv.key.value, + value: from_moz(assertion_kv.value) + }) + ) + }); + } + return null; + }; + + var MOZ_TO_ME = { + Program: function(M) { + return new AST_Toplevel({ + start: my_start_token(M), + end: my_end_token(M), + body: normalize_directives(M.body.map(from_moz)) + }); + }, + + ArrayPattern: function(M) { + return new AST_Destructuring({ + start: my_start_token(M), + end: my_end_token(M), + names: M.elements.map(function(elm) { + if (elm === null) { + return new AST_Hole(); + } + return from_moz(elm); + }), + is_array: true + }); + }, + + ObjectPattern: function(M) { + return new AST_Destructuring({ + start: my_start_token(M), + end: my_end_token(M), + names: M.properties.map(from_moz), + is_array: false + }); + }, + + AssignmentPattern: function(M) { + return new AST_DefaultAssign({ + start: my_start_token(M), + end: my_end_token(M), + left: from_moz(M.left), + operator: "=", + right: from_moz(M.right) + }); + }, + + SpreadElement: function(M) { + return new AST_Expansion({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz(M.argument) + }); + }, + + RestElement: function(M) { + return new AST_Expansion({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz(M.argument) + }); + }, + + TemplateElement: function(M) { + return new AST_TemplateSegment({ + start: my_start_token(M), + end: my_end_token(M), + value: M.value.cooked, + raw: M.value.raw + }); + }, + + TemplateLiteral: function(M) { + var segments = []; + for (var i = 0; i < M.quasis.length; i++) { + segments.push(from_moz(M.quasis[i])); + if (M.expressions[i]) { + segments.push(from_moz(M.expressions[i])); + } + } + return new AST_TemplateString({ + start: my_start_token(M), + end: my_end_token(M), + segments: segments + }); + }, + + TaggedTemplateExpression: function(M) { + return new AST_PrefixedTemplateString({ + start: my_start_token(M), + end: my_end_token(M), + template_string: from_moz(M.quasi), + prefix: from_moz(M.tag) + }); + }, + + FunctionDeclaration: function(M) { + return new AST_Defun({ + start: my_start_token(M), + end: my_end_token(M), + name: from_moz(M.id), + argnames: M.params.map(from_moz), + is_generator: M.generator, + async: M.async, + body: normalize_directives(from_moz(M.body).body) + }); + }, + + FunctionExpression: function(M) { + return new AST_Function({ + start: my_start_token(M), + end: my_end_token(M), + name: from_moz(M.id), + argnames: M.params.map(from_moz), + is_generator: M.generator, + async: M.async, + body: normalize_directives(from_moz(M.body).body) + }); + }, + + ArrowFunctionExpression: function(M) { + const body = M.body.type === "BlockStatement" + ? from_moz(M.body).body + : [make_node(AST_Return, {}, { value: from_moz(M.body) })]; + return new AST_Arrow({ + start: my_start_token(M), + end: my_end_token(M), + argnames: M.params.map(from_moz), + body, + async: M.async, + }); + }, + + ExpressionStatement: function(M) { + return new AST_SimpleStatement({ + start: my_start_token(M), + end: my_end_token(M), + body: from_moz(M.expression) + }); + }, + + TryStatement: function(M) { + var handlers = M.handlers || [M.handler]; + if (handlers.length > 1 || M.guardedHandlers && M.guardedHandlers.length) { + throw new Error("Multiple catch clauses are not supported."); + } + return new AST_Try({ + start : my_start_token(M), + end : my_end_token(M), + body : new AST_TryBlock(from_moz(M.block)), + bcatch : from_moz(handlers[0]), + bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null + }); + }, + + Property: function(M) { + var key = M.key; + var args = { + start : my_start_token(key || M.value), + end : my_end_token(M.value), + key : key.type == "Identifier" ? key.name : key.value, + value : from_moz(M.value) + }; + if (M.computed) { + args.key = from_moz(M.key); + } + if (M.method) { + args.is_generator = M.value.generator; + args.async = M.value.async; + if (!M.computed) { + args.key = new AST_SymbolMethod({ name: args.key }); + } else { + args.key = from_moz(M.key); + } + return new AST_ConciseMethod(args); + } + if (M.kind == "init") { + if (key.type != "Identifier" && key.type != "Literal") { + args.key = from_moz(key); + } + return new AST_ObjectKeyVal(args); + } + if (typeof args.key === "string" || typeof args.key === "number") { + args.key = new AST_SymbolMethod({ + name: args.key + }); + } + args.value = new AST_Accessor(args.value); + if (M.kind == "get") return new AST_ObjectGetter(args); + if (M.kind == "set") return new AST_ObjectSetter(args); + if (M.kind == "method") { + args.async = M.value.async; + args.is_generator = M.value.generator; + args.quote = M.computed ? "\"" : null; + return new AST_ConciseMethod(args); + } + }, + + MethodDefinition: function(M) { + const is_private = M.key.type === "PrivateIdentifier"; + const key = M.computed ? from_moz(M.key) : new AST_SymbolMethod({ name: M.key.name || M.key.value }); + + var args = { + start : my_start_token(M), + end : my_end_token(M), + key, + value : from_moz(M.value), + static : M.static, + }; + if (M.kind == "get") { + return new (is_private ? AST_PrivateGetter : AST_ObjectGetter)(args); + } + if (M.kind == "set") { + return new (is_private ? AST_PrivateSetter : AST_ObjectSetter)(args); + } + args.is_generator = M.value.generator; + args.async = M.value.async; + return new (is_private ? AST_PrivateMethod : AST_ConciseMethod)(args); + }, + + FieldDefinition: function(M) { + let key; + if (M.computed) { + key = from_moz(M.key); + } else { + if (M.key.type !== "Identifier") throw new Error("Non-Identifier key in FieldDefinition"); + key = from_moz(M.key); + } + return new AST_ClassProperty({ + start : my_start_token(M), + end : my_end_token(M), + key, + value : from_moz(M.value), + static : M.static, + }); + }, + + PropertyDefinition: function(M) { + let key; + if (M.computed) { + key = from_moz(M.key); + } else if (M.key.type === "PrivateIdentifier") { + return new AST_ClassPrivateProperty({ + start : my_start_token(M), + end : my_end_token(M), + key : from_moz(M.key), + value : from_moz(M.value), + static : M.static, + }); + } else { + if (M.key.type !== "Identifier") { + throw new Error("Non-Identifier key in PropertyDefinition"); + } + key = from_moz(M.key); + } + + return new AST_ClassProperty({ + start : my_start_token(M), + end : my_end_token(M), + key, + value : from_moz(M.value), + static : M.static, + }); + }, + + PrivateIdentifier: function (M) { + return new AST_SymbolPrivateProperty({ + start: my_start_token(M), + end: my_end_token(M), + name: M.name + }); + }, + + StaticBlock: function(M) { + return new AST_ClassStaticBlock({ + start : my_start_token(M), + end : my_end_token(M), + body : M.body.map(from_moz), + }); + }, + + ArrayExpression: function(M) { + return new AST_Array({ + start : my_start_token(M), + end : my_end_token(M), + elements : M.elements.map(function(elem) { + return elem === null ? new AST_Hole() : from_moz(elem); + }) + }); + }, + + ObjectExpression: function(M) { + return new AST_Object({ + start : my_start_token(M), + end : my_end_token(M), + properties : M.properties.map(function(prop) { + if (prop.type === "SpreadElement") { + return from_moz(prop); + } + prop.type = "Property"; + return from_moz(prop); + }) + }); + }, + + SequenceExpression: function(M) { + return new AST_Sequence({ + start : my_start_token(M), + end : my_end_token(M), + expressions: M.expressions.map(from_moz) + }); + }, + + MemberExpression: function(M) { + if (M.property.type === "PrivateIdentifier") { + return new AST_DotHash({ + start : my_start_token(M), + end : my_end_token(M), + property : M.property.name, + expression : from_moz(M.object), + optional : M.optional || false + }); + } + return new (M.computed ? AST_Sub : AST_Dot)({ + start : my_start_token(M), + end : my_end_token(M), + property : M.computed ? from_moz(M.property) : M.property.name, + expression : from_moz(M.object), + optional : M.optional || false + }); + }, + + ChainExpression: function(M) { + return new AST_Chain({ + start : my_start_token(M), + end : my_end_token(M), + expression : from_moz(M.expression) + }); + }, + + SwitchCase: function(M) { + return new (M.test ? AST_Case : AST_Default)({ + start : my_start_token(M), + end : my_end_token(M), + expression : from_moz(M.test), + body : M.consequent.map(from_moz) + }); + }, + + VariableDeclaration: function(M) { + return new (M.kind === "const" ? AST_Const : + M.kind === "let" ? AST_Let : AST_Var)({ + start : my_start_token(M), + end : my_end_token(M), + definitions : M.declarations.map(from_moz) + }); + }, + + ImportDeclaration: function(M) { + var imported_name = null; + var imported_names = null; + M.specifiers.forEach(function (specifier) { + if (specifier.type === "ImportSpecifier" || specifier.type === "ImportNamespaceSpecifier") { + if (!imported_names) { imported_names = []; } + imported_names.push(from_moz(specifier)); + } else if (specifier.type === "ImportDefaultSpecifier") { + imported_name = from_moz(specifier); + } + }); + return new AST_Import({ + start : my_start_token(M), + end : my_end_token(M), + imported_name: imported_name, + imported_names : imported_names, + module_name : from_moz(M.source), + assert_clause: assert_clause_from_moz(M.assertions) + }); + }, + + ImportSpecifier: function(M) { + return new AST_NameMapping({ + start: my_start_token(M), + end: my_end_token(M), + foreign_name: from_moz(M.imported), + name: from_moz(M.local) + }); + }, + + ImportDefaultSpecifier: function(M) { + return from_moz(M.local); + }, + + ImportNamespaceSpecifier: function(M) { + return new AST_NameMapping({ + start: my_start_token(M), + end: my_end_token(M), + foreign_name: new AST_SymbolImportForeign({ name: "*" }), + name: from_moz(M.local) + }); + }, + + ImportExpression: function(M) { + return new AST_Call({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz({ + type: "Identifier", + name: "import" + }), + optional: false, + args: [from_moz(M.source)] + }); + }, + + ExportAllDeclaration: function(M) { + var foreign_name = M.exported == null ? + new AST_SymbolExportForeign({ name: "*" }) : + from_moz(M.exported); + return new AST_Export({ + start: my_start_token(M), + end: my_end_token(M), + exported_names: [ + new AST_NameMapping({ + name: new AST_SymbolExportForeign({ name: "*" }), + foreign_name: foreign_name + }) + ], + module_name: from_moz(M.source), + assert_clause: assert_clause_from_moz(M.assertions) + }); + }, + + ExportNamedDeclaration: function(M) { + return new AST_Export({ + start: my_start_token(M), + end: my_end_token(M), + exported_definition: from_moz(M.declaration), + exported_names: M.specifiers && M.specifiers.length ? M.specifiers.map(from_moz) : null, + module_name: from_moz(M.source), + assert_clause: assert_clause_from_moz(M.assertions) + }); + }, + + ExportDefaultDeclaration: function(M) { + return new AST_Export({ + start: my_start_token(M), + end: my_end_token(M), + exported_value: from_moz(M.declaration), + is_default: true + }); + }, + + ExportSpecifier: function(M) { + return new AST_NameMapping({ + foreign_name: from_moz(M.exported), + name: from_moz(M.local) + }); + }, + + Literal: function(M) { + var val = M.value, args = { + start : my_start_token(M), + end : my_end_token(M) + }; + var rx = M.regex; + if (rx && rx.pattern) { + // RegExpLiteral as per ESTree AST spec + args.value = { + source: rx.pattern, + flags: rx.flags + }; + return new AST_RegExp(args); + } else if (rx) { + // support legacy RegExp + const rx_source = M.raw || val; + const match = rx_source.match(/^\/(.*)\/(\w*)$/); + if (!match) throw new Error("Invalid regex source " + rx_source); + const [_, source, flags] = match; + args.value = { source, flags }; + return new AST_RegExp(args); + } + const bi = typeof M.value === "bigint" ? M.value.toString() : M.bigint; + if (typeof bi === "string") { + args.value = bi; + return new AST_BigInt(args); + } + if (val === null) return new AST_Null(args); + switch (typeof val) { + case "string": + args.quote = "\""; + var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2]; + if (p.type == "ImportSpecifier") { + args.name = val; + return new AST_SymbolImportForeign(args); + } else if (p.type == "ExportSpecifier") { + args.name = val; + if (M == p.exported) { + return new AST_SymbolExportForeign(args); + } else { + return new AST_SymbolExport(args); + } + } else if (p.type == "ExportAllDeclaration" && M == p.exported) { + args.name = val; + return new AST_SymbolExportForeign(args); + } + args.value = val; + return new AST_String(args); + case "number": + args.value = val; + args.raw = M.raw || val.toString(); + return new AST_Number(args); + case "boolean": + return new (val ? AST_True : AST_False)(args); + } + }, + + MetaProperty: function(M) { + if (M.meta.name === "new" && M.property.name === "target") { + return new AST_NewTarget({ + start: my_start_token(M), + end: my_end_token(M) + }); + } else if (M.meta.name === "import" && M.property.name === "meta") { + return new AST_ImportMeta({ + start: my_start_token(M), + end: my_end_token(M) + }); + } + }, + + Identifier: function(M) { + var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2]; + return new ( p.type == "LabeledStatement" ? AST_Label + : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : p.kind == "let" ? AST_SymbolLet : AST_SymbolVar) + : /Import.*Specifier/.test(p.type) ? (p.local === M ? AST_SymbolImport : AST_SymbolImportForeign) + : p.type == "ExportSpecifier" ? (p.local === M ? AST_SymbolExport : AST_SymbolExportForeign) + : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg) + : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg) + : p.type == "ArrowFunctionExpression" ? (p.params.includes(M)) ? AST_SymbolFunarg : AST_SymbolRef + : p.type == "ClassExpression" ? (p.id === M ? AST_SymbolClass : AST_SymbolRef) + : p.type == "Property" ? (p.key === M && p.computed || p.value === M ? AST_SymbolRef : AST_SymbolMethod) + : p.type == "PropertyDefinition" || p.type === "FieldDefinition" ? (p.key === M && p.computed || p.value === M ? AST_SymbolRef : AST_SymbolClassProperty) + : p.type == "ClassDeclaration" ? (p.id === M ? AST_SymbolDefClass : AST_SymbolRef) + : p.type == "MethodDefinition" ? (p.computed ? AST_SymbolRef : AST_SymbolMethod) + : p.type == "CatchClause" ? AST_SymbolCatch + : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef + : AST_SymbolRef)({ + start : my_start_token(M), + end : my_end_token(M), + name : M.name + }); + }, + + EmptyStatement: function(M) { + return new AST_EmptyStatement({ + start: my_start_token(M), + end: my_end_token(M) + }); + }, + + BlockStatement: function(M) { + return new AST_BlockStatement({ + start: my_start_token(M), + end: my_end_token(M), + body: M.body.map(from_moz) + }); + }, + + IfStatement: function(M) { + return new AST_If({ + start: my_start_token(M), + end: my_end_token(M), + condition: from_moz(M.test), + body: from_moz(M.consequent), + alternative: from_moz(M.alternate) + }); + }, + + LabeledStatement: function(M) { + return new AST_LabeledStatement({ + start: my_start_token(M), + end: my_end_token(M), + label: from_moz(M.label), + body: from_moz(M.body) + }); + }, + + BreakStatement: function(M) { + return new AST_Break({ + start: my_start_token(M), + end: my_end_token(M), + label: from_moz(M.label) + }); + }, + + ContinueStatement: function(M) { + return new AST_Continue({ + start: my_start_token(M), + end: my_end_token(M), + label: from_moz(M.label) + }); + }, + + WithStatement: function(M) { + return new AST_With({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz(M.object), + body: from_moz(M.body) + }); + }, + + SwitchStatement: function(M) { + return new AST_Switch({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz(M.discriminant), + body: M.cases.map(from_moz) + }); + }, + + ReturnStatement: function(M) { + return new AST_Return({ + start: my_start_token(M), + end: my_end_token(M), + value: from_moz(M.argument) + }); + }, + + ThrowStatement: function(M) { + return new AST_Throw({ + start: my_start_token(M), + end: my_end_token(M), + value: from_moz(M.argument) + }); + }, + + WhileStatement: function(M) { + return new AST_While({ + start: my_start_token(M), + end: my_end_token(M), + condition: from_moz(M.test), + body: from_moz(M.body) + }); + }, + + DoWhileStatement: function(M) { + return new AST_Do({ + start: my_start_token(M), + end: my_end_token(M), + condition: from_moz(M.test), + body: from_moz(M.body) + }); + }, + + ForStatement: function(M) { + return new AST_For({ + start: my_start_token(M), + end: my_end_token(M), + init: from_moz(M.init), + condition: from_moz(M.test), + step: from_moz(M.update), + body: from_moz(M.body) + }); + }, + + ForInStatement: function(M) { + return new AST_ForIn({ + start: my_start_token(M), + end: my_end_token(M), + init: from_moz(M.left), + object: from_moz(M.right), + body: from_moz(M.body) + }); + }, + + ForOfStatement: function(M) { + return new AST_ForOf({ + start: my_start_token(M), + end: my_end_token(M), + init: from_moz(M.left), + object: from_moz(M.right), + body: from_moz(M.body), + await: M.await + }); + }, + + AwaitExpression: function(M) { + return new AST_Await({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz(M.argument) + }); + }, + + YieldExpression: function(M) { + return new AST_Yield({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz(M.argument), + is_star: M.delegate + }); + }, + + DebuggerStatement: function(M) { + return new AST_Debugger({ + start: my_start_token(M), + end: my_end_token(M) + }); + }, + + VariableDeclarator: function(M) { + return new AST_VarDef({ + start: my_start_token(M), + end: my_end_token(M), + name: from_moz(M.id), + value: from_moz(M.init) + }); + }, + + CatchClause: function(M) { + return new AST_Catch({ + start: my_start_token(M), + end: my_end_token(M), + argname: from_moz(M.param), + body: from_moz(M.body).body + }); + }, + + ThisExpression: function(M) { + return new AST_This({ + start: my_start_token(M), + end: my_end_token(M) + }); + }, + + Super: function(M) { + return new AST_Super({ + start: my_start_token(M), + end: my_end_token(M) + }); + }, + + BinaryExpression: function(M) { + if (M.left.type === "PrivateIdentifier") { + return new AST_PrivateIn({ + start: my_start_token(M), + end: my_end_token(M), + key: new AST_SymbolPrivateProperty({ + start: my_start_token(M.left), + end: my_end_token(M.left), + name: M.left.name + }), + value: from_moz(M.right), + }); + } + return new AST_Binary({ + start: my_start_token(M), + end: my_end_token(M), + operator: M.operator, + left: from_moz(M.left), + right: from_moz(M.right) + }); + }, + + LogicalExpression: function(M) { + return new AST_Binary({ + start: my_start_token(M), + end: my_end_token(M), + operator: M.operator, + left: from_moz(M.left), + right: from_moz(M.right) + }); + }, + + AssignmentExpression: function(M) { + return new AST_Assign({ + start: my_start_token(M), + end: my_end_token(M), + operator: M.operator, + left: from_moz(M.left), + right: from_moz(M.right) + }); + }, + + ConditionalExpression: function(M) { + return new AST_Conditional({ + start: my_start_token(M), + end: my_end_token(M), + condition: from_moz(M.test), + consequent: from_moz(M.consequent), + alternative: from_moz(M.alternate) + }); + }, + + NewExpression: function(M) { + return new AST_New({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz(M.callee), + args: M.arguments.map(from_moz) + }); + }, + + CallExpression: function(M) { + return new AST_Call({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz(M.callee), + optional: M.optional, + args: M.arguments.map(from_moz) + }); + } + }; + + MOZ_TO_ME.UpdateExpression = + MOZ_TO_ME.UnaryExpression = function To_Moz_Unary(M) { + var prefix = "prefix" in M ? M.prefix + : M.type == "UnaryExpression" ? true : false; + return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({ + start : my_start_token(M), + end : my_end_token(M), + operator : M.operator, + expression : from_moz(M.argument) + }); + }; + + MOZ_TO_ME.ClassDeclaration = + MOZ_TO_ME.ClassExpression = function From_Moz_Class(M) { + return new (M.type === "ClassDeclaration" ? AST_DefClass : AST_ClassExpression)({ + start : my_start_token(M), + end : my_end_token(M), + name : from_moz(M.id), + extends : from_moz(M.superClass), + properties: M.body.body.map(from_moz) + }); + }; + + def_to_moz(AST_EmptyStatement, function To_Moz_EmptyStatement() { + return { + type: "EmptyStatement" + }; + }); + def_to_moz(AST_BlockStatement, function To_Moz_BlockStatement(M) { + return { + type: "BlockStatement", + body: M.body.map(to_moz) + }; + }); + def_to_moz(AST_If, function To_Moz_IfStatement(M) { + return { + type: "IfStatement", + test: to_moz(M.condition), + consequent: to_moz(M.body), + alternate: to_moz(M.alternative) + }; + }); + def_to_moz(AST_LabeledStatement, function To_Moz_LabeledStatement(M) { + return { + type: "LabeledStatement", + label: to_moz(M.label), + body: to_moz(M.body) + }; + }); + def_to_moz(AST_Break, function To_Moz_BreakStatement(M) { + return { + type: "BreakStatement", + label: to_moz(M.label) + }; + }); + def_to_moz(AST_Continue, function To_Moz_ContinueStatement(M) { + return { + type: "ContinueStatement", + label: to_moz(M.label) + }; + }); + def_to_moz(AST_With, function To_Moz_WithStatement(M) { + return { + type: "WithStatement", + object: to_moz(M.expression), + body: to_moz(M.body) + }; + }); + def_to_moz(AST_Switch, function To_Moz_SwitchStatement(M) { + return { + type: "SwitchStatement", + discriminant: to_moz(M.expression), + cases: M.body.map(to_moz) + }; + }); + def_to_moz(AST_Return, function To_Moz_ReturnStatement(M) { + return { + type: "ReturnStatement", + argument: to_moz(M.value) + }; + }); + def_to_moz(AST_Throw, function To_Moz_ThrowStatement(M) { + return { + type: "ThrowStatement", + argument: to_moz(M.value) + }; + }); + def_to_moz(AST_While, function To_Moz_WhileStatement(M) { + return { + type: "WhileStatement", + test: to_moz(M.condition), + body: to_moz(M.body) + }; + }); + def_to_moz(AST_Do, function To_Moz_DoWhileStatement(M) { + return { + type: "DoWhileStatement", + test: to_moz(M.condition), + body: to_moz(M.body) + }; + }); + def_to_moz(AST_For, function To_Moz_ForStatement(M) { + return { + type: "ForStatement", + init: to_moz(M.init), + test: to_moz(M.condition), + update: to_moz(M.step), + body: to_moz(M.body) + }; + }); + def_to_moz(AST_ForIn, function To_Moz_ForInStatement(M) { + return { + type: "ForInStatement", + left: to_moz(M.init), + right: to_moz(M.object), + body: to_moz(M.body) + }; + }); + def_to_moz(AST_ForOf, function To_Moz_ForOfStatement(M) { + return { + type: "ForOfStatement", + left: to_moz(M.init), + right: to_moz(M.object), + body: to_moz(M.body), + await: M.await + }; + }); + def_to_moz(AST_Await, function To_Moz_AwaitExpression(M) { + return { + type: "AwaitExpression", + argument: to_moz(M.expression) + }; + }); + def_to_moz(AST_Yield, function To_Moz_YieldExpression(M) { + return { + type: "YieldExpression", + argument: to_moz(M.expression), + delegate: M.is_star + }; + }); + def_to_moz(AST_Debugger, function To_Moz_DebuggerStatement() { + return { + type: "DebuggerStatement" + }; + }); + def_to_moz(AST_VarDef, function To_Moz_VariableDeclarator(M) { + return { + type: "VariableDeclarator", + id: to_moz(M.name), + init: to_moz(M.value) + }; + }); + def_to_moz(AST_Catch, function To_Moz_CatchClause(M) { + return { + type: "CatchClause", + param: to_moz(M.argname), + body: to_moz_block(M) + }; + }); + + def_to_moz(AST_This, function To_Moz_ThisExpression() { + return { + type: "ThisExpression" + }; + }); + def_to_moz(AST_Super, function To_Moz_Super() { + return { + type: "Super" + }; + }); + def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) { + return { + type: "BinaryExpression", + operator: M.operator, + left: to_moz(M.left), + right: to_moz(M.right) + }; + }); + def_to_moz(AST_Binary, function To_Moz_LogicalExpression(M) { + return { + type: "LogicalExpression", + operator: M.operator, + left: to_moz(M.left), + right: to_moz(M.right) + }; + }); + def_to_moz(AST_Assign, function To_Moz_AssignmentExpression(M) { + return { + type: "AssignmentExpression", + operator: M.operator, + left: to_moz(M.left), + right: to_moz(M.right) + }; + }); + def_to_moz(AST_Conditional, function To_Moz_ConditionalExpression(M) { + return { + type: "ConditionalExpression", + test: to_moz(M.condition), + consequent: to_moz(M.consequent), + alternate: to_moz(M.alternative) + }; + }); + def_to_moz(AST_New, function To_Moz_NewExpression(M) { + return { + type: "NewExpression", + callee: to_moz(M.expression), + arguments: M.args.map(to_moz) + }; + }); + def_to_moz(AST_Call, function To_Moz_CallExpression(M) { + if (M.expression instanceof AST_SymbolRef && M.expression.name === "import") { + const [source] = M.args.map(to_moz); + return { + type: "ImportExpression", + source, + }; + } + + return { + type: "CallExpression", + callee: to_moz(M.expression), + optional: M.optional, + arguments: M.args.map(to_moz) + }; + }); + + def_to_moz(AST_Toplevel, function To_Moz_Program(M) { + return to_moz_scope("Program", M); + }); + + def_to_moz(AST_Expansion, function To_Moz_Spread(M) { + return { + type: to_moz_in_destructuring() ? "RestElement" : "SpreadElement", + argument: to_moz(M.expression) + }; + }); + + def_to_moz(AST_PrefixedTemplateString, function To_Moz_TaggedTemplateExpression(M) { + return { + type: "TaggedTemplateExpression", + tag: to_moz(M.prefix), + quasi: to_moz(M.template_string) + }; + }); + + def_to_moz(AST_TemplateString, function To_Moz_TemplateLiteral(M) { + var quasis = []; + var expressions = []; + for (var i = 0; i < M.segments.length; i++) { + if (i % 2 !== 0) { + expressions.push(to_moz(M.segments[i])); + } else { + quasis.push({ + type: "TemplateElement", + value: { + raw: M.segments[i].raw, + cooked: M.segments[i].value + }, + tail: i === M.segments.length - 1 + }); + } + } + return { + type: "TemplateLiteral", + quasis: quasis, + expressions: expressions + }; + }); + + def_to_moz(AST_Defun, function To_Moz_FunctionDeclaration(M) { + return { + type: "FunctionDeclaration", + id: to_moz(M.name), + params: M.argnames.map(to_moz), + generator: M.is_generator, + async: M.async, + body: to_moz_scope("BlockStatement", M) + }; + }); + + def_to_moz(AST_Function, function To_Moz_FunctionExpression(M, parent) { + var is_generator = parent.is_generator !== undefined ? + parent.is_generator : M.is_generator; + return { + type: "FunctionExpression", + id: to_moz(M.name), + params: M.argnames.map(to_moz), + generator: is_generator, + async: M.async, + body: to_moz_scope("BlockStatement", M) + }; + }); + + def_to_moz(AST_Arrow, function To_Moz_ArrowFunctionExpression(M) { + var body = { + type: "BlockStatement", + body: M.body.map(to_moz) + }; + return { + type: "ArrowFunctionExpression", + params: M.argnames.map(to_moz), + async: M.async, + body: body + }; + }); + + def_to_moz(AST_Destructuring, function To_Moz_ObjectPattern(M) { + if (M.is_array) { + return { + type: "ArrayPattern", + elements: M.names.map(to_moz) + }; + } + return { + type: "ObjectPattern", + properties: M.names.map(to_moz) + }; + }); + + def_to_moz(AST_Directive, function To_Moz_Directive(M) { + return { + type: "ExpressionStatement", + expression: { + type: "Literal", + value: M.value, + raw: M.print_to_string() + }, + directive: M.value + }; + }); + + def_to_moz(AST_SimpleStatement, function To_Moz_ExpressionStatement(M) { + return { + type: "ExpressionStatement", + expression: to_moz(M.body) + }; + }); + + def_to_moz(AST_SwitchBranch, function To_Moz_SwitchCase(M) { + return { + type: "SwitchCase", + test: to_moz(M.expression), + consequent: M.body.map(to_moz) + }; + }); + + def_to_moz(AST_Try, function To_Moz_TryStatement(M) { + return { + type: "TryStatement", + block: to_moz_block(M.body), + handler: to_moz(M.bcatch), + guardedHandlers: [], + finalizer: to_moz(M.bfinally) + }; + }); + + def_to_moz(AST_Catch, function To_Moz_CatchClause(M) { + return { + type: "CatchClause", + param: to_moz(M.argname), + guard: null, + body: to_moz_block(M) + }; + }); + + def_to_moz(AST_Definitions, function To_Moz_VariableDeclaration(M) { + return { + type: "VariableDeclaration", + kind: + M instanceof AST_Const ? "const" : + M instanceof AST_Let ? "let" : "var", + declarations: M.definitions.map(to_moz) + }; + }); + + const assert_clause_to_moz = assert_clause => { + const assertions = []; + if (assert_clause) { + for (const { key, value } of assert_clause.properties) { + const key_moz = is_basic_identifier_string(key) + ? { type: "Identifier", name: key } + : { type: "Literal", value: key, raw: JSON.stringify(key) }; + assertions.push({ + type: "ImportAttribute", + key: key_moz, + value: to_moz(value) + }); + } + } + return assertions; + }; + + def_to_moz(AST_Export, function To_Moz_ExportDeclaration(M) { + if (M.exported_names) { + var first_exported = M.exported_names[0]; + var first_exported_name = first_exported.name; + if (first_exported_name.name === "*" && !first_exported_name.quote) { + var foreign_name = first_exported.foreign_name; + var exported = foreign_name.name === "*" && !foreign_name.quote + ? null + : to_moz(foreign_name); + return { + type: "ExportAllDeclaration", + source: to_moz(M.module_name), + exported: exported, + assertions: assert_clause_to_moz(M.assert_clause) + }; + } + return { + type: "ExportNamedDeclaration", + specifiers: M.exported_names.map(function (name_mapping) { + return { + type: "ExportSpecifier", + exported: to_moz(name_mapping.foreign_name), + local: to_moz(name_mapping.name) + }; + }), + declaration: to_moz(M.exported_definition), + source: to_moz(M.module_name), + assertions: assert_clause_to_moz(M.assert_clause) + }; + } + return { + type: M.is_default ? "ExportDefaultDeclaration" : "ExportNamedDeclaration", + declaration: to_moz(M.exported_value || M.exported_definition) + }; + }); + + def_to_moz(AST_Import, function To_Moz_ImportDeclaration(M) { + var specifiers = []; + if (M.imported_name) { + specifiers.push({ + type: "ImportDefaultSpecifier", + local: to_moz(M.imported_name) + }); + } + if (M.imported_names) { + var first_imported_foreign_name = M.imported_names[0].foreign_name; + if (first_imported_foreign_name.name === "*" && !first_imported_foreign_name.quote) { + specifiers.push({ + type: "ImportNamespaceSpecifier", + local: to_moz(M.imported_names[0].name) + }); + } else { + M.imported_names.forEach(function(name_mapping) { + specifiers.push({ + type: "ImportSpecifier", + local: to_moz(name_mapping.name), + imported: to_moz(name_mapping.foreign_name) + }); + }); + } + } + return { + type: "ImportDeclaration", + specifiers: specifiers, + source: to_moz(M.module_name), + assertions: assert_clause_to_moz(M.assert_clause) + }; + }); + + def_to_moz(AST_ImportMeta, function To_Moz_MetaProperty() { + return { + type: "MetaProperty", + meta: { + type: "Identifier", + name: "import" + }, + property: { + type: "Identifier", + name: "meta" + } + }; + }); + + def_to_moz(AST_Sequence, function To_Moz_SequenceExpression(M) { + return { + type: "SequenceExpression", + expressions: M.expressions.map(to_moz) + }; + }); + + def_to_moz(AST_DotHash, function To_Moz_PrivateMemberExpression(M) { + return { + type: "MemberExpression", + object: to_moz(M.expression), + computed: false, + property: { + type: "PrivateIdentifier", + name: M.property + }, + optional: M.optional + }; + }); + + def_to_moz(AST_PropAccess, function To_Moz_MemberExpression(M) { + var isComputed = M instanceof AST_Sub; + return { + type: "MemberExpression", + object: to_moz(M.expression), + computed: isComputed, + property: isComputed ? to_moz(M.property) : {type: "Identifier", name: M.property}, + optional: M.optional + }; + }); + + def_to_moz(AST_Chain, function To_Moz_ChainExpression(M) { + return { + type: "ChainExpression", + expression: to_moz(M.expression) + }; + }); + + def_to_moz(AST_Unary, function To_Moz_Unary(M) { + return { + type: M.operator == "++" || M.operator == "--" ? "UpdateExpression" : "UnaryExpression", + operator: M.operator, + prefix: M instanceof AST_UnaryPrefix, + argument: to_moz(M.expression) + }; + }); + + def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) { + if (M.operator == "=" && to_moz_in_destructuring()) { + return { + type: "AssignmentPattern", + left: to_moz(M.left), + right: to_moz(M.right) + }; + } + + const type = M.operator == "&&" || M.operator == "||" || M.operator === "??" + ? "LogicalExpression" + : "BinaryExpression"; + + return { + type, + left: to_moz(M.left), + operator: M.operator, + right: to_moz(M.right) + }; + }); + + def_to_moz(AST_PrivateIn, function To_Moz_BinaryExpression_PrivateIn(M) { + return { + type: "BinaryExpression", + left: { type: "PrivateIdentifier", name: M.key.name }, + operator: "in", + right: to_moz(M.value), + }; + }); + + def_to_moz(AST_Array, function To_Moz_ArrayExpression(M) { + return { + type: "ArrayExpression", + elements: M.elements.map(to_moz) + }; + }); + + def_to_moz(AST_Object, function To_Moz_ObjectExpression(M) { + return { + type: "ObjectExpression", + properties: M.properties.map(to_moz) + }; + }); + + def_to_moz(AST_ObjectProperty, function To_Moz_Property(M, parent) { + var key = M.key instanceof AST_Node ? to_moz(M.key) : { + type: "Identifier", + value: M.key + }; + if (typeof M.key === "number") { + key = { + type: "Literal", + value: Number(M.key) + }; + } + if (typeof M.key === "string") { + key = { + type: "Identifier", + name: M.key + }; + } + var kind; + var string_or_num = typeof M.key === "string" || typeof M.key === "number"; + var computed = string_or_num ? false : !(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef; + if (M instanceof AST_ObjectKeyVal) { + kind = "init"; + computed = !string_or_num; + } else + if (M instanceof AST_ObjectGetter) { + kind = "get"; + } else + if (M instanceof AST_ObjectSetter) { + kind = "set"; + } + if (M instanceof AST_PrivateGetter || M instanceof AST_PrivateSetter) { + const kind = M instanceof AST_PrivateGetter ? "get" : "set"; + return { + type: "MethodDefinition", + computed: false, + kind: kind, + static: M.static, + key: { + type: "PrivateIdentifier", + name: M.key.name + }, + value: to_moz(M.value) + }; + } + if (M instanceof AST_ClassPrivateProperty) { + return { + type: "PropertyDefinition", + key: { + type: "PrivateIdentifier", + name: M.key.name + }, + value: to_moz(M.value), + computed: false, + static: M.static + }; + } + if (M instanceof AST_ClassProperty) { + return { + type: "PropertyDefinition", + key, + value: to_moz(M.value), + computed, + static: M.static + }; + } + if (parent instanceof AST_Class) { + return { + type: "MethodDefinition", + computed: computed, + kind: kind, + static: M.static, + key: to_moz(M.key), + value: to_moz(M.value) + }; + } + return { + type: "Property", + computed: computed, + kind: kind, + key: key, + value: to_moz(M.value) + }; + }); + + def_to_moz(AST_ConciseMethod, function To_Moz_MethodDefinition(M, parent) { + if (parent instanceof AST_Object) { + return { + type: "Property", + computed: !(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef, + kind: "init", + method: true, + shorthand: false, + key: to_moz(M.key), + value: to_moz(M.value) + }; + } + + const key = M instanceof AST_PrivateMethod + ? { + type: "PrivateIdentifier", + name: M.key.name + } + : to_moz(M.key); + + return { + type: "MethodDefinition", + kind: M.key === "constructor" ? "constructor" : "method", + key, + value: to_moz(M.value), + computed: !(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef, + static: M.static, + }; + }); + + def_to_moz(AST_Class, function To_Moz_Class(M) { + var type = M instanceof AST_ClassExpression ? "ClassExpression" : "ClassDeclaration"; + return { + type: type, + superClass: to_moz(M.extends), + id: M.name ? to_moz(M.name) : null, + body: { + type: "ClassBody", + body: M.properties.map(to_moz) + } + }; + }); + + def_to_moz(AST_ClassStaticBlock, function To_Moz_StaticBlock(M) { + return { + type: "StaticBlock", + body: M.body.map(to_moz), + }; + }); + + def_to_moz(AST_NewTarget, function To_Moz_MetaProperty() { + return { + type: "MetaProperty", + meta: { + type: "Identifier", + name: "new" + }, + property: { + type: "Identifier", + name: "target" + } + }; + }); + + def_to_moz(AST_Symbol, function To_Moz_Identifier(M, parent) { + if ( + (M instanceof AST_SymbolMethod && parent.quote) || + (( + M instanceof AST_SymbolImportForeign || + M instanceof AST_SymbolExportForeign || + M instanceof AST_SymbolExport + ) && M.quote) + ) { + return { + type: "Literal", + value: M.name + }; + } + var def = M.definition(); + return { + type: "Identifier", + name: def ? def.mangled_name || def.name : M.name + }; + }); + + def_to_moz(AST_RegExp, function To_Moz_RegExpLiteral(M) { + const pattern = M.value.source; + const flags = M.value.flags; + return { + type: "Literal", + value: null, + raw: M.print_to_string(), + regex: { pattern, flags } + }; + }); + + def_to_moz(AST_Constant, function To_Moz_Literal(M) { + var value = M.value; + return { + type: "Literal", + value: value, + raw: M.raw || M.print_to_string() + }; + }); + + def_to_moz(AST_Atom, function To_Moz_Atom(M) { + return { + type: "Identifier", + name: String(M.value) + }; + }); + + def_to_moz(AST_BigInt, M => ({ + type: "Literal", + // value cannot be represented natively + // see: https://github.com/estree/estree/blob/master/es2020.md#bigintliteral + value: null, + // `M.value` is a string that may be a hex number representation. + // but "bigint" property should have only decimal digits + bigint: typeof BigInt === "function" ? BigInt(M.value).toString() : M.value, + })); + + AST_Boolean.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast); + AST_Null.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast); + AST_Hole.DEFMETHOD("to_mozilla_ast", function To_Moz_ArrayHole() { return null; }); + + AST_Block.DEFMETHOD("to_mozilla_ast", AST_BlockStatement.prototype.to_mozilla_ast); + AST_Lambda.DEFMETHOD("to_mozilla_ast", AST_Function.prototype.to_mozilla_ast); + + /* -----[ tools ]----- */ + + function my_start_token(moznode) { + var loc = moznode.loc, start = loc && loc.start; + var range = moznode.range; + return new AST_Token( + "", + "", + start && start.line || 0, + start && start.column || 0, + range ? range [0] : moznode.start, + false, + [], + [], + loc && loc.source, + ); + } + + function my_end_token(moznode) { + var loc = moznode.loc, end = loc && loc.end; + var range = moznode.range; + return new AST_Token( + "", + "", + end && end.line || 0, + end && end.column || 0, + range ? range [0] : moznode.end, + false, + [], + [], + loc && loc.source, + ); + } + + var FROM_MOZ_STACK = null; + + function from_moz(node) { + FROM_MOZ_STACK.push(node); + var ret = node != null ? MOZ_TO_ME[node.type](node) : null; + FROM_MOZ_STACK.pop(); + return ret; + } + + AST_Node.from_mozilla_ast = function(node) { + var save_stack = FROM_MOZ_STACK; + FROM_MOZ_STACK = []; + var ast = from_moz(node); + FROM_MOZ_STACK = save_stack; + return ast; + }; + + function set_moz_loc(mynode, moznode) { + var start = mynode.start; + var end = mynode.end; + if (!(start && end)) { + return moznode; + } + if (start.pos != null && end.endpos != null) { + moznode.range = [start.pos, end.endpos]; + } + if (start.line) { + moznode.loc = { + start: {line: start.line, column: start.col}, + end: end.endline ? {line: end.endline, column: end.endcol} : null + }; + if (start.file) { + moznode.loc.source = start.file; + } + } + return moznode; + } + + function def_to_moz(mytype, handler) { + mytype.DEFMETHOD("to_mozilla_ast", function(parent) { + return set_moz_loc(this, handler(this, parent)); + }); + } + + var TO_MOZ_STACK = null; + + function to_moz(node) { + if (TO_MOZ_STACK === null) { TO_MOZ_STACK = []; } + TO_MOZ_STACK.push(node); + var ast = node != null ? node.to_mozilla_ast(TO_MOZ_STACK[TO_MOZ_STACK.length - 2]) : null; + TO_MOZ_STACK.pop(); + if (TO_MOZ_STACK.length === 0) { TO_MOZ_STACK = null; } + return ast; + } + + function to_moz_in_destructuring() { + var i = TO_MOZ_STACK.length; + while (i--) { + if (TO_MOZ_STACK[i] instanceof AST_Destructuring) { + return true; + } + } + return false; + } + + function to_moz_block(node) { + return { + type: "BlockStatement", + body: node.body.map(to_moz) + }; + } + + function to_moz_scope(type, node) { + var body = node.body.map(to_moz); + if (node.body[0] instanceof AST_SimpleStatement && node.body[0].body instanceof AST_String) { + body.unshift(to_moz(new AST_EmptyStatement(node.body[0]))); + } + return { + type: type, + body: body + }; + } +})(); + +// return true if the node at the top of the stack (that means the +// innermost node in the current output) is lexically the first in +// a statement. +function first_in_statement(stack) { + let node = stack.parent(-1); + for (let i = 0, p; p = stack.parent(i); i++) { + if (p instanceof AST_Statement && p.body === node) + return true; + if ((p instanceof AST_Sequence && p.expressions[0] === node) || + (p.TYPE === "Call" && p.expression === node) || + (p instanceof AST_PrefixedTemplateString && p.prefix === node) || + (p instanceof AST_Dot && p.expression === node) || + (p instanceof AST_Sub && p.expression === node) || + (p instanceof AST_Chain && p.expression === node) || + (p instanceof AST_Conditional && p.condition === node) || + (p instanceof AST_Binary && p.left === node) || + (p instanceof AST_UnaryPostfix && p.expression === node) + ) { + node = p; + } else { + return false; + } + } +} + +// Returns whether the leftmost item in the expression is an object +function left_is_object(node) { + if (node instanceof AST_Object) return true; + if (node instanceof AST_Sequence) return left_is_object(node.expressions[0]); + if (node.TYPE === "Call") return left_is_object(node.expression); + if (node instanceof AST_PrefixedTemplateString) return left_is_object(node.prefix); + if (node instanceof AST_Dot || node instanceof AST_Sub) return left_is_object(node.expression); + if (node instanceof AST_Chain) return left_is_object(node.expression); + if (node instanceof AST_Conditional) return left_is_object(node.condition); + if (node instanceof AST_Binary) return left_is_object(node.left); + if (node instanceof AST_UnaryPostfix) return left_is_object(node.expression); + return false; +} + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +const CODE_LINE_BREAK = 10; +const CODE_SPACE = 32; + +const r_annotation = /[@#]__(PURE|INLINE|NOINLINE)__/; + +function is_some_comments(comment) { + // multiline comment + return ( + (comment.type === "comment2" || comment.type === "comment1") + && /@preserve|@copyright|@lic|@cc_on|^\**!/i.test(comment.value) + ); +} + +const ROPE_COMMIT_WHEN = 8 * 1000; +class Rope { + constructor() { + this.committed = ""; + this.current = ""; + } + + append(str) { + /** When `this.current` is too long, commit it. */ + if (this.current.length > ROPE_COMMIT_WHEN) { + this.committed += this.current + str; + this.current = ""; + } else { + this.current += str; + } + } + + insertAt(char, index) { + const { committed, current } = this; + if (index < committed.length) { + this.committed = committed.slice(0, index) + char + committed.slice(index); + } else if (index === committed.length) { + this.committed += char; + } else { + index -= committed.length; + this.committed += current.slice(0, index) + char; + this.current = current.slice(index); + } + } + + charAt(index) { + const { committed } = this; + if (index < committed.length) return committed[index]; + return this.current[index - committed.length]; + } + + charCodeAt(index) { + const { committed } = this; + if (index < committed.length) return committed.charCodeAt(index); + return this.current.charCodeAt(index - committed.length); + } + + length() { + return this.committed.length + this.current.length; + } + + expectDirective() { + // /^$|[;{][\s\n]*$/ + + let ch, n = this.length(); + + if (n <= 0) return true; + + // Skip N whitespace from the end + while ( + (ch = this.charCodeAt(--n)) + && (ch == CODE_SPACE || ch == CODE_LINE_BREAK) + ); + + // either ";", or "{", or the string ended + return !ch || ch === 59 || ch === 123; + } + + hasNLB() { + let n = this.length() - 1; + while (n >= 0) { + const code = this.charCodeAt(n--); + + if (code === CODE_LINE_BREAK) return true; + if (code !== CODE_SPACE) return false; + } + return true; + } + + + toString() { + return this.committed + this.current; + } +} + +function OutputStream(options) { + + var readonly = !options; + options = defaults(options, { + ascii_only : false, + beautify : false, + braces : false, + comments : "some", + ecma : 5, + ie8 : false, + indent_level : 4, + indent_start : 0, + inline_script : true, + keep_numbers : false, + keep_quoted_props : false, + max_line_len : false, + preamble : null, + preserve_annotations : false, + quote_keys : false, + quote_style : 0, + safari10 : false, + semicolons : true, + shebang : true, + shorthand : undefined, + source_map : null, + webkit : false, + width : 80, + wrap_iife : false, + wrap_func_args : true, + + _destroy_ast : false + }, true); + + if (options.shorthand === undefined) + options.shorthand = options.ecma > 5; + + // Convert comment option to RegExp if necessary and set up comments filter + var comment_filter = return_false; // Default case, throw all comments away + if (options.comments) { + let comments = options.comments; + if (typeof options.comments === "string" && /^\/.*\/[a-zA-Z]*$/.test(options.comments)) { + var regex_pos = options.comments.lastIndexOf("/"); + comments = new RegExp( + options.comments.substr(1, regex_pos - 1), + options.comments.substr(regex_pos + 1) + ); + } + if (comments instanceof RegExp) { + comment_filter = function(comment) { + return comment.type != "comment5" && comments.test(comment.value); + }; + } else if (typeof comments === "function") { + comment_filter = function(comment) { + return comment.type != "comment5" && comments(this, comment); + }; + } else if (comments === "some") { + comment_filter = is_some_comments; + } else { // NOTE includes "all" option + comment_filter = return_true; + } + } + + if (options.preserve_annotations) { + let prev_comment_filter = comment_filter; + comment_filter = function (comment) { + return r_annotation.test(comment.value) || prev_comment_filter.apply(this, arguments); + }; + } + + var indentation = 0; + var current_col = 0; + var current_line = 1; + var current_pos = 0; + var OUTPUT = new Rope(); + let printed_comments = new Set(); + + var to_utf8 = options.ascii_only ? function(str, identifier = false, regexp = false) { + if (options.ecma >= 2015 && !options.safari10 && !regexp) { + str = str.replace(/[\ud800-\udbff][\udc00-\udfff]/g, function(ch) { + var code = get_full_char_code(ch, 0).toString(16); + return "\\u{" + code + "}"; + }); + } + return str.replace(/[\u0000-\u001f\u007f-\uffff]/g, function(ch) { + var code = ch.charCodeAt(0).toString(16); + if (code.length <= 2 && !identifier) { + while (code.length < 2) code = "0" + code; + return "\\x" + code; + } else { + while (code.length < 4) code = "0" + code; + return "\\u" + code; + } + }); + } : function(str) { + return str.replace(/[\ud800-\udbff][\udc00-\udfff]|([\ud800-\udbff]|[\udc00-\udfff])/g, function(match, lone) { + if (lone) { + return "\\u" + lone.charCodeAt(0).toString(16); + } + return match; + }); + }; + + function make_string(str, quote) { + var dq = 0, sq = 0; + str = str.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g, + function(s, i) { + switch (s) { + case '"': ++dq; return '"'; + case "'": ++sq; return "'"; + case "\\": return "\\\\"; + case "\n": return "\\n"; + case "\r": return "\\r"; + case "\t": return "\\t"; + case "\b": return "\\b"; + case "\f": return "\\f"; + case "\x0B": return options.ie8 ? "\\x0B" : "\\v"; + case "\u2028": return "\\u2028"; + case "\u2029": return "\\u2029"; + case "\ufeff": return "\\ufeff"; + case "\0": + return /[0-9]/.test(get_full_char(str, i+1)) ? "\\x00" : "\\0"; + } + return s; + }); + function quote_single() { + return "'" + str.replace(/\x27/g, "\\'") + "'"; + } + function quote_double() { + return '"' + str.replace(/\x22/g, '\\"') + '"'; + } + function quote_template() { + return "`" + str.replace(/`/g, "\\`") + "`"; + } + str = to_utf8(str); + if (quote === "`") return quote_template(); + switch (options.quote_style) { + case 1: + return quote_single(); + case 2: + return quote_double(); + case 3: + return quote == "'" ? quote_single() : quote_double(); + default: + return dq > sq ? quote_single() : quote_double(); + } + } + + function encode_string(str, quote) { + var ret = make_string(str, quote); + if (options.inline_script) { + ret = ret.replace(/<\x2f(script)([>\/\t\n\f\r ])/gi, "<\\/$1$2"); + ret = ret.replace(/\x3c!--/g, "\\x3c!--"); + ret = ret.replace(/--\x3e/g, "--\\x3e"); + } + return ret; + } + + function make_name(name) { + name = name.toString(); + name = to_utf8(name, true); + return name; + } + + function make_indent(back) { + return " ".repeat(options.indent_start + indentation - back * options.indent_level); + } + + /* -----[ beautification/minification ]----- */ + + var has_parens = false; + var might_need_space = false; + var might_need_semicolon = false; + var might_add_newline = 0; + var need_newline_indented = false; + var need_space = false; + var newline_insert = -1; + var last = ""; + var mapping_token, mapping_name, mappings = options.source_map && []; + + var do_add_mapping = mappings ? function() { + mappings.forEach(function(mapping) { + try { + let { name, token } = mapping; + if (name !== false) { + if (token.type == "name" || token.type === "privatename") { + name = token.value; + } else if (name instanceof AST_Symbol) { + name = token.type === "string" ? token.value : name.name; + } + } + options.source_map.add( + mapping.token.file, + mapping.line, mapping.col, + mapping.token.line, mapping.token.col, + is_basic_identifier_string(name) ? name : undefined + ); + } catch(ex) { + // Ignore bad mapping + } + }); + mappings = []; + } : noop; + + var ensure_line_len = options.max_line_len ? function() { + if (current_col > options.max_line_len) { + if (might_add_newline) { + OUTPUT.insertAt("\n", might_add_newline); + const len_after_newline = OUTPUT.length() - might_add_newline - 1; + if (mappings) { + var delta = len_after_newline - current_col; + mappings.forEach(function(mapping) { + mapping.line++; + mapping.col += delta; + }); + } + current_line++; + current_pos++; + current_col = len_after_newline; + } + } + if (might_add_newline) { + might_add_newline = 0; + do_add_mapping(); + } + } : noop; + + var requireSemicolonChars = makePredicate("( [ + * / - , . `"); + + function print(str) { + str = String(str); + var ch = get_full_char(str, 0); + if (need_newline_indented && ch) { + need_newline_indented = false; + if (ch !== "\n") { + print("\n"); + indent(); + } + } + if (need_space && ch) { + need_space = false; + if (!/[\s;})]/.test(ch)) { + space(); + } + } + newline_insert = -1; + var prev = last.charAt(last.length - 1); + if (might_need_semicolon) { + might_need_semicolon = false; + + if (prev === ":" && ch === "}" || (!ch || !";}".includes(ch)) && prev !== ";") { + if (options.semicolons || requireSemicolonChars.has(ch)) { + OUTPUT.append(";"); + current_col++; + current_pos++; + } else { + ensure_line_len(); + if (current_col > 0) { + OUTPUT.append("\n"); + current_pos++; + current_line++; + current_col = 0; + } + + if (/^\s+$/.test(str)) { + // reset the semicolon flag, since we didn't print one + // now and might still have to later + might_need_semicolon = true; + } + } + + if (!options.beautify) + might_need_space = false; + } + } + + if (might_need_space) { + if ((is_identifier_char(prev) + && (is_identifier_char(ch) || ch == "\\")) + || (ch == "/" && ch == prev) + || ((ch == "+" || ch == "-") && ch == last) + ) { + OUTPUT.append(" "); + current_col++; + current_pos++; + } + might_need_space = false; + } + + if (mapping_token) { + mappings.push({ + token: mapping_token, + name: mapping_name, + line: current_line, + col: current_col + }); + mapping_token = false; + if (!might_add_newline) do_add_mapping(); + } + + OUTPUT.append(str); + has_parens = str[str.length - 1] == "("; + current_pos += str.length; + var a = str.split(/\r?\n/), n = a.length - 1; + current_line += n; + current_col += a[0].length; + if (n > 0) { + ensure_line_len(); + current_col = a[n].length; + } + last = str; + } + + var star = function() { + print("*"); + }; + + var space = options.beautify ? function() { + print(" "); + } : function() { + might_need_space = true; + }; + + var indent = options.beautify ? function(half) { + if (options.beautify) { + print(make_indent(half ? 0.5 : 0)); + } + } : noop; + + var with_indent = options.beautify ? function(col, cont) { + if (col === true) col = next_indent(); + var save_indentation = indentation; + indentation = col; + var ret = cont(); + indentation = save_indentation; + return ret; + } : function(col, cont) { return cont(); }; + + var newline = options.beautify ? function() { + if (newline_insert < 0) return print("\n"); + if (OUTPUT.charAt(newline_insert) != "\n") { + OUTPUT.insertAt("\n", newline_insert); + current_pos++; + current_line++; + } + newline_insert++; + } : options.max_line_len ? function() { + ensure_line_len(); + might_add_newline = OUTPUT.length(); + } : noop; + + var semicolon = options.beautify ? function() { + print(";"); + } : function() { + might_need_semicolon = true; + }; + + function force_semicolon() { + might_need_semicolon = false; + print(";"); + } + + function next_indent() { + return indentation + options.indent_level; + } + + function with_block(cont) { + var ret; + print("{"); + newline(); + with_indent(next_indent(), function() { + ret = cont(); + }); + indent(); + print("}"); + return ret; + } + + function with_parens(cont) { + print("("); + //XXX: still nice to have that for argument lists + //var ret = with_indent(current_col, cont); + var ret = cont(); + print(")"); + return ret; + } + + function with_square(cont) { + print("["); + //var ret = with_indent(current_col, cont); + var ret = cont(); + print("]"); + return ret; + } + + function comma() { + print(","); + space(); + } + + function colon() { + print(":"); + space(); + } + + var add_mapping = mappings ? function(token, name) { + mapping_token = token; + mapping_name = name; + } : noop; + + function get() { + if (might_add_newline) { + ensure_line_len(); + } + return OUTPUT.toString(); + } + + function filter_comment(comment) { + if (!options.preserve_annotations) { + comment = comment.replace(r_annotation, " "); + } + if (/^\s*$/.test(comment)) { + return ""; + } + return comment.replace(/(<\s*\/\s*)(script)/i, "<\\/$2"); + } + + function prepend_comments(node) { + var self = this; + var start = node.start; + if (!start) return; + var printed_comments = self.printed_comments; + + // There cannot be a newline between return/yield and its value. + const keyword_with_value = + node instanceof AST_Exit && node.value + || (node instanceof AST_Await || node instanceof AST_Yield) + && node.expression; + + if ( + start.comments_before + && printed_comments.has(start.comments_before) + ) { + if (keyword_with_value) { + start.comments_before = []; + } else { + return; + } + } + + var comments = start.comments_before; + if (!comments) { + comments = start.comments_before = []; + } + printed_comments.add(comments); + + if (keyword_with_value) { + var tw = new TreeWalker(function(node) { + var parent = tw.parent(); + if (parent instanceof AST_Exit + || parent instanceof AST_Await + || parent instanceof AST_Yield + || parent instanceof AST_Binary && parent.left === node + || parent.TYPE == "Call" && parent.expression === node + || parent instanceof AST_Conditional && parent.condition === node + || parent instanceof AST_Dot && parent.expression === node + || parent instanceof AST_Sequence && parent.expressions[0] === node + || parent instanceof AST_Sub && parent.expression === node + || parent instanceof AST_UnaryPostfix) { + if (!node.start) return; + var text = node.start.comments_before; + if (text && !printed_comments.has(text)) { + printed_comments.add(text); + comments = comments.concat(text); + } + } else { + return true; + } + }); + tw.push(node); + keyword_with_value.walk(tw); + } + + if (current_pos == 0) { + if (comments.length > 0 && options.shebang && comments[0].type === "comment5" + && !printed_comments.has(comments[0])) { + print("#!" + comments.shift().value + "\n"); + indent(); + } + var preamble = options.preamble; + if (preamble) { + print(preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n")); + } + } + + comments = comments.filter(comment_filter, node).filter(c => !printed_comments.has(c)); + if (comments.length == 0) return; + var last_nlb = OUTPUT.hasNLB(); + comments.forEach(function(c, i) { + printed_comments.add(c); + if (!last_nlb) { + if (c.nlb) { + print("\n"); + indent(); + last_nlb = true; + } else if (i > 0) { + space(); + } + } + + if (/comment[134]/.test(c.type)) { + var value = filter_comment(c.value); + if (value) { + print("//" + value + "\n"); + indent(); + } + last_nlb = true; + } else if (c.type == "comment2") { + var value = filter_comment(c.value); + if (value) { + print("/*" + value + "*/"); + } + last_nlb = false; + } + }); + if (!last_nlb) { + if (start.nlb) { + print("\n"); + indent(); + } else { + space(); + } + } + } + + function append_comments(node, tail) { + var self = this; + var token = node.end; + if (!token) return; + var printed_comments = self.printed_comments; + var comments = token[tail ? "comments_before" : "comments_after"]; + if (!comments || printed_comments.has(comments)) return; + if (!(node instanceof AST_Statement || comments.every((c) => + !/comment[134]/.test(c.type) + ))) return; + printed_comments.add(comments); + var insert = OUTPUT.length(); + comments.filter(comment_filter, node).forEach(function(c, i) { + if (printed_comments.has(c)) return; + printed_comments.add(c); + need_space = false; + if (need_newline_indented) { + print("\n"); + indent(); + need_newline_indented = false; + } else if (c.nlb && (i > 0 || !OUTPUT.hasNLB())) { + print("\n"); + indent(); + } else if (i > 0 || !tail) { + space(); + } + if (/comment[134]/.test(c.type)) { + const value = filter_comment(c.value); + if (value) { + print("//" + value); + } + need_newline_indented = true; + } else if (c.type == "comment2") { + const value = filter_comment(c.value); + if (value) { + print("/*" + value + "*/"); + } + need_space = true; + } + }); + if (OUTPUT.length() > insert) newline_insert = insert; + } + + /** + * When output.option("_destroy_ast") is enabled, destroy the function. + * Call this after printing it. + */ + const gc_scope = + options["_destroy_ast"] + ? function gc_scope(scope) { + scope.body.length = 0; + scope.argnames.length = 0; + } + : noop; + + var stack = []; + return { + get : get, + toString : get, + indent : indent, + in_directive : false, + use_asm : null, + active_scope : null, + indentation : function() { return indentation; }, + current_width : function() { return current_col - indentation; }, + should_break : function() { return options.width && this.current_width() >= options.width; }, + has_parens : function() { return has_parens; }, + newline : newline, + print : print, + star : star, + space : space, + comma : comma, + colon : colon, + last : function() { return last; }, + semicolon : semicolon, + force_semicolon : force_semicolon, + to_utf8 : to_utf8, + print_name : function(name) { print(make_name(name)); }, + print_string : function(str, quote, escape_directive) { + var encoded = encode_string(str, quote); + if (escape_directive === true && !encoded.includes("\\")) { + // Insert semicolons to break directive prologue + if (!OUTPUT.expectDirective()) { + force_semicolon(); + } + force_semicolon(); + } + print(encoded); + }, + print_template_string_chars: function(str) { + var encoded = encode_string(str, "`").replace(/\${/g, "\\${"); + return print(encoded.substr(1, encoded.length - 2)); + }, + encode_string : encode_string, + next_indent : next_indent, + with_indent : with_indent, + with_block : with_block, + with_parens : with_parens, + with_square : with_square, + add_mapping : add_mapping, + option : function(opt) { return options[opt]; }, + gc_scope, + printed_comments: printed_comments, + prepend_comments: readonly ? noop : prepend_comments, + append_comments : readonly || comment_filter === return_false ? noop : append_comments, + line : function() { return current_line; }, + col : function() { return current_col; }, + pos : function() { return current_pos; }, + push_node : function(node) { stack.push(node); }, + pop_node : function() { return stack.pop(); }, + parent : function(n) { + return stack[stack.length - 2 - (n || 0)]; + } + }; + +} + +/* -----[ code generators ]----- */ + +(function() { + + /* -----[ utils ]----- */ + + function DEFPRINT(nodetype, generator) { + nodetype.DEFMETHOD("_codegen", generator); + } + + AST_Node.DEFMETHOD("print", function(output, force_parens) { + var self = this, generator = self._codegen; + if (self instanceof AST_Scope) { + output.active_scope = self; + } else if (!output.use_asm && self instanceof AST_Directive && self.value == "use asm") { + output.use_asm = output.active_scope; + } + function doit() { + output.prepend_comments(self); + self.add_source_map(output); + generator(self, output); + output.append_comments(self); + } + output.push_node(self); + if (force_parens || self.needs_parens(output)) { + output.with_parens(doit); + } else { + doit(); + } + output.pop_node(); + if (self === output.use_asm) { + output.use_asm = null; + } + }); + AST_Node.DEFMETHOD("_print", AST_Node.prototype.print); + + AST_Node.DEFMETHOD("print_to_string", function(options) { + var output = OutputStream(options); + this.print(output); + return output.get(); + }); + + /* -----[ PARENTHESES ]----- */ + + function PARENS(nodetype, func) { + if (Array.isArray(nodetype)) { + nodetype.forEach(function(nodetype) { + PARENS(nodetype, func); + }); + } else { + nodetype.DEFMETHOD("needs_parens", func); + } + } + + PARENS(AST_Node, return_false); + + // a function expression needs parens around it when it's provably + // the first token to appear in a statement. + PARENS(AST_Function, function(output) { + if (!output.has_parens() && first_in_statement(output)) { + return true; + } + + if (output.option("webkit")) { + var p = output.parent(); + if (p instanceof AST_PropAccess && p.expression === this) { + return true; + } + } + + if (output.option("wrap_iife")) { + var p = output.parent(); + if (p instanceof AST_Call && p.expression === this) { + return true; + } + } + + if (output.option("wrap_func_args")) { + var p = output.parent(); + if (p instanceof AST_Call && p.args.includes(this)) { + return true; + } + } + + return false; + }); + + PARENS(AST_Arrow, function(output) { + var p = output.parent(); + + if ( + output.option("wrap_func_args") + && p instanceof AST_Call + && p.args.includes(this) + ) { + return true; + } + return p instanceof AST_PropAccess && p.expression === this + || p instanceof AST_Conditional && p.condition === this; + }); + + // same goes for an object literal (as in AST_Function), because + // otherwise {...} would be interpreted as a block of code. + PARENS(AST_Object, function(output) { + return !output.has_parens() && first_in_statement(output); + }); + + PARENS(AST_ClassExpression, first_in_statement); + + PARENS(AST_Unary, function(output) { + var p = output.parent(); + return p instanceof AST_PropAccess && p.expression === this + || p instanceof AST_Call && p.expression === this + || p instanceof AST_Binary + && p.operator === "**" + && this instanceof AST_UnaryPrefix + && p.left === this + && this.operator !== "++" + && this.operator !== "--"; + }); + + PARENS(AST_Await, function(output) { + var p = output.parent(); + return p instanceof AST_PropAccess && p.expression === this + || p instanceof AST_Call && p.expression === this + || p instanceof AST_Binary && p.operator === "**" && p.left === this + || output.option("safari10") && p instanceof AST_UnaryPrefix; + }); + + PARENS(AST_Sequence, function(output) { + var p = output.parent(); + return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4) + || p instanceof AST_Unary // !(foo, bar, baz) + || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8 + || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4 + || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2 + || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ] + || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2 + || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30) + * ==> 20 (side effect, set a := 10 and b := 20) */ + || p instanceof AST_Arrow // x => (x, x) + || p instanceof AST_DefaultAssign // x => (x = (0, function(){})) + || p instanceof AST_Expansion // [...(a, b)] + || p instanceof AST_ForOf && this === p.object // for (e of (foo, bar)) {} + || p instanceof AST_Yield // yield (foo, bar) + || p instanceof AST_Export // export default (foo, bar) + ; + }); + + PARENS(AST_Binary, function(output) { + var p = output.parent(); + // (foo && bar)() + if (p instanceof AST_Call && p.expression === this) + return true; + // typeof (foo && bar) + if (p instanceof AST_Unary) + return true; + // (foo && bar)["prop"], (foo && bar).prop + if (p instanceof AST_PropAccess && p.expression === this) + return true; + // this deals with precedence: 3 * (2 + 1) + if (p instanceof AST_Binary) { + const parent_op = p.operator; + const op = this.operator; + + // It is forbidden for ?? to be used with || or && without parens. + if (op === "??" && (parent_op === "||" || parent_op === "&&")) { + return true; + } + if (parent_op === "??" && (op === "||" || op === "&&")) { + return true; + } + + const pp = PRECEDENCE[parent_op]; + const sp = PRECEDENCE[op]; + if (pp > sp + || (pp == sp + && (this === p.right || parent_op == "**"))) { + return true; + } + } + if (p instanceof AST_PrivateIn) { + const op = this.operator; + + const pp = PRECEDENCE["in"]; + const sp = PRECEDENCE[op]; + if (pp > sp || (pp == sp && this === p.value)) { + return true; + } + } + }); + + PARENS(AST_PrivateIn, function(output) { + var p = output.parent(); + // (#x in this)() + if (p instanceof AST_Call && p.expression === this) { + return true; + } + // typeof (#x in this) + if (p instanceof AST_Unary) { + return true; + } + // (#x in this)["prop"], (#x in this).prop + if (p instanceof AST_PropAccess && p.expression === this) { + return true; + } + // same precedence as regular in operator + if (p instanceof AST_Binary) { + const parent_op = p.operator; + + const pp = PRECEDENCE[parent_op]; + const sp = PRECEDENCE["in"]; + if (pp > sp + || (pp == sp + && (this === p.right || parent_op == "**"))) { + return true; + } + } + // rules are the same as binary in, but the class differs + if (p instanceof AST_PrivateIn && this === p.value) { + return true; + } + }); + + PARENS(AST_Yield, function(output) { + var p = output.parent(); + // (yield 1) + (yield 2) + // a = yield 3 + if (p instanceof AST_Binary && p.operator !== "=") + return true; + // (yield 1)() + // new (yield 1)() + if (p instanceof AST_Call && p.expression === this) + return true; + // (yield 1) ? yield 2 : yield 3 + if (p instanceof AST_Conditional && p.condition === this) + return true; + // -(yield 4) + if (p instanceof AST_Unary) + return true; + // (yield x).foo + // (yield x)['foo'] + if (p instanceof AST_PropAccess && p.expression === this) + return true; + }); + + PARENS(AST_Chain, function(output) { + var p = output.parent(); + if (!(p instanceof AST_Call || p instanceof AST_PropAccess)) return false; + return p.expression === this; + }); + + PARENS(AST_PropAccess, function(output) { + var p = output.parent(); + if (p instanceof AST_New && p.expression === this) { + // i.e. new (foo.bar().baz) + // + // if there's one call into this subtree, then we need + // parens around it too, otherwise the call will be + // interpreted as passing the arguments to the upper New + // expression. + return walk(this, node => { + if (node instanceof AST_Scope) return true; + if (node instanceof AST_Call) { + return walk_abort; // makes walk() return true. + } + }); + } + }); + + PARENS(AST_Call, function(output) { + var p = output.parent(), p1; + if (p instanceof AST_New && p.expression === this + || p instanceof AST_Export && p.is_default && this.expression instanceof AST_Function) + return true; + + // workaround for Safari bug. + // https://bugs.webkit.org/show_bug.cgi?id=123506 + return this.expression instanceof AST_Function + && p instanceof AST_PropAccess + && p.expression === this + && (p1 = output.parent(1)) instanceof AST_Assign + && p1.left === p; + }); + + PARENS(AST_New, function(output) { + var p = output.parent(); + if (this.args.length === 0 + && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]() + || p instanceof AST_Call && p.expression === this + || p instanceof AST_PrefixedTemplateString && p.prefix === this)) // (new foo)(bar) + return true; + }); + + PARENS(AST_Number, function(output) { + var p = output.parent(); + if (p instanceof AST_PropAccess && p.expression === this) { + var value = this.getValue(); + if (value < 0 || /^0/.test(make_num(value))) { + return true; + } + } + }); + + PARENS(AST_BigInt, function(output) { + var p = output.parent(); + if (p instanceof AST_PropAccess && p.expression === this) { + var value = this.getValue(); + if (value.startsWith("-")) { + return true; + } + } + }); + + PARENS([ AST_Assign, AST_Conditional ], function(output) { + var p = output.parent(); + // !(a = false) → true + if (p instanceof AST_Unary) + return true; + // 1 + (a = 2) + 3 → 6, side effect setting a = 2 + if (p instanceof AST_Binary && !(p instanceof AST_Assign)) + return true; + // (a = func)() —or— new (a = Object)() + if (p instanceof AST_Call && p.expression === this) + return true; + // (a = foo) ? bar : baz + if (p instanceof AST_Conditional && p.condition === this) + return true; + // (a = foo)["prop"] —or— (a = foo).prop + if (p instanceof AST_PropAccess && p.expression === this) + return true; + // ({a, b} = {a: 1, b: 2}), a destructuring assignment + if (this instanceof AST_Assign && this.left instanceof AST_Destructuring && this.left.is_array === false) + return true; + }); + + /* -----[ PRINTERS ]----- */ + + DEFPRINT(AST_Directive, function(self, output) { + output.print_string(self.value, self.quote); + output.semicolon(); + }); + + DEFPRINT(AST_Expansion, function (self, output) { + output.print("..."); + self.expression.print(output); + }); + + DEFPRINT(AST_Destructuring, function (self, output) { + output.print(self.is_array ? "[" : "{"); + var len = self.names.length; + self.names.forEach(function (name, i) { + if (i > 0) output.comma(); + name.print(output); + // If the final element is a hole, we need to make sure it + // doesn't look like a trailing comma, by inserting an actual + // trailing comma. + if (i == len - 1 && name instanceof AST_Hole) output.comma(); + }); + output.print(self.is_array ? "]" : "}"); + }); + + DEFPRINT(AST_Debugger, function(self, output) { + output.print("debugger"); + output.semicolon(); + }); + + /* -----[ statements ]----- */ + + function display_body(body, is_toplevel, output, allow_directives) { + var last = body.length - 1; + output.in_directive = allow_directives; + body.forEach(function(stmt, i) { + if (output.in_directive === true && !(stmt instanceof AST_Directive || + stmt instanceof AST_EmptyStatement || + (stmt instanceof AST_SimpleStatement && stmt.body instanceof AST_String) + )) { + output.in_directive = false; + } + if (!(stmt instanceof AST_EmptyStatement)) { + output.indent(); + stmt.print(output); + if (!(i == last && is_toplevel)) { + output.newline(); + if (is_toplevel) output.newline(); + } + } + if (output.in_directive === true && + stmt instanceof AST_SimpleStatement && + stmt.body instanceof AST_String + ) { + output.in_directive = false; + } + }); + output.in_directive = false; + } + + AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output) { + print_maybe_braced_body(this.body, output); + }); + + DEFPRINT(AST_Statement, function(self, output) { + self.body.print(output); + output.semicolon(); + }); + DEFPRINT(AST_Toplevel, function(self, output) { + display_body(self.body, true, output, true); + output.print(""); + }); + DEFPRINT(AST_LabeledStatement, function(self, output) { + self.label.print(output); + output.colon(); + self.body.print(output); + }); + DEFPRINT(AST_SimpleStatement, function(self, output) { + self.body.print(output); + output.semicolon(); + }); + function print_braced_empty(self, output) { + output.print("{"); + output.with_indent(output.next_indent(), function() { + output.append_comments(self, true); + }); + output.add_mapping(self.end); + output.print("}"); + } + function print_braced(self, output, allow_directives) { + if (self.body.length > 0) { + output.with_block(function() { + display_body(self.body, false, output, allow_directives); + output.add_mapping(self.end); + }); + } else print_braced_empty(self, output); + } + DEFPRINT(AST_BlockStatement, function(self, output) { + print_braced(self, output); + }); + DEFPRINT(AST_EmptyStatement, function(self, output) { + output.semicolon(); + }); + DEFPRINT(AST_Do, function(self, output) { + output.print("do"); + output.space(); + make_block(self.body, output); + output.space(); + output.print("while"); + output.space(); + output.with_parens(function() { + self.condition.print(output); + }); + output.semicolon(); + }); + DEFPRINT(AST_While, function(self, output) { + output.print("while"); + output.space(); + output.with_parens(function() { + self.condition.print(output); + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_For, function(self, output) { + output.print("for"); + output.space(); + output.with_parens(function() { + if (self.init) { + if (self.init instanceof AST_Definitions) { + self.init.print(output); + } else { + parenthesize_for_noin(self.init, output, true); + } + output.print(";"); + output.space(); + } else { + output.print(";"); + } + if (self.condition) { + self.condition.print(output); + output.print(";"); + output.space(); + } else { + output.print(";"); + } + if (self.step) { + self.step.print(output); + } + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_ForIn, function(self, output) { + output.print("for"); + if (self.await) { + output.space(); + output.print("await"); + } + output.space(); + output.with_parens(function() { + self.init.print(output); + output.space(); + output.print(self instanceof AST_ForOf ? "of" : "in"); + output.space(); + self.object.print(output); + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_With, function(self, output) { + output.print("with"); + output.space(); + output.with_parens(function() { + self.expression.print(output); + }); + output.space(); + self._do_print_body(output); + }); + + /* -----[ functions ]----- */ + AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword) { + var self = this; + if (!nokeyword) { + if (self.async) { + output.print("async"); + output.space(); + } + output.print("function"); + if (self.is_generator) { + output.star(); + } + if (self.name) { + output.space(); + } + } + if (self.name instanceof AST_Symbol) { + self.name.print(output); + } else if (nokeyword && self.name instanceof AST_Node) { + output.with_square(function() { + self.name.print(output); // Computed method name + }); + } + output.with_parens(function() { + self.argnames.forEach(function(arg, i) { + if (i) output.comma(); + arg.print(output); + }); + }); + output.space(); + print_braced(self, output, true); + }); + DEFPRINT(AST_Lambda, function(self, output) { + self._do_print(output); + output.gc_scope(self); + }); + + DEFPRINT(AST_PrefixedTemplateString, function(self, output) { + var tag = self.prefix; + var parenthesize_tag = tag instanceof AST_Lambda + || tag instanceof AST_Binary + || tag instanceof AST_Conditional + || tag instanceof AST_Sequence + || tag instanceof AST_Unary + || tag instanceof AST_Dot && tag.expression instanceof AST_Object; + if (parenthesize_tag) output.print("("); + self.prefix.print(output); + if (parenthesize_tag) output.print(")"); + self.template_string.print(output); + }); + DEFPRINT(AST_TemplateString, function(self, output) { + var is_tagged = output.parent() instanceof AST_PrefixedTemplateString; + + output.print("`"); + for (var i = 0; i < self.segments.length; i++) { + if (!(self.segments[i] instanceof AST_TemplateSegment)) { + output.print("${"); + self.segments[i].print(output); + output.print("}"); + } else if (is_tagged) { + output.print(self.segments[i].raw); + } else { + output.print_template_string_chars(self.segments[i].value); + } + } + output.print("`"); + }); + DEFPRINT(AST_TemplateSegment, function(self, output) { + output.print_template_string_chars(self.value); + }); + + AST_Arrow.DEFMETHOD("_do_print", function(output) { + var self = this; + var parent = output.parent(); + var needs_parens = (parent instanceof AST_Binary && + !(parent instanceof AST_Assign) && + !(parent instanceof AST_DefaultAssign)) || + parent instanceof AST_Unary || + (parent instanceof AST_Call && self === parent.expression); + if (needs_parens) { output.print("("); } + if (self.async) { + output.print("async"); + output.space(); + } + if (self.argnames.length === 1 && self.argnames[0] instanceof AST_Symbol) { + self.argnames[0].print(output); + } else { + output.with_parens(function() { + self.argnames.forEach(function(arg, i) { + if (i) output.comma(); + arg.print(output); + }); + }); + } + output.space(); + output.print("=>"); + output.space(); + const first_statement = self.body[0]; + if ( + self.body.length === 1 + && first_statement instanceof AST_Return + ) { + const returned = first_statement.value; + if (!returned) { + output.print("{}"); + } else if (left_is_object(returned)) { + output.print("("); + returned.print(output); + output.print(")"); + } else { + returned.print(output); + } + } else { + print_braced(self, output); + } + if (needs_parens) { output.print(")"); } + output.gc_scope(self); + }); + + /* -----[ exits ]----- */ + AST_Exit.DEFMETHOD("_do_print", function(output, kind) { + output.print(kind); + if (this.value) { + output.space(); + const comments = this.value.start.comments_before; + if (comments && comments.length && !output.printed_comments.has(comments)) { + output.print("("); + this.value.print(output); + output.print(")"); + } else { + this.value.print(output); + } + } + output.semicolon(); + }); + DEFPRINT(AST_Return, function(self, output) { + self._do_print(output, "return"); + }); + DEFPRINT(AST_Throw, function(self, output) { + self._do_print(output, "throw"); + }); + + /* -----[ yield ]----- */ + + DEFPRINT(AST_Yield, function(self, output) { + var star = self.is_star ? "*" : ""; + output.print("yield" + star); + if (self.expression) { + output.space(); + self.expression.print(output); + } + }); + + DEFPRINT(AST_Await, function(self, output) { + output.print("await"); + output.space(); + var e = self.expression; + var parens = !( + e instanceof AST_Call + || e instanceof AST_SymbolRef + || e instanceof AST_PropAccess + || e instanceof AST_Unary + || e instanceof AST_Constant + || e instanceof AST_Await + || e instanceof AST_Object + ); + if (parens) output.print("("); + self.expression.print(output); + if (parens) output.print(")"); + }); + + /* -----[ loop control ]----- */ + AST_LoopControl.DEFMETHOD("_do_print", function(output, kind) { + output.print(kind); + if (this.label) { + output.space(); + this.label.print(output); + } + output.semicolon(); + }); + DEFPRINT(AST_Break, function(self, output) { + self._do_print(output, "break"); + }); + DEFPRINT(AST_Continue, function(self, output) { + self._do_print(output, "continue"); + }); + + /* -----[ if ]----- */ + function make_then(self, output) { + var b = self.body; + if (output.option("braces") + || output.option("ie8") && b instanceof AST_Do) + return make_block(b, output); + // The squeezer replaces "block"-s that contain only a single + // statement with the statement itself; technically, the AST + // is correct, but this can create problems when we output an + // IF having an ELSE clause where the THEN clause ends in an + // IF *without* an ELSE block (then the outer ELSE would refer + // to the inner IF). This function checks for this case and + // adds the block braces if needed. + if (!b) return output.force_semicolon(); + while (true) { + if (b instanceof AST_If) { + if (!b.alternative) { + make_block(self.body, output); + return; + } + b = b.alternative; + } else if (b instanceof AST_StatementWithBody) { + b = b.body; + } else break; + } + print_maybe_braced_body(self.body, output); + } + DEFPRINT(AST_If, function(self, output) { + output.print("if"); + output.space(); + output.with_parens(function() { + self.condition.print(output); + }); + output.space(); + if (self.alternative) { + make_then(self, output); + output.space(); + output.print("else"); + output.space(); + if (self.alternative instanceof AST_If) + self.alternative.print(output); + else + print_maybe_braced_body(self.alternative, output); + } else { + self._do_print_body(output); + } + }); + + /* -----[ switch ]----- */ + DEFPRINT(AST_Switch, function(self, output) { + output.print("switch"); + output.space(); + output.with_parens(function() { + self.expression.print(output); + }); + output.space(); + var last = self.body.length - 1; + if (last < 0) print_braced_empty(self, output); + else output.with_block(function() { + self.body.forEach(function(branch, i) { + output.indent(true); + branch.print(output); + if (i < last && branch.body.length > 0) + output.newline(); + }); + }); + }); + AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output) { + output.newline(); + this.body.forEach(function(stmt) { + output.indent(); + stmt.print(output); + output.newline(); + }); + }); + DEFPRINT(AST_Default, function(self, output) { + output.print("default:"); + self._do_print_body(output); + }); + DEFPRINT(AST_Case, function(self, output) { + output.print("case"); + output.space(); + self.expression.print(output); + output.print(":"); + self._do_print_body(output); + }); + + /* -----[ exceptions ]----- */ + DEFPRINT(AST_Try, function(self, output) { + output.print("try"); + output.space(); + self.body.print(output); + if (self.bcatch) { + output.space(); + self.bcatch.print(output); + } + if (self.bfinally) { + output.space(); + self.bfinally.print(output); + } + }); + DEFPRINT(AST_TryBlock, function(self, output) { + print_braced(self, output); + }); + DEFPRINT(AST_Catch, function(self, output) { + output.print("catch"); + if (self.argname) { + output.space(); + output.with_parens(function() { + self.argname.print(output); + }); + } + output.space(); + print_braced(self, output); + }); + DEFPRINT(AST_Finally, function(self, output) { + output.print("finally"); + output.space(); + print_braced(self, output); + }); + + /* -----[ var/const ]----- */ + AST_Definitions.DEFMETHOD("_do_print", function(output, kind) { + output.print(kind); + output.space(); + this.definitions.forEach(function(def, i) { + if (i) output.comma(); + def.print(output); + }); + var p = output.parent(); + var in_for = p instanceof AST_For || p instanceof AST_ForIn; + var output_semicolon = !in_for || p && p.init !== this; + if (output_semicolon) + output.semicolon(); + }); + DEFPRINT(AST_Let, function(self, output) { + self._do_print(output, "let"); + }); + DEFPRINT(AST_Var, function(self, output) { + self._do_print(output, "var"); + }); + DEFPRINT(AST_Const, function(self, output) { + self._do_print(output, "const"); + }); + DEFPRINT(AST_Import, function(self, output) { + output.print("import"); + output.space(); + if (self.imported_name) { + self.imported_name.print(output); + } + if (self.imported_name && self.imported_names) { + output.print(","); + output.space(); + } + if (self.imported_names) { + if (self.imported_names.length === 1 && + self.imported_names[0].foreign_name.name === "*" && + !self.imported_names[0].foreign_name.quote) { + self.imported_names[0].print(output); + } else { + output.print("{"); + self.imported_names.forEach(function (name_import, i) { + output.space(); + name_import.print(output); + if (i < self.imported_names.length - 1) { + output.print(","); + } + }); + output.space(); + output.print("}"); + } + } + if (self.imported_name || self.imported_names) { + output.space(); + output.print("from"); + output.space(); + } + self.module_name.print(output); + if (self.assert_clause) { + output.print("assert"); + self.assert_clause.print(output); + } + output.semicolon(); + }); + DEFPRINT(AST_ImportMeta, function(self, output) { + output.print("import.meta"); + }); + + DEFPRINT(AST_NameMapping, function(self, output) { + var is_import = output.parent() instanceof AST_Import; + var definition = self.name.definition(); + var foreign_name = self.foreign_name; + var names_are_different = + (definition && definition.mangled_name || self.name.name) !== + foreign_name.name; + if (!names_are_different && + foreign_name.name === "*" && + foreign_name.quote != self.name.quote) { + // export * as "*" + names_are_different = true; + } + var foreign_name_is_name = foreign_name.quote == null; + if (names_are_different) { + if (is_import) { + if (foreign_name_is_name) { + output.print(foreign_name.name); + } else { + output.print_string(foreign_name.name, foreign_name.quote); + } + } else { + if (self.name.quote == null) { + self.name.print(output); + } else { + output.print_string(self.name.name, self.name.quote); + } + + } + output.space(); + output.print("as"); + output.space(); + if (is_import) { + self.name.print(output); + } else { + if (foreign_name_is_name) { + output.print(foreign_name.name); + } else { + output.print_string(foreign_name.name, foreign_name.quote); + } + } + } else { + if (self.name.quote == null) { + self.name.print(output); + } else { + output.print_string(self.name.name, self.name.quote); + } + } + }); + + DEFPRINT(AST_Export, function(self, output) { + output.print("export"); + output.space(); + if (self.is_default) { + output.print("default"); + output.space(); + } + if (self.exported_names) { + if (self.exported_names.length === 1 && + self.exported_names[0].name.name === "*" && + !self.exported_names[0].name.quote) { + self.exported_names[0].print(output); + } else { + output.print("{"); + self.exported_names.forEach(function(name_export, i) { + output.space(); + name_export.print(output); + if (i < self.exported_names.length - 1) { + output.print(","); + } + }); + output.space(); + output.print("}"); + } + } else if (self.exported_value) { + self.exported_value.print(output); + } else if (self.exported_definition) { + self.exported_definition.print(output); + if (self.exported_definition instanceof AST_Definitions) return; + } + if (self.module_name) { + output.space(); + output.print("from"); + output.space(); + self.module_name.print(output); + } + if (self.assert_clause) { + output.print("assert"); + self.assert_clause.print(output); + } + if (self.exported_value + && !(self.exported_value instanceof AST_Defun || + self.exported_value instanceof AST_Function || + self.exported_value instanceof AST_Class) + || self.module_name + || self.exported_names + ) { + output.semicolon(); + } + }); + + function parenthesize_for_noin(node, output, noin) { + var parens = false; + // need to take some precautions here: + // https://github.com/mishoo/UglifyJS2/issues/60 + if (noin) { + parens = walk(node, node => { + // Don't go into scopes -- except arrow functions: + // https://github.com/terser/terser/issues/1019#issuecomment-877642607 + if (node instanceof AST_Scope && !(node instanceof AST_Arrow)) { + return true; + } + if ( + node instanceof AST_Binary && node.operator == "in" + || node instanceof AST_PrivateIn + ) { + return walk_abort; // makes walk() return true + } + }); + } + node.print(output, parens); + } + + DEFPRINT(AST_VarDef, function(self, output) { + self.name.print(output); + if (self.value) { + output.space(); + output.print("="); + output.space(); + var p = output.parent(1); + var noin = p instanceof AST_For || p instanceof AST_ForIn; + parenthesize_for_noin(self.value, output, noin); + } + }); + + /* -----[ other expressions ]----- */ + DEFPRINT(AST_Call, function(self, output) { + self.expression.print(output); + if (self instanceof AST_New && self.args.length === 0) + return; + if (self.expression instanceof AST_Call || self.expression instanceof AST_Lambda) { + output.add_mapping(self.start); + } + if (self.optional) output.print("?."); + output.with_parens(function() { + self.args.forEach(function(expr, i) { + if (i) output.comma(); + expr.print(output); + }); + }); + }); + DEFPRINT(AST_New, function(self, output) { + output.print("new"); + output.space(); + AST_Call.prototype._codegen(self, output); + }); + + AST_Sequence.DEFMETHOD("_do_print", function(output) { + this.expressions.forEach(function(node, index) { + if (index > 0) { + output.comma(); + if (output.should_break()) { + output.newline(); + output.indent(); + } + } + node.print(output); + }); + }); + DEFPRINT(AST_Sequence, function(self, output) { + self._do_print(output); + // var p = output.parent(); + // if (p instanceof AST_Statement) { + // output.with_indent(output.next_indent(), function(){ + // self._do_print(output); + // }); + // } else { + // self._do_print(output); + // } + }); + DEFPRINT(AST_Dot, function(self, output) { + var expr = self.expression; + expr.print(output); + var prop = self.property; + var print_computed = ALL_RESERVED_WORDS.has(prop) + ? output.option("ie8") + : !is_identifier_string( + prop, + output.option("ecma") >= 2015 && !output.option("safari10") + ); + + if (self.optional) output.print("?."); + + if (print_computed) { + output.print("["); + output.add_mapping(self.end); + output.print_string(prop); + output.print("]"); + } else { + if (expr instanceof AST_Number && expr.getValue() >= 0) { + if (!/[xa-f.)]/i.test(output.last())) { + output.print("."); + } + } + if (!self.optional) output.print("."); + // the name after dot would be mapped about here. + output.add_mapping(self.end); + output.print_name(prop); + } + }); + DEFPRINT(AST_DotHash, function(self, output) { + var expr = self.expression; + expr.print(output); + var prop = self.property; + + if (self.optional) output.print("?"); + output.print(".#"); + output.add_mapping(self.end); + output.print_name(prop); + }); + DEFPRINT(AST_Sub, function(self, output) { + self.expression.print(output); + if (self.optional) output.print("?."); + output.print("["); + self.property.print(output); + output.print("]"); + }); + DEFPRINT(AST_Chain, function(self, output) { + self.expression.print(output); + }); + DEFPRINT(AST_UnaryPrefix, function(self, output) { + var op = self.operator; + if (op === "--" && output.last().endsWith("!")) { + // avoid printing " + output.print(" "); + } else { + // the space is optional depending on "beautify" + output.space(); + } + output.print(op); + output.space(); + self.right.print(output); + }); + DEFPRINT(AST_Conditional, function(self, output) { + self.condition.print(output); + output.space(); + output.print("?"); + output.space(); + self.consequent.print(output); + output.space(); + output.colon(); + self.alternative.print(output); + }); + + /* -----[ literals ]----- */ + DEFPRINT(AST_Array, function(self, output) { + output.with_square(function() { + var a = self.elements, len = a.length; + if (len > 0) output.space(); + a.forEach(function(exp, i) { + if (i) output.comma(); + exp.print(output); + // If the final element is a hole, we need to make sure it + // doesn't look like a trailing comma, by inserting an actual + // trailing comma. + if (i === len - 1 && exp instanceof AST_Hole) + output.comma(); + }); + if (len > 0) output.space(); + }); + }); + DEFPRINT(AST_Object, function(self, output) { + if (self.properties.length > 0) output.with_block(function() { + self.properties.forEach(function(prop, i) { + if (i) { + output.print(","); + output.newline(); + } + output.indent(); + prop.print(output); + }); + output.newline(); + }); + else print_braced_empty(self, output); + }); + DEFPRINT(AST_Class, function(self, output) { + output.print("class"); + output.space(); + if (self.name) { + self.name.print(output); + output.space(); + } + if (self.extends) { + var parens = ( + !(self.extends instanceof AST_SymbolRef) + && !(self.extends instanceof AST_PropAccess) + && !(self.extends instanceof AST_ClassExpression) + && !(self.extends instanceof AST_Function) + ); + output.print("extends"); + if (parens) { + output.print("("); + } else { + output.space(); + } + self.extends.print(output); + if (parens) { + output.print(")"); + } else { + output.space(); + } + } + if (self.properties.length > 0) output.with_block(function() { + self.properties.forEach(function(prop, i) { + if (i) { + output.newline(); + } + output.indent(); + prop.print(output); + }); + output.newline(); + }); + else output.print("{}"); + }); + DEFPRINT(AST_NewTarget, function(self, output) { + output.print("new.target"); + }); + + /** Prints a prop name. Returns whether it can be used as a shorthand. */ + function print_property_name(key, quote, output) { + if (output.option("quote_keys")) { + output.print_string(key); + return false; + } + if ("" + +key == key && key >= 0) { + if (output.option("keep_numbers")) { + output.print(key); + return false; + } + output.print(make_num(key)); + return false; + } + var print_string = ALL_RESERVED_WORDS.has(key) + ? output.option("ie8") + : ( + output.option("ecma") < 2015 || output.option("safari10") + ? !is_basic_identifier_string(key) + : !is_identifier_string(key, true) + ); + if (print_string || (quote && output.option("keep_quoted_props"))) { + output.print_string(key, quote); + return false; + } + output.print_name(key); + return true; + } + + DEFPRINT(AST_ObjectKeyVal, function(self, output) { + function get_name(self) { + var def = self.definition(); + return def ? def.mangled_name || def.name : self.name; + } + + const try_shorthand = output.option("shorthand") && !(self.key instanceof AST_Node); + if ( + try_shorthand + && self.value instanceof AST_Symbol + && get_name(self.value) === self.key + && !ALL_RESERVED_WORDS.has(self.key) + ) { + const was_shorthand = print_property_name(self.key, self.quote, output); + if (!was_shorthand) { + output.colon(); + self.value.print(output); + } + } else if ( + try_shorthand + && self.value instanceof AST_DefaultAssign + && self.value.left instanceof AST_Symbol + && get_name(self.value.left) === self.key + ) { + const was_shorthand = print_property_name(self.key, self.quote, output); + if (!was_shorthand) { + output.colon(); + self.value.left.print(output); + } + output.space(); + output.print("="); + output.space(); + self.value.right.print(output); + } else { + if (!(self.key instanceof AST_Node)) { + print_property_name(self.key, self.quote, output); + } else { + output.with_square(function() { + self.key.print(output); + }); + } + output.colon(); + self.value.print(output); + } + }); + DEFPRINT(AST_ClassPrivateProperty, (self, output) => { + if (self.static) { + output.print("static"); + output.space(); + } + + output.print("#"); + + print_property_name(self.key.name, self.quote, output); + + if (self.value) { + output.print("="); + self.value.print(output); + } + + output.semicolon(); + }); + DEFPRINT(AST_ClassProperty, (self, output) => { + if (self.static) { + output.print("static"); + output.space(); + } + + if (self.key instanceof AST_SymbolClassProperty) { + print_property_name(self.key.name, self.quote, output); + } else { + output.print("["); + self.key.print(output); + output.print("]"); + } + + if (self.value) { + output.print("="); + self.value.print(output); + } + + output.semicolon(); + }); + AST_ObjectProperty.DEFMETHOD("_print_getter_setter", function(type, is_private, output) { + var self = this; + if (self.static) { + output.print("static"); + output.space(); + } + if (type) { + output.print(type); + output.space(); + } + if (self.key instanceof AST_SymbolMethod) { + if (is_private) output.print("#"); + print_property_name(self.key.name, self.quote, output); + self.key.add_source_map(output); + } else { + output.with_square(function() { + self.key.print(output); + }); + } + self.value._do_print(output, true); + }); + DEFPRINT(AST_ObjectSetter, function(self, output) { + self._print_getter_setter("set", false, output); + }); + DEFPRINT(AST_ObjectGetter, function(self, output) { + self._print_getter_setter("get", false, output); + }); + DEFPRINT(AST_PrivateSetter, function(self, output) { + self._print_getter_setter("set", true, output); + }); + DEFPRINT(AST_PrivateGetter, function(self, output) { + self._print_getter_setter("get", true, output); + }); + DEFPRINT(AST_PrivateMethod, function(self, output) { + var type; + if (self.is_generator && self.async) { + type = "async*"; + } else if (self.is_generator) { + type = "*"; + } else if (self.async) { + type = "async"; + } + self._print_getter_setter(type, true, output); + }); + DEFPRINT(AST_PrivateIn, function(self, output) { + self.key.print(output); + output.space(); + output.print("in"); + output.space(); + self.value.print(output); + }); + DEFPRINT(AST_SymbolPrivateProperty, function(self, output) { + output.print("#" + self.name); + }); + DEFPRINT(AST_ConciseMethod, function(self, output) { + var type; + if (self.is_generator && self.async) { + type = "async*"; + } else if (self.is_generator) { + type = "*"; + } else if (self.async) { + type = "async"; + } + self._print_getter_setter(type, false, output); + }); + DEFPRINT(AST_ClassStaticBlock, function (self, output) { + output.print("static"); + output.space(); + print_braced(self, output); + }); + AST_Symbol.DEFMETHOD("_do_print", function(output) { + var def = this.definition(); + output.print_name(def ? def.mangled_name || def.name : this.name); + }); + DEFPRINT(AST_Symbol, function (self, output) { + self._do_print(output); + }); + DEFPRINT(AST_Hole, noop); + DEFPRINT(AST_This, function(self, output) { + output.print("this"); + }); + DEFPRINT(AST_Super, function(self, output) { + output.print("super"); + }); + DEFPRINT(AST_Constant, function(self, output) { + output.print(self.getValue()); + }); + DEFPRINT(AST_String, function(self, output) { + output.print_string(self.getValue(), self.quote, output.in_directive); + }); + DEFPRINT(AST_Number, function(self, output) { + if ((output.option("keep_numbers") || output.use_asm) && self.raw) { + output.print(self.raw); + } else { + output.print(make_num(self.getValue())); + } + }); + DEFPRINT(AST_BigInt, function(self, output) { + output.print(self.getValue() + "n"); + }); + + const r_slash_script = /(<\s*\/\s*script)/i; + const r_starts_with_script = /^\s*script/i; + const slash_script_replace = (_, $1) => $1.replace("/", "\\/"); + DEFPRINT(AST_RegExp, function(self, output) { + let { source, flags } = self.getValue(); + source = regexp_source_fix(source); + flags = flags ? sort_regexp_flags(flags) : ""; + + // Avoid outputting end of script tag + source = source.replace(r_slash_script, slash_script_replace); + if (r_starts_with_script.test(source) && output.last().endsWith("<")) { + output.print(" "); + } + + output.print(output.to_utf8(`/${source}/${flags}`, false, true)); + + const parent = output.parent(); + if ( + parent instanceof AST_Binary + && /^\w/.test(parent.operator) + && parent.left === self + ) { + output.print(" "); + } + }); + + /** if, for, while, may or may not have braces surrounding its body */ + function print_maybe_braced_body(stat, output) { + if (output.option("braces")) { + make_block(stat, output); + } else { + if (!stat || stat instanceof AST_EmptyStatement) + output.force_semicolon(); + else if (stat instanceof AST_Let || stat instanceof AST_Const || stat instanceof AST_Class) + make_block(stat, output); + else + stat.print(output); + } + } + + function best_of(a) { + var best = a[0], len = best.length; + for (var i = 1; i < a.length; ++i) { + if (a[i].length < len) { + best = a[i]; + len = best.length; + } + } + return best; + } + + function make_num(num) { + var str = num.toString(10).replace(/^0\./, ".").replace("e+", "e"); + var candidates = [ str ]; + if (Math.floor(num) === num) { + if (num < 0) { + candidates.push("-0x" + (-num).toString(16).toLowerCase()); + } else { + candidates.push("0x" + num.toString(16).toLowerCase()); + } + } + var match, len, digits; + if (match = /^\.0+/.exec(str)) { + len = match[0].length; + digits = str.slice(len); + candidates.push(digits + "e-" + (digits.length + len - 1)); + } else if (match = /0+$/.exec(str)) { + len = match[0].length; + candidates.push(str.slice(0, -len) + "e" + len); + } else if (match = /^(\d)\.(\d+)e(-?\d+)$/.exec(str)) { + candidates.push(match[1] + match[2] + "e" + (match[3] - match[2].length)); + } + return best_of(candidates); + } + + function make_block(stmt, output) { + if (!stmt || stmt instanceof AST_EmptyStatement) + output.print("{}"); + else if (stmt instanceof AST_BlockStatement) + stmt.print(output); + else output.with_block(function() { + output.indent(); + stmt.print(output); + output.newline(); + }); + } + + /* -----[ source map generators ]----- */ + + function DEFMAP(nodetype, generator) { + nodetype.forEach(function(nodetype) { + nodetype.DEFMETHOD("add_source_map", generator); + }); + } + + DEFMAP([ + // We could easily add info for ALL nodes, but it seems to me that + // would be quite wasteful, hence this noop in the base class. + AST_Node, + // since the label symbol will mark it + AST_LabeledStatement, + AST_Toplevel, + ], noop); + + // XXX: I'm not exactly sure if we need it for all of these nodes, + // or if we should add even more. + DEFMAP([ + AST_Array, + AST_BlockStatement, + AST_Catch, + AST_Class, + AST_Constant, + AST_Debugger, + AST_Definitions, + AST_Directive, + AST_Finally, + AST_Jump, + AST_Lambda, + AST_New, + AST_Object, + AST_StatementWithBody, + AST_Symbol, + AST_Switch, + AST_SwitchBranch, + AST_TemplateString, + AST_TemplateSegment, + AST_Try, + ], function(output) { + output.add_mapping(this.start); + }); + + DEFMAP([ + AST_ObjectGetter, + AST_ObjectSetter, + AST_PrivateGetter, + AST_PrivateSetter, + AST_ConciseMethod, + AST_PrivateMethod, + ], function(output) { + output.add_mapping(this.start, false /*name handled below*/); + }); + + DEFMAP([ + AST_SymbolMethod, + AST_SymbolPrivateProperty + ], function(output) { + const tok_type = this.end && this.end.type; + if (tok_type === "name" || tok_type === "privatename") { + output.add_mapping(this.end, this.name); + } else { + output.add_mapping(this.end); + } + }); + + DEFMAP([ AST_ObjectProperty ], function(output) { + output.add_mapping(this.start, this.key); + }); +})(); + +const shallow_cmp = (node1, node2) => { + return ( + node1 === null && node2 === null + || node1.TYPE === node2.TYPE && node1.shallow_cmp(node2) + ); +}; + +const equivalent_to = (tree1, tree2) => { + if (!shallow_cmp(tree1, tree2)) return false; + const walk_1_state = [tree1]; + const walk_2_state = [tree2]; + + const walk_1_push = walk_1_state.push.bind(walk_1_state); + const walk_2_push = walk_2_state.push.bind(walk_2_state); + + while (walk_1_state.length && walk_2_state.length) { + const node_1 = walk_1_state.pop(); + const node_2 = walk_2_state.pop(); + + if (!shallow_cmp(node_1, node_2)) return false; + + node_1._children_backwards(walk_1_push); + node_2._children_backwards(walk_2_push); + + if (walk_1_state.length !== walk_2_state.length) { + // Different number of children + return false; + } + } + + return walk_1_state.length == 0 && walk_2_state.length == 0; +}; + +const pass_through = () => true; + +AST_Node.prototype.shallow_cmp = function () { + throw new Error("did not find a shallow_cmp function for " + this.constructor.name); +}; + +AST_Debugger.prototype.shallow_cmp = pass_through; + +AST_Directive.prototype.shallow_cmp = function(other) { + return this.value === other.value; +}; + +AST_SimpleStatement.prototype.shallow_cmp = pass_through; + +AST_Block.prototype.shallow_cmp = pass_through; + +AST_EmptyStatement.prototype.shallow_cmp = pass_through; + +AST_LabeledStatement.prototype.shallow_cmp = function(other) { + return this.label.name === other.label.name; +}; + +AST_Do.prototype.shallow_cmp = pass_through; + +AST_While.prototype.shallow_cmp = pass_through; + +AST_For.prototype.shallow_cmp = function(other) { + return (this.init == null ? other.init == null : this.init === other.init) && (this.condition == null ? other.condition == null : this.condition === other.condition) && (this.step == null ? other.step == null : this.step === other.step); +}; + +AST_ForIn.prototype.shallow_cmp = pass_through; + +AST_ForOf.prototype.shallow_cmp = pass_through; + +AST_With.prototype.shallow_cmp = pass_through; + +AST_Toplevel.prototype.shallow_cmp = pass_through; + +AST_Expansion.prototype.shallow_cmp = pass_through; + +AST_Lambda.prototype.shallow_cmp = function(other) { + return this.is_generator === other.is_generator && this.async === other.async; +}; + +AST_Destructuring.prototype.shallow_cmp = function(other) { + return this.is_array === other.is_array; +}; + +AST_PrefixedTemplateString.prototype.shallow_cmp = pass_through; + +AST_TemplateString.prototype.shallow_cmp = pass_through; + +AST_TemplateSegment.prototype.shallow_cmp = function(other) { + return this.value === other.value; +}; + +AST_Jump.prototype.shallow_cmp = pass_through; + +AST_LoopControl.prototype.shallow_cmp = pass_through; + +AST_Await.prototype.shallow_cmp = pass_through; + +AST_Yield.prototype.shallow_cmp = function(other) { + return this.is_star === other.is_star; +}; + +AST_If.prototype.shallow_cmp = function(other) { + return this.alternative == null ? other.alternative == null : this.alternative === other.alternative; +}; + +AST_Switch.prototype.shallow_cmp = pass_through; + +AST_SwitchBranch.prototype.shallow_cmp = pass_through; + +AST_Try.prototype.shallow_cmp = function(other) { + return (this.body === other.body) && (this.bcatch == null ? other.bcatch == null : this.bcatch === other.bcatch) && (this.bfinally == null ? other.bfinally == null : this.bfinally === other.bfinally); +}; + +AST_Catch.prototype.shallow_cmp = function(other) { + return this.argname == null ? other.argname == null : this.argname === other.argname; +}; + +AST_Finally.prototype.shallow_cmp = pass_through; + +AST_Definitions.prototype.shallow_cmp = pass_through; + +AST_VarDef.prototype.shallow_cmp = function(other) { + return this.value == null ? other.value == null : this.value === other.value; +}; + +AST_NameMapping.prototype.shallow_cmp = pass_through; + +AST_Import.prototype.shallow_cmp = function(other) { + return (this.imported_name == null ? other.imported_name == null : this.imported_name === other.imported_name) && (this.imported_names == null ? other.imported_names == null : this.imported_names === other.imported_names); +}; + +AST_ImportMeta.prototype.shallow_cmp = pass_through; + +AST_Export.prototype.shallow_cmp = function(other) { + return (this.exported_definition == null ? other.exported_definition == null : this.exported_definition === other.exported_definition) && (this.exported_value == null ? other.exported_value == null : this.exported_value === other.exported_value) && (this.exported_names == null ? other.exported_names == null : this.exported_names === other.exported_names) && this.module_name === other.module_name && this.is_default === other.is_default; +}; + +AST_Call.prototype.shallow_cmp = pass_through; + +AST_Sequence.prototype.shallow_cmp = pass_through; + +AST_PropAccess.prototype.shallow_cmp = pass_through; + +AST_Chain.prototype.shallow_cmp = pass_through; + +AST_Dot.prototype.shallow_cmp = function(other) { + return this.property === other.property; +}; + +AST_DotHash.prototype.shallow_cmp = function(other) { + return this.property === other.property; +}; + +AST_Unary.prototype.shallow_cmp = function(other) { + return this.operator === other.operator; +}; + +AST_Binary.prototype.shallow_cmp = function(other) { + return this.operator === other.operator; +}; + +AST_Conditional.prototype.shallow_cmp = pass_through; + +AST_Array.prototype.shallow_cmp = pass_through; + +AST_Object.prototype.shallow_cmp = pass_through; + +AST_ObjectProperty.prototype.shallow_cmp = pass_through; + +AST_ObjectKeyVal.prototype.shallow_cmp = function(other) { + return this.key === other.key; +}; + +AST_ObjectSetter.prototype.shallow_cmp = function(other) { + return this.static === other.static; +}; + +AST_ObjectGetter.prototype.shallow_cmp = function(other) { + return this.static === other.static; +}; + +AST_ConciseMethod.prototype.shallow_cmp = function(other) { + return this.static === other.static && this.is_generator === other.is_generator && this.async === other.async; +}; + +AST_Class.prototype.shallow_cmp = function(other) { + return (this.name == null ? other.name == null : this.name === other.name) && (this.extends == null ? other.extends == null : this.extends === other.extends); +}; + +AST_ClassProperty.prototype.shallow_cmp = function(other) { + return this.static === other.static; +}; + +AST_Symbol.prototype.shallow_cmp = function(other) { + return this.name === other.name; +}; + +AST_NewTarget.prototype.shallow_cmp = pass_through; + +AST_This.prototype.shallow_cmp = pass_through; + +AST_Super.prototype.shallow_cmp = pass_through; + +AST_String.prototype.shallow_cmp = function(other) { + return this.value === other.value; +}; + +AST_Number.prototype.shallow_cmp = function(other) { + return this.value === other.value; +}; + +AST_BigInt.prototype.shallow_cmp = function(other) { + return this.value === other.value; +}; + +AST_RegExp.prototype.shallow_cmp = function (other) { + return ( + this.value.flags === other.value.flags + && this.value.source === other.value.source + ); +}; + +AST_Atom.prototype.shallow_cmp = pass_through; + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +const MASK_EXPORT_DONT_MANGLE = 1 << 0; +const MASK_EXPORT_WANT_MANGLE = 1 << 1; + +let function_defs = null; +let unmangleable_names = null; +/** + * When defined, there is a function declaration somewhere that's inside of a block. + * See https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-block-level-function-declarations-web-legacy-compatibility-semantics +*/ +let scopes_with_block_defuns = null; + +class SymbolDef { + constructor(scope, orig, init) { + this.name = orig.name; + this.orig = [ orig ]; + this.init = init; + this.eliminated = 0; + this.assignments = 0; + this.scope = scope; + this.replaced = 0; + this.global = false; + this.export = 0; + this.mangled_name = null; + this.undeclared = false; + this.id = SymbolDef.next_id++; + this.chained = false; + this.direct_access = false; + this.escaped = 0; + this.recursive_refs = 0; + this.references = []; + this.should_replace = undefined; + this.single_use = false; + this.fixed = false; + Object.seal(this); + } + fixed_value() { + if (!this.fixed || this.fixed instanceof AST_Node) return this.fixed; + return this.fixed(); + } + unmangleable(options) { + if (!options) options = {}; + + if ( + function_defs && + function_defs.has(this.id) && + keep_name(options.keep_fnames, this.orig[0].name) + ) return true; + + return this.global && !options.toplevel + || (this.export & MASK_EXPORT_DONT_MANGLE) + || this.undeclared + || !options.eval && this.scope.pinned() + || (this.orig[0] instanceof AST_SymbolLambda + || this.orig[0] instanceof AST_SymbolDefun) && keep_name(options.keep_fnames, this.orig[0].name) + || this.orig[0] instanceof AST_SymbolMethod + || (this.orig[0] instanceof AST_SymbolClass + || this.orig[0] instanceof AST_SymbolDefClass) && keep_name(options.keep_classnames, this.orig[0].name); + } + mangle(options) { + const cache = options.cache && options.cache.props; + if (this.global && cache && cache.has(this.name)) { + this.mangled_name = cache.get(this.name); + } else if (!this.mangled_name && !this.unmangleable(options)) { + var s = this.scope; + var sym = this.orig[0]; + if (options.ie8 && sym instanceof AST_SymbolLambda) + s = s.parent_scope; + const redefinition = redefined_catch_def(this); + this.mangled_name = redefinition + ? redefinition.mangled_name || redefinition.name + : s.next_mangled(options, this); + if (this.global && cache) { + cache.set(this.name, this.mangled_name); + } + } + } +} + +SymbolDef.next_id = 1; + +function redefined_catch_def(def) { + if (def.orig[0] instanceof AST_SymbolCatch + && def.scope.is_block_scope() + ) { + return def.scope.get_defun_scope().variables.get(def.name); + } +} + +AST_Scope.DEFMETHOD("figure_out_scope", function(options, { parent_scope = null, toplevel = this } = {}) { + options = defaults(options, { + cache: null, + ie8: false, + safari10: false, + module: false, + }); + + if (!(toplevel instanceof AST_Toplevel)) { + throw new Error("Invalid toplevel scope"); + } + + // pass 1: setup scope chaining and handle definitions + var scope = this.parent_scope = parent_scope; + var labels = new Map(); + var defun = null; + var in_destructuring = null; + var for_scopes = []; + var tw = new TreeWalker((node, descend) => { + if (node.is_block_scope()) { + const save_scope = scope; + node.block_scope = scope = new AST_Scope(node); + scope._block_scope = true; + scope.init_scope_vars(save_scope); + scope.uses_with = save_scope.uses_with; + scope.uses_eval = save_scope.uses_eval; + + if (options.safari10) { + if (node instanceof AST_For || node instanceof AST_ForIn || node instanceof AST_ForOf) { + for_scopes.push(scope); + } + } + + if (node instanceof AST_Switch) { + // XXX: HACK! Ensure the switch expression gets the correct scope (the parent scope) and the body gets the contained scope + // AST_Switch has a scope within the body, but it itself "is a block scope" + // This means the switched expression has to belong to the outer scope + // while the body inside belongs to the switch itself. + // This is pretty nasty and warrants an AST change + const the_block_scope = scope; + scope = save_scope; + node.expression.walk(tw); + scope = the_block_scope; + for (let i = 0; i < node.body.length; i++) { + node.body[i].walk(tw); + } + } else { + descend(); + } + scope = save_scope; + return true; + } + if (node instanceof AST_Destructuring) { + const save_destructuring = in_destructuring; + in_destructuring = node; + descend(); + in_destructuring = save_destructuring; + return true; + } + if (node instanceof AST_Scope) { + node.init_scope_vars(scope); + var save_scope = scope; + var save_defun = defun; + var save_labels = labels; + defun = scope = node; + labels = new Map(); + descend(); + scope = save_scope; + defun = save_defun; + labels = save_labels; + return true; // don't descend again in TreeWalker + } + if (node instanceof AST_LabeledStatement) { + var l = node.label; + if (labels.has(l.name)) { + throw new Error(string_template("Label {name} defined twice", l)); + } + labels.set(l.name, l); + descend(); + labels.delete(l.name); + return true; // no descend again + } + if (node instanceof AST_With) { + for (var s = scope; s; s = s.parent_scope) + s.uses_with = true; + return; + } + if (node instanceof AST_Symbol) { + node.scope = scope; + } + if (node instanceof AST_Label) { + node.thedef = node; + node.references = []; + } + if (node instanceof AST_SymbolLambda) { + defun.def_function(node, node.name == "arguments" ? undefined : defun); + } else if (node instanceof AST_SymbolDefun) { + // Careful here, the scope where this should be defined is + // the parent scope. The reason is that we enter a new + // scope when we encounter the AST_Defun node (which is + // instanceof AST_Scope) but we get to the symbol a bit + // later. + const closest_scope = defun.parent_scope; + + // In strict mode, function definitions are block-scoped + node.scope = tw.directives["use strict"] + ? closest_scope + : closest_scope.get_defun_scope(); + + mark_export(node.scope.def_function(node, defun), 1); + } else if (node instanceof AST_SymbolClass) { + mark_export(defun.def_variable(node, defun), 1); + } else if (node instanceof AST_SymbolImport) { + scope.def_variable(node); + } else if (node instanceof AST_SymbolDefClass) { + // This deals with the name of the class being available + // inside the class. + mark_export((node.scope = defun.parent_scope).def_function(node, defun), 1); + } else if ( + node instanceof AST_SymbolVar + || node instanceof AST_SymbolLet + || node instanceof AST_SymbolConst + || node instanceof AST_SymbolCatch + ) { + var def; + if (node instanceof AST_SymbolBlockDeclaration) { + def = scope.def_variable(node, null); + } else { + def = defun.def_variable(node, node.TYPE == "SymbolVar" ? null : undefined); + } + if (!def.orig.every((sym) => { + if (sym === node) return true; + if (node instanceof AST_SymbolBlockDeclaration) { + return sym instanceof AST_SymbolLambda; + } + return !(sym instanceof AST_SymbolLet || sym instanceof AST_SymbolConst); + })) { + js_error( + `"${node.name}" is redeclared`, + node.start.file, + node.start.line, + node.start.col, + node.start.pos + ); + } + if (!(node instanceof AST_SymbolFunarg)) mark_export(def, 2); + if (defun !== scope) { + node.mark_enclosed(); + var def = scope.find_variable(node); + if (node.thedef !== def) { + node.thedef = def; + node.reference(); + } + } + } else if (node instanceof AST_LabelRef) { + var sym = labels.get(node.name); + if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", { + name: node.name, + line: node.start.line, + col: node.start.col + })); + node.thedef = sym; + } + if (!(scope instanceof AST_Toplevel) && (node instanceof AST_Export || node instanceof AST_Import)) { + js_error( + `"${node.TYPE}" statement may only appear at the top level`, + node.start.file, + node.start.line, + node.start.col, + node.start.pos + ); + } + }); + + if (options.module) { + tw.directives["use strict"] = true; + } + + this.walk(tw); + + function mark_export(def, level) { + if (in_destructuring) { + var i = 0; + do { + level++; + } while (tw.parent(i++) !== in_destructuring); + } + var node = tw.parent(level); + if (def.export = node instanceof AST_Export ? MASK_EXPORT_DONT_MANGLE : 0) { + var exported = node.exported_definition; + if ((exported instanceof AST_Defun || exported instanceof AST_DefClass) && node.is_default) { + def.export = MASK_EXPORT_WANT_MANGLE; + } + } + } + + // pass 2: find back references and eval + const is_toplevel = this instanceof AST_Toplevel; + if (is_toplevel) { + this.globals = new Map(); + } + + var tw = new TreeWalker(node => { + if (node instanceof AST_LoopControl && node.label) { + node.label.thedef.references.push(node); + return true; + } + if (node instanceof AST_SymbolRef) { + var name = node.name; + if (name == "eval" && tw.parent() instanceof AST_Call) { + for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) { + s.uses_eval = true; + } + } + var sym; + if (tw.parent() instanceof AST_NameMapping && tw.parent(1).module_name + || !(sym = node.scope.find_variable(name))) { + + sym = toplevel.def_global(node); + if (node instanceof AST_SymbolExport) sym.export = MASK_EXPORT_DONT_MANGLE; + } else if (sym.scope instanceof AST_Lambda && name == "arguments") { + sym.scope.get_defun_scope().uses_arguments = true; + } + node.thedef = sym; + node.reference(); + if (node.scope.is_block_scope() + && !(sym.orig[0] instanceof AST_SymbolBlockDeclaration)) { + node.scope = node.scope.get_defun_scope(); + } + return true; + } + // ensure mangling works if catch reuses a scope variable + var def; + if (node instanceof AST_SymbolCatch && (def = redefined_catch_def(node.definition()))) { + var s = node.scope; + while (s) { + push_uniq(s.enclosed, def); + if (s === def.scope) break; + s = s.parent_scope; + } + } + }); + this.walk(tw); + + // pass 3: work around IE8 and Safari catch scope bugs + if (options.ie8 || options.safari10) { + walk(this, node => { + if (node instanceof AST_SymbolCatch) { + var name = node.name; + var refs = node.thedef.references; + var scope = node.scope.get_defun_scope(); + var def = scope.find_variable(name) + || toplevel.globals.get(name) + || scope.def_variable(node); + refs.forEach(function(ref) { + ref.thedef = def; + ref.reference(); + }); + node.thedef = def; + node.reference(); + return true; + } + }); + } + + // pass 4: add symbol definitions to loop scopes + // Safari/Webkit bug workaround - loop init let variable shadowing argument. + // https://github.com/mishoo/UglifyJS2/issues/1753 + // https://bugs.webkit.org/show_bug.cgi?id=171041 + if (options.safari10) { + for (const scope of for_scopes) { + scope.parent_scope.variables.forEach(function(def) { + push_uniq(scope.enclosed, def); + }); + } + } +}); + +AST_Toplevel.DEFMETHOD("def_global", function(node) { + var globals = this.globals, name = node.name; + if (globals.has(name)) { + return globals.get(name); + } else { + var g = new SymbolDef(this, node); + g.undeclared = true; + g.global = true; + globals.set(name, g); + return g; + } +}); + +AST_Scope.DEFMETHOD("init_scope_vars", function(parent_scope) { + this.variables = new Map(); // map name to AST_SymbolVar (variables defined in this scope; includes functions) + this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement + this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval` + this.parent_scope = parent_scope; // the parent scope + this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes + this.cname = -1; // the current index for mangling functions/variables +}); + +AST_Scope.DEFMETHOD("conflicting_def", function (name) { + return ( + this.enclosed.find(def => def.name === name) + || this.variables.has(name) + || (this.parent_scope && this.parent_scope.conflicting_def(name)) + ); +}); + +AST_Scope.DEFMETHOD("conflicting_def_shallow", function (name) { + return ( + this.enclosed.find(def => def.name === name) + || this.variables.has(name) + ); +}); + +AST_Scope.DEFMETHOD("add_child_scope", function (scope) { + // `scope` is going to be moved into `this` right now. + // Update the required scopes' information + + if (scope.parent_scope === this) return; + + scope.parent_scope = this; + + // Propagate to this.uses_arguments from arrow functions + if ((scope instanceof AST_Arrow) && !this.uses_arguments) { + this.uses_arguments = walk(scope, node => { + if ( + node instanceof AST_SymbolRef + && node.scope instanceof AST_Lambda + && node.name === "arguments" + ) { + return walk_abort; + } + + if (node instanceof AST_Lambda && !(node instanceof AST_Arrow)) { + return true; + } + }); + } + + this.uses_with = this.uses_with || scope.uses_with; + this.uses_eval = this.uses_eval || scope.uses_eval; + + const scope_ancestry = (() => { + const ancestry = []; + let cur = this; + do { + ancestry.push(cur); + } while ((cur = cur.parent_scope)); + ancestry.reverse(); + return ancestry; + })(); + + const new_scope_enclosed_set = new Set(scope.enclosed); + const to_enclose = []; + for (const scope_topdown of scope_ancestry) { + to_enclose.forEach(e => push_uniq(scope_topdown.enclosed, e)); + for (const def of scope_topdown.variables.values()) { + if (new_scope_enclosed_set.has(def)) { + push_uniq(to_enclose, def); + push_uniq(scope_topdown.enclosed, def); + } + } + } +}); + +function find_scopes_visible_from(scopes) { + const found_scopes = new Set(); + + for (const scope of new Set(scopes)) { + (function bubble_up(scope) { + if (scope == null || found_scopes.has(scope)) return; + + found_scopes.add(scope); + + bubble_up(scope.parent_scope); + })(scope); + } + + return [...found_scopes]; +} + +// Creates a symbol during compression +AST_Scope.DEFMETHOD("create_symbol", function(SymClass, { + source, + tentative_name, + scope, + conflict_scopes = [scope], + init = null +} = {}) { + let symbol_name; + + conflict_scopes = find_scopes_visible_from(conflict_scopes); + + if (tentative_name) { + // Implement hygiene (no new names are conflicting with existing names) + tentative_name = + symbol_name = + tentative_name.replace(/(?:^[^a-z_$]|[^a-z0-9_$])/ig, "_"); + + let i = 0; + while (conflict_scopes.find(s => s.conflicting_def_shallow(symbol_name))) { + symbol_name = tentative_name + "$" + i++; + } + } + + if (!symbol_name) { + throw new Error("No symbol name could be generated in create_symbol()"); + } + + const symbol = make_node(SymClass, source, { + name: symbol_name, + scope + }); + + this.def_variable(symbol, init || null); + + symbol.mark_enclosed(); + + return symbol; +}); + + +AST_Node.DEFMETHOD("is_block_scope", return_false); +AST_Class.DEFMETHOD("is_block_scope", return_false); +AST_Lambda.DEFMETHOD("is_block_scope", return_false); +AST_Toplevel.DEFMETHOD("is_block_scope", return_false); +AST_SwitchBranch.DEFMETHOD("is_block_scope", return_false); +AST_Block.DEFMETHOD("is_block_scope", return_true); +AST_Scope.DEFMETHOD("is_block_scope", function () { + return this._block_scope || false; +}); +AST_IterationStatement.DEFMETHOD("is_block_scope", return_true); + +AST_Lambda.DEFMETHOD("init_scope_vars", function() { + AST_Scope.prototype.init_scope_vars.apply(this, arguments); + this.uses_arguments = false; + this.def_variable(new AST_SymbolFunarg({ + name: "arguments", + start: this.start, + end: this.end + })); +}); + +AST_Arrow.DEFMETHOD("init_scope_vars", function() { + AST_Scope.prototype.init_scope_vars.apply(this, arguments); + this.uses_arguments = false; +}); + +AST_Symbol.DEFMETHOD("mark_enclosed", function() { + var def = this.definition(); + var s = this.scope; + while (s) { + push_uniq(s.enclosed, def); + if (s === def.scope) break; + s = s.parent_scope; + } +}); + +AST_Symbol.DEFMETHOD("reference", function() { + this.definition().references.push(this); + this.mark_enclosed(); +}); + +AST_Scope.DEFMETHOD("find_variable", function(name) { + if (name instanceof AST_Symbol) name = name.name; + return this.variables.get(name) + || (this.parent_scope && this.parent_scope.find_variable(name)); +}); + +AST_Scope.DEFMETHOD("def_function", function(symbol, init) { + var def = this.def_variable(symbol, init); + if (!def.init || def.init instanceof AST_Defun) def.init = init; + return def; +}); + +AST_Scope.DEFMETHOD("def_variable", function(symbol, init) { + var def = this.variables.get(symbol.name); + if (def) { + def.orig.push(symbol); + if (def.init && (def.scope !== symbol.scope || def.init instanceof AST_Function)) { + def.init = init; + } + } else { + def = new SymbolDef(this, symbol, init); + this.variables.set(symbol.name, def); + def.global = !this.parent_scope; + } + return symbol.thedef = def; +}); + +function next_mangled(scope, options) { + let defun_scope; + if ( + scopes_with_block_defuns + && (defun_scope = scope.get_defun_scope()) + && scopes_with_block_defuns.has(defun_scope) + ) { + scope = defun_scope; + } + + var ext = scope.enclosed; + var nth_identifier = options.nth_identifier; + out: while (true) { + var m = nth_identifier.get(++scope.cname); + if (ALL_RESERVED_WORDS.has(m)) continue; // skip over "do" + + // https://github.com/mishoo/UglifyJS2/issues/242 -- do not + // shadow a name reserved from mangling. + if (options.reserved.has(m)) continue; + + // Functions with short names might collide with base54 output + // and therefore cause collisions when keep_fnames is true. + if (unmangleable_names && unmangleable_names.has(m)) continue out; + + // we must ensure that the mangled name does not shadow a name + // from some parent scope that is referenced in this or in + // inner scopes. + for (let i = ext.length; --i >= 0;) { + const def = ext[i]; + const name = def.mangled_name || (def.unmangleable(options) && def.name); + if (m == name) continue out; + } + return m; + } +} + +AST_Scope.DEFMETHOD("next_mangled", function(options) { + return next_mangled(this, options); +}); + +AST_Toplevel.DEFMETHOD("next_mangled", function(options) { + let name; + const mangled_names = this.mangled_names; + do { + name = next_mangled(this, options); + } while (mangled_names.has(name)); + return name; +}); + +AST_Function.DEFMETHOD("next_mangled", function(options, def) { + // #179, #326 + // in Safari strict mode, something like (function x(x){...}) is a syntax error; + // a function expression's argument cannot shadow the function expression's name + + var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition(); + + // the function's mangled_name is null when keep_fnames is true + var tricky_name = tricky_def ? tricky_def.mangled_name || tricky_def.name : null; + + while (true) { + var name = next_mangled(this, options); + if (!tricky_name || tricky_name != name) + return name; + } +}); + +AST_Symbol.DEFMETHOD("unmangleable", function(options) { + var def = this.definition(); + return !def || def.unmangleable(options); +}); + +// labels are always mangleable +AST_Label.DEFMETHOD("unmangleable", return_false); + +AST_Symbol.DEFMETHOD("unreferenced", function() { + return !this.definition().references.length && !this.scope.pinned(); +}); + +AST_Symbol.DEFMETHOD("definition", function() { + return this.thedef; +}); + +AST_Symbol.DEFMETHOD("global", function() { + return this.thedef.global; +}); + +/** + * Format the mangler options (if any) into their appropriate types + */ +function format_mangler_options(options) { + options = defaults(options, { + eval : false, + nth_identifier : base54, + ie8 : false, + keep_classnames: false, + keep_fnames : false, + module : false, + reserved : [], + toplevel : false, + }); + if (options.module) options.toplevel = true; + if (!Array.isArray(options.reserved) + && !(options.reserved instanceof Set) + ) { + options.reserved = []; + } + options.reserved = new Set(options.reserved); + // Never mangle arguments + options.reserved.add("arguments"); + return options; +} + +AST_Toplevel.DEFMETHOD("mangle_names", function(options) { + options = format_mangler_options(options); + var nth_identifier = options.nth_identifier; + + // We only need to mangle declaration nodes. Special logic wired + // into the code generator will display the mangled name if it's + // present (and for AST_SymbolRef-s it'll use the mangled name of + // the AST_SymbolDeclaration that it points to). + var lname = -1; + var to_mangle = []; + + if (options.keep_fnames) { + function_defs = new Set(); + } + + const mangled_names = this.mangled_names = new Set(); + unmangleable_names = new Set(); + + if (options.cache) { + this.globals.forEach(collect); + if (options.cache.props) { + options.cache.props.forEach(function(mangled_name) { + mangled_names.add(mangled_name); + }); + } + } + + var tw = new TreeWalker(function(node, descend) { + if (node instanceof AST_LabeledStatement) { + // lname is incremented when we get to the AST_Label + var save_nesting = lname; + descend(); + lname = save_nesting; + return true; // don't descend again in TreeWalker + } + if ( + node instanceof AST_Defun + && !(tw.parent() instanceof AST_Scope) + ) { + scopes_with_block_defuns = scopes_with_block_defuns || new Set(); + scopes_with_block_defuns.add(node.parent_scope.get_defun_scope()); + } + if (node instanceof AST_Scope) { + node.variables.forEach(collect); + return; + } + if (node.is_block_scope()) { + node.block_scope.variables.forEach(collect); + return; + } + if ( + function_defs + && node instanceof AST_VarDef + && node.value instanceof AST_Lambda + && !node.value.name + && keep_name(options.keep_fnames, node.name.name) + ) { + function_defs.add(node.name.definition().id); + return; + } + if (node instanceof AST_Label) { + let name; + do { + name = nth_identifier.get(++lname); + } while (ALL_RESERVED_WORDS.has(name)); + node.mangled_name = name; + return true; + } + if (!(options.ie8 || options.safari10) && node instanceof AST_SymbolCatch) { + to_mangle.push(node.definition()); + return; + } + }); + + this.walk(tw); + + if (options.keep_fnames || options.keep_classnames) { + // Collect a set of short names which are unmangleable, + // for use in avoiding collisions in next_mangled. + to_mangle.forEach(def => { + if (def.name.length < 6 && def.unmangleable(options)) { + unmangleable_names.add(def.name); + } + }); + } + + to_mangle.forEach(def => { def.mangle(options); }); + + function_defs = null; + unmangleable_names = null; + scopes_with_block_defuns = null; + + function collect(symbol) { + if (symbol.export & MASK_EXPORT_DONT_MANGLE) { + unmangleable_names.add(symbol.name); + } else if (!options.reserved.has(symbol.name)) { + to_mangle.push(symbol); + } + } +}); + +AST_Toplevel.DEFMETHOD("find_colliding_names", function(options) { + const cache = options.cache && options.cache.props; + const avoid = new Set(); + options.reserved.forEach(to_avoid); + this.globals.forEach(add_def); + this.walk(new TreeWalker(function(node) { + if (node instanceof AST_Scope) node.variables.forEach(add_def); + if (node instanceof AST_SymbolCatch) add_def(node.definition()); + })); + return avoid; + + function to_avoid(name) { + avoid.add(name); + } + + function add_def(def) { + var name = def.name; + if (def.global && cache && cache.has(name)) name = cache.get(name); + else if (!def.unmangleable(options)) return; + to_avoid(name); + } +}); + +AST_Toplevel.DEFMETHOD("expand_names", function(options) { + options = format_mangler_options(options); + var nth_identifier = options.nth_identifier; + if (nth_identifier.reset && nth_identifier.sort) { + nth_identifier.reset(); + nth_identifier.sort(); + } + var avoid = this.find_colliding_names(options); + var cname = 0; + this.globals.forEach(rename); + this.walk(new TreeWalker(function(node) { + if (node instanceof AST_Scope) node.variables.forEach(rename); + if (node instanceof AST_SymbolCatch) rename(node.definition()); + })); + + function next_name() { + var name; + do { + name = nth_identifier.get(cname++); + } while (avoid.has(name) || ALL_RESERVED_WORDS.has(name)); + return name; + } + + function rename(def) { + if (def.global && options.cache) return; + if (def.unmangleable(options)) return; + if (options.reserved.has(def.name)) return; + const redefinition = redefined_catch_def(def); + const name = def.name = redefinition ? redefinition.name : next_name(); + def.orig.forEach(function(sym) { + sym.name = name; + }); + def.references.forEach(function(sym) { + sym.name = name; + }); + } +}); + +AST_Node.DEFMETHOD("tail_node", return_this); +AST_Sequence.DEFMETHOD("tail_node", function() { + return this.expressions[this.expressions.length - 1]; +}); + +AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options) { + options = format_mangler_options(options); + var nth_identifier = options.nth_identifier; + if (!nth_identifier.reset || !nth_identifier.consider || !nth_identifier.sort) { + // If the identifier mangler is invariant, skip computing character frequency. + return; + } + nth_identifier.reset(); + + try { + AST_Node.prototype.print = function(stream, force_parens) { + this._print(stream, force_parens); + if (this instanceof AST_Symbol && !this.unmangleable(options)) { + nth_identifier.consider(this.name, -1); + } else if (options.properties) { + if (this instanceof AST_DotHash) { + nth_identifier.consider("#" + this.property, -1); + } else if (this instanceof AST_Dot) { + nth_identifier.consider(this.property, -1); + } else if (this instanceof AST_Sub) { + skip_string(this.property); + } + } + }; + nth_identifier.consider(this.print_to_string(), 1); + } finally { + AST_Node.prototype.print = AST_Node.prototype._print; + } + nth_identifier.sort(); + + function skip_string(node) { + if (node instanceof AST_String) { + nth_identifier.consider(node.value, -1); + } else if (node instanceof AST_Conditional) { + skip_string(node.consequent); + skip_string(node.alternative); + } else if (node instanceof AST_Sequence) { + skip_string(node.tail_node()); + } + } +}); + +const base54 = (() => { + const leading = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_".split(""); + const digits = "0123456789".split(""); + let chars; + let frequency; + function reset() { + frequency = new Map(); + leading.forEach(function(ch) { + frequency.set(ch, 0); + }); + digits.forEach(function(ch) { + frequency.set(ch, 0); + }); + } + function consider(str, delta) { + for (var i = str.length; --i >= 0;) { + frequency.set(str[i], frequency.get(str[i]) + delta); + } + } + function compare(a, b) { + return frequency.get(b) - frequency.get(a); + } + function sort() { + chars = mergeSort(leading, compare).concat(mergeSort(digits, compare)); + } + // Ensure this is in a usable initial state. + reset(); + sort(); + function base54(num) { + var ret = "", base = 54; + num++; + do { + num--; + ret += chars[num % base]; + num = Math.floor(num / base); + base = 64; + } while (num > 0); + return ret; + } + + return { + get: base54, + consider, + reset, + sort + }; +})(); + +let mangle_options = undefined; +AST_Node.prototype.size = function (compressor, stack) { + mangle_options = compressor && compressor._mangle_options; + + let size = 0; + walk_parent(this, (node, info) => { + size += node._size(info); + + // Braceless arrow functions have fake "return" statements + if (node instanceof AST_Arrow && node.is_braceless()) { + size += node.body[0].value._size(info); + return true; + } + }, stack || (compressor && compressor.stack)); + + // just to save a bit of memory + mangle_options = undefined; + + return size; +}; + +AST_Node.prototype._size = () => 0; + +AST_Debugger.prototype._size = () => 8; + +AST_Directive.prototype._size = function () { + // TODO string encoding stuff + return 2 + this.value.length; +}; + +/** Count commas/semicolons necessary to show a list of expressions/statements */ +const list_overhead = (array) => array.length && array.length - 1; + +AST_Block.prototype._size = function () { + return 2 + list_overhead(this.body); +}; + +AST_Toplevel.prototype._size = function() { + return list_overhead(this.body); +}; + +AST_EmptyStatement.prototype._size = () => 1; + +AST_LabeledStatement.prototype._size = () => 2; // x: + +AST_Do.prototype._size = () => 9; + +AST_While.prototype._size = () => 7; + +AST_For.prototype._size = () => 8; + +AST_ForIn.prototype._size = () => 8; +// AST_ForOf inherits ^ + +AST_With.prototype._size = () => 6; + +AST_Expansion.prototype._size = () => 3; + +const lambda_modifiers = func => + (func.is_generator ? 1 : 0) + (func.async ? 6 : 0); + +AST_Accessor.prototype._size = function () { + return lambda_modifiers(this) + 4 + list_overhead(this.argnames) + list_overhead(this.body); +}; + +AST_Function.prototype._size = function (info) { + const first = !!first_in_statement(info); + return (first * 2) + lambda_modifiers(this) + 12 + list_overhead(this.argnames) + list_overhead(this.body); +}; + +AST_Defun.prototype._size = function () { + return lambda_modifiers(this) + 13 + list_overhead(this.argnames) + list_overhead(this.body); +}; + +AST_Arrow.prototype._size = function () { + let args_and_arrow = 2 + list_overhead(this.argnames); + + if ( + !( + this.argnames.length === 1 + && this.argnames[0] instanceof AST_Symbol + ) + ) { + args_and_arrow += 2; // parens around the args + } + + const body_overhead = this.is_braceless() ? 0 : list_overhead(this.body) + 2; + + return lambda_modifiers(this) + args_and_arrow + body_overhead; +}; + +AST_Destructuring.prototype._size = () => 2; + +AST_TemplateString.prototype._size = function () { + return 2 + (Math.floor(this.segments.length / 2) * 3); /* "${}" */ +}; + +AST_TemplateSegment.prototype._size = function () { + return this.value.length; +}; + +AST_Return.prototype._size = function () { + return this.value ? 7 : 6; +}; + +AST_Throw.prototype._size = () => 6; + +AST_Break.prototype._size = function () { + return this.label ? 6 : 5; +}; + +AST_Continue.prototype._size = function () { + return this.label ? 9 : 8; +}; + +AST_If.prototype._size = () => 4; + +AST_Switch.prototype._size = function () { + return 8 + list_overhead(this.body); +}; + +AST_Case.prototype._size = function () { + return 5 + list_overhead(this.body); +}; + +AST_Default.prototype._size = function () { + return 8 + list_overhead(this.body); +}; + +AST_Try.prototype._size = () => 3; + +AST_Catch.prototype._size = function () { + let size = 7 + list_overhead(this.body); + if (this.argname) { + size += 2; + } + return size; +}; + +AST_Finally.prototype._size = function () { + return 7 + list_overhead(this.body); +}; + +AST_Var.prototype._size = function () { + return 4 + list_overhead(this.definitions); +}; + +AST_Let.prototype._size = function () { + return 4 + list_overhead(this.definitions); +}; + +AST_Const.prototype._size = function () { + return 6 + list_overhead(this.definitions); +}; + +AST_VarDef.prototype._size = function () { + return this.value ? 1 : 0; +}; + +AST_NameMapping.prototype._size = function () { + // foreign name isn't mangled + return this.name ? 4 : 0; +}; + +AST_Import.prototype._size = function () { + // import + let size = 6; + + if (this.imported_name) size += 1; + + // from + if (this.imported_name || this.imported_names) size += 5; + + // braces, and the commas + if (this.imported_names) { + size += 2 + list_overhead(this.imported_names); + } + + return size; +}; + +AST_ImportMeta.prototype._size = () => 11; + +AST_Export.prototype._size = function () { + let size = 7 + (this.is_default ? 8 : 0); + + if (this.exported_value) { + size += this.exported_value._size(); + } + + if (this.exported_names) { + // Braces and commas + size += 2 + list_overhead(this.exported_names); + } + + if (this.module_name) { + // "from " + size += 5; + } + + return size; +}; + +AST_Call.prototype._size = function () { + if (this.optional) { + return 4 + list_overhead(this.args); + } + return 2 + list_overhead(this.args); +}; + +AST_New.prototype._size = function () { + return 6 + list_overhead(this.args); +}; + +AST_Sequence.prototype._size = function () { + return list_overhead(this.expressions); +}; + +AST_Dot.prototype._size = function () { + if (this.optional) { + return this.property.length + 2; + } + return this.property.length + 1; +}; + +AST_DotHash.prototype._size = function () { + if (this.optional) { + return this.property.length + 3; + } + return this.property.length + 2; +}; + +AST_Sub.prototype._size = function () { + return this.optional ? 4 : 2; +}; + +AST_Unary.prototype._size = function () { + if (this.operator === "typeof") return 7; + if (this.operator === "void") return 5; + return this.operator.length; +}; + +AST_Binary.prototype._size = function (info) { + if (this.operator === "in") return 4; + + let size = this.operator.length; + + if ( + (this.operator === "+" || this.operator === "-") + && this.right instanceof AST_Unary && this.right.operator === this.operator + ) { + // 1+ +a > needs space between the + + size += 1; + } + + if (this.needs_parens(info)) { + size += 2; + } + + return size; +}; + +AST_Conditional.prototype._size = () => 3; + +AST_Array.prototype._size = function () { + return 2 + list_overhead(this.elements); +}; + +AST_Object.prototype._size = function (info) { + let base = 2; + if (first_in_statement(info)) { + base += 2; // parens + } + return base + list_overhead(this.properties); +}; + +/*#__INLINE__*/ +const key_size = key => + typeof key === "string" ? key.length : 0; + +AST_ObjectKeyVal.prototype._size = function () { + return key_size(this.key) + 1; +}; + +/*#__INLINE__*/ +const static_size = is_static => is_static ? 7 : 0; + +AST_ObjectGetter.prototype._size = function () { + return 5 + static_size(this.static) + key_size(this.key); +}; + +AST_ObjectSetter.prototype._size = function () { + return 5 + static_size(this.static) + key_size(this.key); +}; + +AST_ConciseMethod.prototype._size = function () { + return static_size(this.static) + key_size(this.key) + lambda_modifiers(this); +}; + +AST_PrivateMethod.prototype._size = function () { + return AST_ConciseMethod.prototype._size.call(this) + 1; +}; + +AST_PrivateGetter.prototype._size = AST_PrivateSetter.prototype._size = function () { + return AST_ConciseMethod.prototype._size.call(this) + 4; +}; + +AST_PrivateIn.prototype._size = function () { + return 5; // "#", and " in " +}; + +AST_Class.prototype._size = function () { + return ( + (this.name ? 8 : 7) + + (this.extends ? 8 : 0) + ); +}; + +AST_ClassStaticBlock.prototype._size = function () { + // "static{}" + semicolons + return 8 + list_overhead(this.body); +}; + +AST_ClassProperty.prototype._size = function () { + return ( + static_size(this.static) + + (typeof this.key === "string" ? this.key.length + 2 : 0) + + (this.value ? 1 : 0) + ); +}; + +AST_ClassPrivateProperty.prototype._size = function () { + return AST_ClassProperty.prototype._size.call(this) + 1; +}; + +AST_Symbol.prototype._size = function () { + if (!(mangle_options && this.thedef && !this.thedef.unmangleable(mangle_options))) { + return this.name.length; + } else { + return 1; + } +}; + +// TODO take propmangle into account +AST_SymbolClassProperty.prototype._size = function () { + return this.name.length; +}; + +AST_SymbolRef.prototype._size = AST_SymbolDeclaration.prototype._size = function () { + if (this.name === "arguments") return 9; + + return AST_Symbol.prototype._size.call(this); +}; + +AST_NewTarget.prototype._size = () => 10; + +AST_SymbolImportForeign.prototype._size = function () { + return this.name.length; +}; + +AST_SymbolExportForeign.prototype._size = function () { + return this.name.length; +}; + +AST_This.prototype._size = () => 4; + +AST_Super.prototype._size = () => 5; + +AST_String.prototype._size = function () { + return this.value.length + 2; +}; + +AST_Number.prototype._size = function () { + const { value } = this; + if (value === 0) return 1; + if (value > 0 && Math.floor(value) === value) { + return Math.floor(Math.log10(value) + 1); + } + return value.toString().length; +}; + +AST_BigInt.prototype._size = function () { + return this.value.length; +}; + +AST_RegExp.prototype._size = function () { + return this.value.toString().length; +}; + +AST_Null.prototype._size = () => 4; + +AST_NaN.prototype._size = () => 3; + +AST_Undefined.prototype._size = () => 6; // "void 0" + +AST_Hole.prototype._size = () => 0; // comma is taken into account by list_overhead() + +AST_Infinity.prototype._size = () => 8; + +AST_True.prototype._size = () => 4; + +AST_False.prototype._size = () => 5; + +AST_Await.prototype._size = () => 6; + +AST_Yield.prototype._size = () => 6; + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +// bitfield flags to be stored in node.flags. +// These are set and unset during compression, and store information in the node without requiring multiple fields. +const UNUSED = 0b00000001; +const TRUTHY = 0b00000010; +const FALSY = 0b00000100; +const UNDEFINED = 0b00001000; +const INLINED = 0b00010000; + +// Nodes to which values are ever written. Used when keep_assign is part of the unused option string. +const WRITE_ONLY = 0b00100000; + +// information specific to a single compression pass +const SQUEEZED = 0b0000000100000000; +const OPTIMIZED = 0b0000001000000000; +const TOP = 0b0000010000000000; +const CLEAR_BETWEEN_PASSES = SQUEEZED | OPTIMIZED | TOP; + +const has_flag = (node, flag) => node.flags & flag; +const set_flag = (node, flag) => { node.flags |= flag; }; +const clear_flag = (node, flag) => { node.flags &= ~flag; }; + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +function merge_sequence(array, node) { + if (node instanceof AST_Sequence) { + array.push(...node.expressions); + } else { + array.push(node); + } + return array; +} + +function make_sequence(orig, expressions) { + if (expressions.length == 1) return expressions[0]; + if (expressions.length == 0) throw new Error("trying to create a sequence with length zero!"); + return make_node(AST_Sequence, orig, { + expressions: expressions.reduce(merge_sequence, []) + }); +} + +function make_node_from_constant(val, orig) { + switch (typeof val) { + case "string": + return make_node(AST_String, orig, { + value: val + }); + case "number": + if (isNaN(val)) return make_node(AST_NaN, orig); + if (isFinite(val)) { + return 1 / val < 0 ? make_node(AST_UnaryPrefix, orig, { + operator: "-", + expression: make_node(AST_Number, orig, { value: -val }) + }) : make_node(AST_Number, orig, { value: val }); + } + return val < 0 ? make_node(AST_UnaryPrefix, orig, { + operator: "-", + expression: make_node(AST_Infinity, orig) + }) : make_node(AST_Infinity, orig); + case "bigint": + return make_node(AST_BigInt, orig, { value: val.toString() }); + case "boolean": + return make_node(val ? AST_True : AST_False, orig); + case "undefined": + return make_node(AST_Undefined, orig); + default: + if (val === null) { + return make_node(AST_Null, orig, { value: null }); + } + if (val instanceof RegExp) { + return make_node(AST_RegExp, orig, { + value: { + source: regexp_source_fix(val.source), + flags: val.flags + } + }); + } + throw new Error(string_template("Can't handle constant of type: {type}", { + type: typeof val + })); + } +} + +function best_of_expression(ast1, ast2) { + return ast1.size() > ast2.size() ? ast2 : ast1; +} + +function best_of_statement(ast1, ast2) { + return best_of_expression( + make_node(AST_SimpleStatement, ast1, { + body: ast1 + }), + make_node(AST_SimpleStatement, ast2, { + body: ast2 + }) + ).body; +} + +/** Find which node is smaller, and return that */ +function best_of(compressor, ast1, ast2) { + if (first_in_statement(compressor)) { + return best_of_statement(ast1, ast2); + } else { + return best_of_expression(ast1, ast2); + } +} + +/** Simplify an object property's key, if possible */ +function get_simple_key(key) { + if (key instanceof AST_Constant) { + return key.getValue(); + } + if (key instanceof AST_UnaryPrefix + && key.operator == "void" + && key.expression instanceof AST_Constant) { + return; + } + return key; +} + +function read_property(obj, key) { + key = get_simple_key(key); + if (key instanceof AST_Node) return; + + var value; + if (obj instanceof AST_Array) { + var elements = obj.elements; + if (key == "length") return make_node_from_constant(elements.length, obj); + if (typeof key == "number" && key in elements) value = elements[key]; + } else if (obj instanceof AST_Object) { + key = "" + key; + var props = obj.properties; + for (var i = props.length; --i >= 0;) { + var prop = props[i]; + if (!(prop instanceof AST_ObjectKeyVal)) return; + if (!value && props[i].key === key) value = props[i].value; + } + } + + return value instanceof AST_SymbolRef && value.fixed_value() || value; +} + +function has_break_or_continue(loop, parent) { + var found = false; + var tw = new TreeWalker(function(node) { + if (found || node instanceof AST_Scope) return true; + if (node instanceof AST_LoopControl && tw.loopcontrol_target(node) === loop) { + return found = true; + } + }); + if (parent instanceof AST_LabeledStatement) tw.push(parent); + tw.push(loop); + loop.body.walk(tw); + return found; +} + +// we shouldn't compress (1,func)(something) to +// func(something) because that changes the meaning of +// the func (becomes lexical instead of global). +function maintain_this_binding(parent, orig, val) { + if (requires_sequence_to_maintain_binding(parent, orig, val)) { + const zero = make_node(AST_Number, orig, { value: 0 }); + return make_sequence(orig, [ zero, val ]); + } else { + return val; + } +} + +/** Detect (1, x.noThis)(), (0, eval)(), which need sequences */ +function requires_sequence_to_maintain_binding(parent, orig, val) { + return ( + parent instanceof AST_UnaryPrefix && parent.operator == "delete" + || parent instanceof AST_Call && parent.expression === orig + && ( + val instanceof AST_Chain + || val instanceof AST_PropAccess + || val instanceof AST_SymbolRef && val.name == "eval" + ) + ); +} + +function is_func_expr(node) { + return node instanceof AST_Arrow || node instanceof AST_Function; +} + +/** + * Used to determine whether the node can benefit from negation. + * Not the case with arrow functions (you need an extra set of parens). */ +function is_iife_call(node) { + if (node.TYPE != "Call") return false; + return node.expression instanceof AST_Function || is_iife_call(node.expression); +} + +function is_empty(thing) { + if (thing === null) return true; + if (thing instanceof AST_EmptyStatement) return true; + if (thing instanceof AST_BlockStatement) return thing.body.length == 0; + return false; +} + +const identifier_atom = makePredicate("Infinity NaN undefined"); +function is_identifier_atom(node) { + return node instanceof AST_Infinity + || node instanceof AST_NaN + || node instanceof AST_Undefined; +} + +/** Check if this is a SymbolRef node which has one def of a certain AST type */ +function is_ref_of(ref, type) { + if (!(ref instanceof AST_SymbolRef)) return false; + var orig = ref.definition().orig; + for (var i = orig.length; --i >= 0;) { + if (orig[i] instanceof type) return true; + } +} + +/**Can we turn { block contents... } into just the block contents ? + * Not if one of these is inside. + **/ +function can_be_evicted_from_block(node) { + return !( + node instanceof AST_DefClass || + node instanceof AST_Defun || + node instanceof AST_Let || + node instanceof AST_Const || + node instanceof AST_Export || + node instanceof AST_Import + ); +} + +function as_statement_array(thing) { + if (thing === null) return []; + if (thing instanceof AST_BlockStatement) return thing.body; + if (thing instanceof AST_EmptyStatement) return []; + if (thing instanceof AST_Statement) return [ thing ]; + throw new Error("Can't convert thing to statement array"); +} + +function is_reachable(scope_node, defs) { + const find_ref = node => { + if (node instanceof AST_SymbolRef && defs.includes(node.definition())) { + return walk_abort; + } + }; + + return walk_parent(scope_node, (node, info) => { + if (node instanceof AST_Scope && node !== scope_node) { + var parent = info.parent(); + + if ( + parent instanceof AST_Call + && parent.expression === node + // Async/Generators aren't guaranteed to sync evaluate all of + // their body steps, so it's possible they close over the variable. + && !(node.async || node.is_generator) + ) { + return; + } + + if (walk(node, find_ref)) return walk_abort; + + return true; + } + }); +} + +/** Check if a ref refers to the name of a function/class it's defined within */ +function is_recursive_ref(tw, def) { + var node; + for (var i = 0; node = tw.parent(i); i++) { + if (node instanceof AST_Lambda || node instanceof AST_Class) { + var name = node.name; + if (name && name.definition() === def) { + return true; + } + } + } + return false; +} + +// TODO this only works with AST_Defun, shouldn't it work for other ways of defining functions? +function retain_top_func(fn, compressor) { + return compressor.top_retain + && fn instanceof AST_Defun + && has_flag(fn, TOP) + && fn.name + && compressor.top_retain(fn.name.definition()); +} + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +// Lists of native methods, useful for `unsafe` option which assumes they exist. +// Note: Lots of methods and functions are missing here, in case they aren't pure +// or not available in all JS environments. + +function make_nested_lookup(obj) { + const out = new Map(); + for (var key of Object.keys(obj)) { + out.set(key, makePredicate(obj[key])); + } + + const does_have = (global_name, fname) => { + const inner_map = out.get(global_name); + return inner_map != null && inner_map.has(fname); + }; + return does_have; +} + +// Objects which are safe to access without throwing or causing a side effect. +// Usually we'd check the `unsafe` option first but these are way too common for that +const pure_prop_access_globals = new Set([ + "Number", + "String", + "Array", + "Object", + "Function", + "Promise", +]); + +const object_methods = [ + "constructor", + "toString", + "valueOf", +]; + +const is_pure_native_method = make_nested_lookup({ + Array: [ + "at", + "flat", + "includes", + "indexOf", + "join", + "lastIndexOf", + "slice", + ...object_methods, + ], + Boolean: object_methods, + Function: object_methods, + Number: [ + "toExponential", + "toFixed", + "toPrecision", + ...object_methods, + ], + Object: object_methods, + RegExp: [ + "test", + ...object_methods, + ], + String: [ + "at", + "charAt", + "charCodeAt", + "charPointAt", + "concat", + "endsWith", + "fromCharCode", + "fromCodePoint", + "includes", + "indexOf", + "italics", + "lastIndexOf", + "localeCompare", + "match", + "matchAll", + "normalize", + "padStart", + "padEnd", + "repeat", + "replace", + "replaceAll", + "search", + "slice", + "split", + "startsWith", + "substr", + "substring", + "repeat", + "toLocaleLowerCase", + "toLocaleUpperCase", + "toLowerCase", + "toUpperCase", + "trim", + "trimEnd", + "trimStart", + ...object_methods, + ], +}); + +const is_pure_native_fn = make_nested_lookup({ + Array: [ + "isArray", + ], + Math: [ + "abs", + "acos", + "asin", + "atan", + "ceil", + "cos", + "exp", + "floor", + "log", + "round", + "sin", + "sqrt", + "tan", + "atan2", + "pow", + "max", + "min", + ], + Number: [ + "isFinite", + "isNaN", + ], + Object: [ + "create", + "getOwnPropertyDescriptor", + "getOwnPropertyNames", + "getPrototypeOf", + "isExtensible", + "isFrozen", + "isSealed", + "hasOwn", + "keys", + ], + String: [ + "fromCharCode", + ], +}); + +// Known numeric values which come with JS environments +const is_pure_native_value = make_nested_lookup({ + Math: [ + "E", + "LN10", + "LN2", + "LOG2E", + "LOG10E", + "PI", + "SQRT1_2", + "SQRT2", + ], + Number: [ + "MAX_VALUE", + "MIN_VALUE", + "NaN", + "NEGATIVE_INFINITY", + "POSITIVE_INFINITY", + ], +}); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +// Functions and methods to infer certain facts about expressions +// It's not always possible to be 100% sure about something just by static analysis, +// so `true` means yes, and `false` means maybe + +const is_undeclared_ref = (node) => + node instanceof AST_SymbolRef && node.definition().undeclared; + +const bitwise_binop = makePredicate("<<< >> << & | ^ ~"); +const lazy_op = makePredicate("&& || ??"); +const unary_side_effects = makePredicate("delete ++ --"); + +// methods to determine whether an expression has a boolean result type +(function(def_is_boolean) { + const unary_bool = makePredicate("! delete"); + const binary_bool = makePredicate("in instanceof == != === !== < <= >= >"); + def_is_boolean(AST_Node, return_false); + def_is_boolean(AST_UnaryPrefix, function() { + return unary_bool.has(this.operator); + }); + def_is_boolean(AST_Binary, function() { + return binary_bool.has(this.operator) + || lazy_op.has(this.operator) + && this.left.is_boolean() + && this.right.is_boolean(); + }); + def_is_boolean(AST_Conditional, function() { + return this.consequent.is_boolean() && this.alternative.is_boolean(); + }); + def_is_boolean(AST_Assign, function() { + return this.operator == "=" && this.right.is_boolean(); + }); + def_is_boolean(AST_Sequence, function() { + return this.tail_node().is_boolean(); + }); + def_is_boolean(AST_True, return_true); + def_is_boolean(AST_False, return_true); +})(function(node, func) { + node.DEFMETHOD("is_boolean", func); +}); + +// methods to determine if an expression has a numeric result type +(function(def_is_number) { + def_is_number(AST_Node, return_false); + def_is_number(AST_Number, return_true); + const unary = makePredicate("+ - ~ ++ --"); + def_is_number(AST_Unary, function() { + return unary.has(this.operator) && !(this.expression instanceof AST_BigInt); + }); + const numeric_ops = makePredicate("- * / % & | ^ << >> >>>"); + def_is_number(AST_Binary, function(compressor) { + return numeric_ops.has(this.operator) || this.operator == "+" + && this.left.is_number(compressor) + && this.right.is_number(compressor); + }); + def_is_number(AST_Assign, function(compressor) { + return numeric_ops.has(this.operator.slice(0, -1)) + || this.operator == "=" && this.right.is_number(compressor); + }); + def_is_number(AST_Sequence, function(compressor) { + return this.tail_node().is_number(compressor); + }); + def_is_number(AST_Conditional, function(compressor) { + return this.consequent.is_number(compressor) && this.alternative.is_number(compressor); + }); +})(function(node, func) { + node.DEFMETHOD("is_number", func); +}); + +// methods to determine if an expression is a 32 bit integer (IE results from bitwise ops, or is an integer constant fitting in that size +(function(def_is_32_bit_integer) { + def_is_32_bit_integer(AST_Node, return_false); + def_is_32_bit_integer(AST_Number, function() { + return this.value === (this.value | 0); + }); + def_is_32_bit_integer(AST_UnaryPrefix, function() { + return this.operator == "~" ? this.expression.is_number() + : this.operator === "+" ? this.expression.is_32_bit_integer() + : false; + }); + def_is_32_bit_integer(AST_Binary, function() { + return bitwise_binop.has(this.operator); + }); +}(function (node, func) { + node.DEFMETHOD("is_32_bit_integer", func); +})); + +// methods to determine if an expression has a string result type +(function(def_is_string) { + def_is_string(AST_Node, return_false); + def_is_string(AST_String, return_true); + def_is_string(AST_TemplateString, return_true); + def_is_string(AST_UnaryPrefix, function() { + return this.operator == "typeof"; + }); + def_is_string(AST_Binary, function(compressor) { + return this.operator == "+" && + (this.left.is_string(compressor) || this.right.is_string(compressor)); + }); + def_is_string(AST_Assign, function(compressor) { + return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor); + }); + def_is_string(AST_Sequence, function(compressor) { + return this.tail_node().is_string(compressor); + }); + def_is_string(AST_Conditional, function(compressor) { + return this.consequent.is_string(compressor) && this.alternative.is_string(compressor); + }); +})(function(node, func) { + node.DEFMETHOD("is_string", func); +}); + +function is_undefined(node, compressor) { + return ( + has_flag(node, UNDEFINED) + || node instanceof AST_Undefined + || node instanceof AST_UnaryPrefix + && node.operator == "void" + && !node.expression.has_side_effects(compressor) + ); +} + +// Is the node explicitly null or undefined. +function is_null_or_undefined(node, compressor) { + let fixed; + return ( + node instanceof AST_Null + || is_undefined(node, compressor) + || ( + node instanceof AST_SymbolRef + && (fixed = node.definition().fixed) instanceof AST_Node + && is_nullish(fixed, compressor) + ) + ); +} + +// Find out if this expression is optionally chained from a base-point that we +// can statically analyze as null or undefined. +function is_nullish_shortcircuited(node, compressor) { + if (node instanceof AST_PropAccess || node instanceof AST_Call) { + return ( + (node.optional && is_null_or_undefined(node.expression, compressor)) + || is_nullish_shortcircuited(node.expression, compressor) + ); + } + if (node instanceof AST_Chain) return is_nullish_shortcircuited(node.expression, compressor); + return false; +} + +// Find out if something is == null, or can short circuit into nullish. +// Used to optimize ?. and ?? +function is_nullish(node, compressor) { + if (is_null_or_undefined(node, compressor)) return true; + return is_nullish_shortcircuited(node, compressor); +} + +// Determine if expression might cause side effects +// If there's a possibility that a node may change something when it's executed, this returns true +(function(def_has_side_effects) { + def_has_side_effects(AST_Node, return_true); + + def_has_side_effects(AST_EmptyStatement, return_false); + def_has_side_effects(AST_Constant, return_false); + def_has_side_effects(AST_This, return_false); + + function any(list, compressor) { + for (var i = list.length; --i >= 0;) + if (list[i].has_side_effects(compressor)) + return true; + return false; + } + + def_has_side_effects(AST_Block, function(compressor) { + return any(this.body, compressor); + }); + def_has_side_effects(AST_Call, function(compressor) { + if ( + !this.is_callee_pure(compressor) + && (!this.expression.is_call_pure(compressor) + || this.expression.has_side_effects(compressor)) + ) { + return true; + } + return any(this.args, compressor); + }); + def_has_side_effects(AST_Switch, function(compressor) { + return this.expression.has_side_effects(compressor) + || any(this.body, compressor); + }); + def_has_side_effects(AST_Case, function(compressor) { + return this.expression.has_side_effects(compressor) + || any(this.body, compressor); + }); + def_has_side_effects(AST_Try, function(compressor) { + return this.body.has_side_effects(compressor) + || this.bcatch && this.bcatch.has_side_effects(compressor) + || this.bfinally && this.bfinally.has_side_effects(compressor); + }); + def_has_side_effects(AST_If, function(compressor) { + return this.condition.has_side_effects(compressor) + || this.body && this.body.has_side_effects(compressor) + || this.alternative && this.alternative.has_side_effects(compressor); + }); + def_has_side_effects(AST_ImportMeta, return_false); + def_has_side_effects(AST_LabeledStatement, function(compressor) { + return this.body.has_side_effects(compressor); + }); + def_has_side_effects(AST_SimpleStatement, function(compressor) { + return this.body.has_side_effects(compressor); + }); + def_has_side_effects(AST_Lambda, return_false); + def_has_side_effects(AST_Class, function (compressor) { + if (this.extends && this.extends.has_side_effects(compressor)) { + return true; + } + return any(this.properties, compressor); + }); + def_has_side_effects(AST_ClassStaticBlock, function(compressor) { + return any(this.body, compressor); + }); + def_has_side_effects(AST_Binary, function(compressor) { + return this.left.has_side_effects(compressor) + || this.right.has_side_effects(compressor); + }); + def_has_side_effects(AST_Assign, return_true); + def_has_side_effects(AST_Conditional, function(compressor) { + return this.condition.has_side_effects(compressor) + || this.consequent.has_side_effects(compressor) + || this.alternative.has_side_effects(compressor); + }); + def_has_side_effects(AST_Unary, function(compressor) { + return unary_side_effects.has(this.operator) + || this.expression.has_side_effects(compressor); + }); + def_has_side_effects(AST_SymbolRef, function(compressor) { + return !this.is_declared(compressor) && !pure_prop_access_globals.has(this.name); + }); + def_has_side_effects(AST_SymbolClassProperty, return_false); + def_has_side_effects(AST_SymbolDeclaration, return_false); + def_has_side_effects(AST_Object, function(compressor) { + return any(this.properties, compressor); + }); + def_has_side_effects(AST_ObjectProperty, function(compressor) { + return ( + this.computed_key() && this.key.has_side_effects(compressor) + || this.value && this.value.has_side_effects(compressor) + ); + }); + def_has_side_effects(AST_ClassProperty, function(compressor) { + return ( + this.computed_key() && this.key.has_side_effects(compressor) + || this.static && this.value && this.value.has_side_effects(compressor) + ); + }); + def_has_side_effects(AST_ConciseMethod, function(compressor) { + return this.computed_key() && this.key.has_side_effects(compressor); + }); + def_has_side_effects(AST_ObjectGetter, function(compressor) { + return this.computed_key() && this.key.has_side_effects(compressor); + }); + def_has_side_effects(AST_ObjectSetter, function(compressor) { + return this.computed_key() && this.key.has_side_effects(compressor); + }); + def_has_side_effects(AST_Array, function(compressor) { + return any(this.elements, compressor); + }); + def_has_side_effects(AST_Dot, function(compressor) { + if (is_nullish(this, compressor)) { + return this.expression.has_side_effects(compressor); + } + if (!this.optional && this.expression.may_throw_on_access(compressor)) { + return true; + } + + return this.expression.has_side_effects(compressor); + }); + def_has_side_effects(AST_Sub, function(compressor) { + if (is_nullish(this, compressor)) { + return this.expression.has_side_effects(compressor); + } + if (!this.optional && this.expression.may_throw_on_access(compressor)) { + return true; + } + + var property = this.property.has_side_effects(compressor); + if (property && this.optional) return true; // "?." is a condition + + return property || this.expression.has_side_effects(compressor); + }); + def_has_side_effects(AST_Chain, function (compressor) { + return this.expression.has_side_effects(compressor); + }); + def_has_side_effects(AST_Sequence, function(compressor) { + return any(this.expressions, compressor); + }); + def_has_side_effects(AST_Definitions, function(compressor) { + return any(this.definitions, compressor); + }); + def_has_side_effects(AST_VarDef, function() { + return this.value != null; + }); + def_has_side_effects(AST_TemplateSegment, return_false); + def_has_side_effects(AST_TemplateString, function(compressor) { + return any(this.segments, compressor); + }); +})(function(node, func) { + node.DEFMETHOD("has_side_effects", func); +}); + +// determine if expression may throw +(function(def_may_throw) { + def_may_throw(AST_Node, return_true); + + def_may_throw(AST_Constant, return_false); + def_may_throw(AST_EmptyStatement, return_false); + def_may_throw(AST_Lambda, return_false); + def_may_throw(AST_SymbolDeclaration, return_false); + def_may_throw(AST_This, return_false); + def_may_throw(AST_ImportMeta, return_false); + + function any(list, compressor) { + for (var i = list.length; --i >= 0;) + if (list[i].may_throw(compressor)) + return true; + return false; + } + + def_may_throw(AST_Class, function(compressor) { + if (this.extends && this.extends.may_throw(compressor)) return true; + return any(this.properties, compressor); + }); + def_may_throw(AST_ClassStaticBlock, function (compressor) { + return any(this.body, compressor); + }); + + def_may_throw(AST_Array, function(compressor) { + return any(this.elements, compressor); + }); + def_may_throw(AST_Assign, function(compressor) { + if (this.right.may_throw(compressor)) return true; + if (!compressor.has_directive("use strict") + && this.operator == "=" + && this.left instanceof AST_SymbolRef) { + return false; + } + return this.left.may_throw(compressor); + }); + def_may_throw(AST_Binary, function(compressor) { + return this.left.may_throw(compressor) + || this.right.may_throw(compressor); + }); + def_may_throw(AST_Block, function(compressor) { + return any(this.body, compressor); + }); + def_may_throw(AST_Call, function(compressor) { + if (is_nullish(this, compressor)) return false; + if (any(this.args, compressor)) return true; + if (this.is_callee_pure(compressor)) return false; + if (this.expression.may_throw(compressor)) return true; + return !(this.expression instanceof AST_Lambda) + || any(this.expression.body, compressor); + }); + def_may_throw(AST_Case, function(compressor) { + return this.expression.may_throw(compressor) + || any(this.body, compressor); + }); + def_may_throw(AST_Conditional, function(compressor) { + return this.condition.may_throw(compressor) + || this.consequent.may_throw(compressor) + || this.alternative.may_throw(compressor); + }); + def_may_throw(AST_Definitions, function(compressor) { + return any(this.definitions, compressor); + }); + def_may_throw(AST_If, function(compressor) { + return this.condition.may_throw(compressor) + || this.body && this.body.may_throw(compressor) + || this.alternative && this.alternative.may_throw(compressor); + }); + def_may_throw(AST_LabeledStatement, function(compressor) { + return this.body.may_throw(compressor); + }); + def_may_throw(AST_Object, function(compressor) { + return any(this.properties, compressor); + }); + def_may_throw(AST_ObjectProperty, function(compressor) { + // TODO key may throw too + return this.value ? this.value.may_throw(compressor) : false; + }); + def_may_throw(AST_ClassProperty, function(compressor) { + return ( + this.computed_key() && this.key.may_throw(compressor) + || this.static && this.value && this.value.may_throw(compressor) + ); + }); + def_may_throw(AST_ConciseMethod, function(compressor) { + return this.computed_key() && this.key.may_throw(compressor); + }); + def_may_throw(AST_ObjectGetter, function(compressor) { + return this.computed_key() && this.key.may_throw(compressor); + }); + def_may_throw(AST_ObjectSetter, function(compressor) { + return this.computed_key() && this.key.may_throw(compressor); + }); + def_may_throw(AST_Return, function(compressor) { + return this.value && this.value.may_throw(compressor); + }); + def_may_throw(AST_Sequence, function(compressor) { + return any(this.expressions, compressor); + }); + def_may_throw(AST_SimpleStatement, function(compressor) { + return this.body.may_throw(compressor); + }); + def_may_throw(AST_Dot, function(compressor) { + if (is_nullish(this, compressor)) return false; + return !this.optional && this.expression.may_throw_on_access(compressor) + || this.expression.may_throw(compressor); + }); + def_may_throw(AST_Sub, function(compressor) { + if (is_nullish(this, compressor)) return false; + return !this.optional && this.expression.may_throw_on_access(compressor) + || this.expression.may_throw(compressor) + || this.property.may_throw(compressor); + }); + def_may_throw(AST_Chain, function(compressor) { + return this.expression.may_throw(compressor); + }); + def_may_throw(AST_Switch, function(compressor) { + return this.expression.may_throw(compressor) + || any(this.body, compressor); + }); + def_may_throw(AST_SymbolRef, function(compressor) { + return !this.is_declared(compressor) && !pure_prop_access_globals.has(this.name); + }); + def_may_throw(AST_SymbolClassProperty, return_false); + def_may_throw(AST_Try, function(compressor) { + return this.bcatch ? this.bcatch.may_throw(compressor) : this.body.may_throw(compressor) + || this.bfinally && this.bfinally.may_throw(compressor); + }); + def_may_throw(AST_Unary, function(compressor) { + if (this.operator == "typeof" && this.expression instanceof AST_SymbolRef) + return false; + return this.expression.may_throw(compressor); + }); + def_may_throw(AST_VarDef, function(compressor) { + if (!this.value) return false; + return this.value.may_throw(compressor); + }); +})(function(node, func) { + node.DEFMETHOD("may_throw", func); +}); + +// determine if expression is constant +(function(def_is_constant_expression) { + function all_refs_local(scope) { + let result = true; + walk(this, node => { + if (node instanceof AST_SymbolRef) { + if (has_flag(this, INLINED)) { + result = false; + return walk_abort; + } + var def = node.definition(); + if ( + member(def, this.enclosed) + && !this.variables.has(def.name) + ) { + if (scope) { + var scope_def = scope.find_variable(node); + if (def.undeclared ? !scope_def : scope_def === def) { + result = "f"; + return true; + } + } + result = false; + return walk_abort; + } + return true; + } + if (node instanceof AST_This && this instanceof AST_Arrow) { + result = false; + return walk_abort; + } + }); + return result; + } + + def_is_constant_expression(AST_Node, return_false); + def_is_constant_expression(AST_Constant, return_true); + def_is_constant_expression(AST_Class, function(scope) { + if (this.extends && !this.extends.is_constant_expression(scope)) { + return false; + } + + for (const prop of this.properties) { + if (prop.computed_key() && !prop.key.is_constant_expression(scope)) { + return false; + } + if (prop.static && prop.value && !prop.value.is_constant_expression(scope)) { + return false; + } + if (prop instanceof AST_ClassStaticBlock) { + return false; + } + } + + return all_refs_local.call(this, scope); + }); + def_is_constant_expression(AST_Lambda, all_refs_local); + def_is_constant_expression(AST_Unary, function() { + return this.expression.is_constant_expression(); + }); + def_is_constant_expression(AST_Binary, function() { + return this.left.is_constant_expression() + && this.right.is_constant_expression(); + }); + def_is_constant_expression(AST_Array, function() { + return this.elements.every((l) => l.is_constant_expression()); + }); + def_is_constant_expression(AST_Object, function() { + return this.properties.every((l) => l.is_constant_expression()); + }); + def_is_constant_expression(AST_ObjectProperty, function() { + return !!(!(this.key instanceof AST_Node) && this.value && this.value.is_constant_expression()); + }); +})(function(node, func) { + node.DEFMETHOD("is_constant_expression", func); +}); + + +// may_throw_on_access() +// returns true if this node may be null, undefined or contain `AST_Accessor` +(function(def_may_throw_on_access) { + AST_Node.DEFMETHOD("may_throw_on_access", function(compressor) { + return !compressor.option("pure_getters") + || this._dot_throw(compressor); + }); + + function is_strict(compressor) { + return /strict/.test(compressor.option("pure_getters")); + } + + def_may_throw_on_access(AST_Node, is_strict); + def_may_throw_on_access(AST_Null, return_true); + def_may_throw_on_access(AST_Undefined, return_true); + def_may_throw_on_access(AST_Constant, return_false); + def_may_throw_on_access(AST_Array, return_false); + def_may_throw_on_access(AST_Object, function(compressor) { + if (!is_strict(compressor)) return false; + for (var i = this.properties.length; --i >=0;) + if (this.properties[i]._dot_throw(compressor)) return true; + return false; + }); + // Do not be as strict with classes as we are with objects. + // Hopefully the community is not going to abuse static getters and setters. + // https://github.com/terser/terser/issues/724#issuecomment-643655656 + def_may_throw_on_access(AST_Class, return_false); + def_may_throw_on_access(AST_ObjectProperty, return_false); + def_may_throw_on_access(AST_ObjectGetter, return_true); + def_may_throw_on_access(AST_Expansion, function(compressor) { + return this.expression._dot_throw(compressor); + }); + def_may_throw_on_access(AST_Function, return_false); + def_may_throw_on_access(AST_Arrow, return_false); + def_may_throw_on_access(AST_UnaryPostfix, return_false); + def_may_throw_on_access(AST_UnaryPrefix, function() { + return this.operator == "void"; + }); + def_may_throw_on_access(AST_Binary, function(compressor) { + return (this.operator == "&&" || this.operator == "||" || this.operator == "??") + && (this.left._dot_throw(compressor) || this.right._dot_throw(compressor)); + }); + def_may_throw_on_access(AST_Assign, function(compressor) { + if (this.logical) return true; + + return this.operator == "=" + && this.right._dot_throw(compressor); + }); + def_may_throw_on_access(AST_Conditional, function(compressor) { + return this.consequent._dot_throw(compressor) + || this.alternative._dot_throw(compressor); + }); + def_may_throw_on_access(AST_Dot, function(compressor) { + if (!is_strict(compressor)) return false; + + if (this.property == "prototype") { + return !( + this.expression instanceof AST_Function + || this.expression instanceof AST_Class + ); + } + return true; + }); + def_may_throw_on_access(AST_Chain, function(compressor) { + return this.expression._dot_throw(compressor); + }); + def_may_throw_on_access(AST_Sequence, function(compressor) { + return this.tail_node()._dot_throw(compressor); + }); + def_may_throw_on_access(AST_SymbolRef, function(compressor) { + if (this.name === "arguments" && this.scope instanceof AST_Lambda) return false; + if (has_flag(this, UNDEFINED)) return true; + if (!is_strict(compressor)) return false; + if (is_undeclared_ref(this) && this.is_declared(compressor)) return false; + if (this.is_immutable()) return false; + var fixed = this.fixed_value(); + return !fixed || fixed._dot_throw(compressor); + }); +})(function(node, func) { + node.DEFMETHOD("_dot_throw", func); +}); + +function is_lhs(node, parent) { + if (parent instanceof AST_Unary && unary_side_effects.has(parent.operator)) return parent.expression; + if (parent instanceof AST_Assign && parent.left === node) return node; + if (parent instanceof AST_ForIn && parent.init === node) return node; +} + +// method to negate an expression +(function(def_negate) { + function basic_negation(exp) { + return make_node(AST_UnaryPrefix, exp, { + operator: "!", + expression: exp + }); + } + function best(orig, alt, first_in_statement) { + var negated = basic_negation(orig); + if (first_in_statement) { + var stat = make_node(AST_SimpleStatement, alt, { + body: alt + }); + return best_of_expression(negated, stat) === stat ? alt : negated; + } + return best_of_expression(negated, alt); + } + def_negate(AST_Node, function() { + return basic_negation(this); + }); + def_negate(AST_Statement, function() { + throw new Error("Cannot negate a statement"); + }); + def_negate(AST_Function, function() { + return basic_negation(this); + }); + def_negate(AST_Class, function() { + return basic_negation(this); + }); + def_negate(AST_Arrow, function() { + return basic_negation(this); + }); + def_negate(AST_UnaryPrefix, function() { + if (this.operator == "!") + return this.expression; + return basic_negation(this); + }); + def_negate(AST_Sequence, function(compressor) { + var expressions = this.expressions.slice(); + expressions.push(expressions.pop().negate(compressor)); + return make_sequence(this, expressions); + }); + def_negate(AST_Conditional, function(compressor, first_in_statement) { + var self = this.clone(); + self.consequent = self.consequent.negate(compressor); + self.alternative = self.alternative.negate(compressor); + return best(this, self, first_in_statement); + }); + def_negate(AST_Binary, function(compressor, first_in_statement) { + var self = this.clone(), op = this.operator; + if (compressor.option("unsafe_comps")) { + switch (op) { + case "<=" : self.operator = ">" ; return self; + case "<" : self.operator = ">=" ; return self; + case ">=" : self.operator = "<" ; return self; + case ">" : self.operator = "<=" ; return self; + } + } + switch (op) { + case "==" : self.operator = "!="; return self; + case "!=" : self.operator = "=="; return self; + case "===": self.operator = "!=="; return self; + case "!==": self.operator = "==="; return self; + case "&&": + self.operator = "||"; + self.left = self.left.negate(compressor, first_in_statement); + self.right = self.right.negate(compressor); + return best(this, self, first_in_statement); + case "||": + self.operator = "&&"; + self.left = self.left.negate(compressor, first_in_statement); + self.right = self.right.negate(compressor); + return best(this, self, first_in_statement); + } + return basic_negation(this); + }); +})(function(node, func) { + node.DEFMETHOD("negate", function(compressor, first_in_statement) { + return func.call(this, compressor, first_in_statement); + }); +}); + +(function (def_bitwise_negate) { + function basic_negation(exp) { + return make_node(AST_UnaryPrefix, exp, { + operator: "~", + expression: exp + }); + } + + def_bitwise_negate(AST_Node, function() { + return basic_negation(this); + }); + + def_bitwise_negate(AST_Number, function() { + const neg = ~this.value; + if (neg.toString().length > this.value.toString().length) { + return basic_negation(this); + } + return make_node(AST_Number, this, { value: neg }); + }); + + def_bitwise_negate(AST_UnaryPrefix, function(in_32_bit_context) { + if (this.operator == "~" && (in_32_bit_context || this.expression.is_32_bit_integer())) { + return this.expression; + } else { + return basic_negation(this); + } + }); +})(function (node, func) { + node.DEFMETHOD("bitwise_negate", func); +}); + +// Is the callee of this function pure? +var global_pure_fns = makePredicate("Boolean decodeURI decodeURIComponent Date encodeURI encodeURIComponent Error escape EvalError isFinite isNaN Number Object parseFloat parseInt RangeError ReferenceError String SyntaxError TypeError unescape URIError"); +AST_Call.DEFMETHOD("is_callee_pure", function(compressor) { + if (compressor.option("unsafe")) { + var expr = this.expression; + var first_arg = (this.args && this.args[0] && this.args[0].evaluate(compressor)); + if ( + expr.expression && expr.expression.name === "hasOwnProperty" && + (first_arg == null || first_arg.thedef && first_arg.thedef.undeclared) + ) { + return false; + } + if (is_undeclared_ref(expr) && global_pure_fns.has(expr.name)) return true; + if ( + expr instanceof AST_Dot + && is_undeclared_ref(expr.expression) + && is_pure_native_fn(expr.expression.name, expr.property) + ) { + return true; + } + } + if ((this instanceof AST_New) && compressor.option("pure_new")) { + return true; + } + if (compressor.option("side_effects") && has_annotation(this, _PURE)) { + return true; + } + return !compressor.pure_funcs(this); +}); + +// If I call this, is it a pure function? +AST_Node.DEFMETHOD("is_call_pure", return_false); +AST_Dot.DEFMETHOD("is_call_pure", function(compressor) { + if (!compressor.option("unsafe")) return; + const expr = this.expression; + + let native_obj; + if (expr instanceof AST_Array) { + native_obj = "Array"; + } else if (expr.is_boolean()) { + native_obj = "Boolean"; + } else if (expr.is_number(compressor)) { + native_obj = "Number"; + } else if (expr instanceof AST_RegExp) { + native_obj = "RegExp"; + } else if (expr.is_string(compressor)) { + native_obj = "String"; + } else if (!this.may_throw_on_access(compressor)) { + native_obj = "Object"; + } + return native_obj != null && is_pure_native_method(native_obj, this.property); +}); + +// tell me if a statement aborts +const aborts = (thing) => thing && thing.aborts(); + +(function(def_aborts) { + def_aborts(AST_Statement, return_null); + def_aborts(AST_Jump, return_this); + function block_aborts() { + for (var i = 0; i < this.body.length; i++) { + if (aborts(this.body[i])) { + return this.body[i]; + } + } + return null; + } + def_aborts(AST_Import, return_null); + def_aborts(AST_BlockStatement, block_aborts); + def_aborts(AST_SwitchBranch, block_aborts); + def_aborts(AST_DefClass, function () { + for (const prop of this.properties) { + if (prop instanceof AST_ClassStaticBlock) { + if (prop.aborts()) return prop; + } + } + return null; + }); + def_aborts(AST_ClassStaticBlock, block_aborts); + def_aborts(AST_If, function() { + return this.alternative && aborts(this.body) && aborts(this.alternative) && this; + }); +})(function(node, func) { + node.DEFMETHOD("aborts", func); +}); + +AST_Node.DEFMETHOD("contains_this", function() { + return walk(this, node => { + if (node instanceof AST_This) return walk_abort; + if ( + node !== this + && node instanceof AST_Scope + && !(node instanceof AST_Arrow) + ) { + return true; + } + }); +}); + +function is_modified(compressor, tw, node, value, level, immutable) { + var parent = tw.parent(level); + var lhs = is_lhs(node, parent); + if (lhs) return lhs; + if (!immutable + && parent instanceof AST_Call + && parent.expression === node + && !(value instanceof AST_Arrow) + && !(value instanceof AST_Class) + && !parent.is_callee_pure(compressor) + && (!(value instanceof AST_Function) + || !(parent instanceof AST_New) && value.contains_this())) { + return true; + } + if (parent instanceof AST_Array) { + return is_modified(compressor, tw, parent, parent, level + 1); + } + if (parent instanceof AST_ObjectKeyVal && node === parent.value) { + var obj = tw.parent(level + 1); + return is_modified(compressor, tw, obj, obj, level + 2); + } + if (parent instanceof AST_PropAccess && parent.expression === node) { + var prop = read_property(value, parent.property); + return !immutable && is_modified(compressor, tw, parent, prop, level + 1); + } +} + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +// methods to evaluate a constant expression + +function def_eval(node, func) { + node.DEFMETHOD("_eval", func); +} + +// Used to propagate a nullish short-circuit signal upwards through the chain. +const nullish = Symbol("This AST_Chain is nullish"); + +// If the node has been successfully reduced to a constant, +// then its value is returned; otherwise the element itself +// is returned. +// They can be distinguished as constant value is never a +// descendant of AST_Node. +AST_Node.DEFMETHOD("evaluate", function (compressor) { + if (!compressor.option("evaluate")) + return this; + var val = this._eval(compressor, 1); + if (!val || val instanceof RegExp) + return val; + if (typeof val == "function" || typeof val == "object" || val == nullish) + return this; + + // Evaluated strings can be larger than the original expression + if (typeof val === "string") { + const unevaluated_size = this.size(compressor); + if (val.length + 2 > unevaluated_size) return this; + } + + return val; +}); + +var unaryPrefix = makePredicate("! ~ - + void"); +AST_Node.DEFMETHOD("is_constant", function () { + // Accomodate when compress option evaluate=false + // as well as the common constant expressions !0 and -1 + if (this instanceof AST_Constant) { + return !(this instanceof AST_RegExp); + } else { + return this instanceof AST_UnaryPrefix + && this.expression instanceof AST_Constant + && unaryPrefix.has(this.operator); + } +}); + +def_eval(AST_Statement, function () { + throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start)); +}); + +def_eval(AST_Lambda, return_this); +def_eval(AST_Class, return_this); +def_eval(AST_Node, return_this); +def_eval(AST_Constant, function () { + return this.getValue(); +}); + +const supports_bigint = typeof BigInt === "function"; +def_eval(AST_BigInt, function () { + if (supports_bigint) { + return BigInt(this.value); + } else { + return this; + } +}); + +def_eval(AST_RegExp, function (compressor) { + let evaluated = compressor.evaluated_regexps.get(this.value); + if (evaluated === undefined && regexp_is_safe(this.value.source)) { + try { + const { source, flags } = this.value; + evaluated = new RegExp(source, flags); + } catch (e) { + evaluated = null; + } + compressor.evaluated_regexps.set(this.value, evaluated); + } + return evaluated || this; +}); + +def_eval(AST_TemplateString, function () { + if (this.segments.length !== 1) return this; + return this.segments[0].value; +}); + +def_eval(AST_Function, function (compressor) { + if (compressor.option("unsafe")) { + var fn = function () { }; + fn.node = this; + fn.toString = () => this.print_to_string(); + return fn; + } + return this; +}); + +def_eval(AST_Array, function (compressor, depth) { + if (compressor.option("unsafe")) { + var elements = []; + for (var i = 0, len = this.elements.length; i < len; i++) { + var element = this.elements[i]; + var value = element._eval(compressor, depth); + if (element === value) + return this; + elements.push(value); + } + return elements; + } + return this; +}); + +def_eval(AST_Object, function (compressor, depth) { + if (compressor.option("unsafe")) { + var val = {}; + for (var i = 0, len = this.properties.length; i < len; i++) { + var prop = this.properties[i]; + if (prop instanceof AST_Expansion) + return this; + var key = prop.key; + if (key instanceof AST_Symbol) { + key = key.name; + } else if (key instanceof AST_Node) { + key = key._eval(compressor, depth); + if (key === prop.key) + return this; + } + if (typeof Object.prototype[key] === "function") { + return this; + } + if (prop.value instanceof AST_Function) + continue; + val[key] = prop.value._eval(compressor, depth); + if (val[key] === prop.value) + return this; + } + return val; + } + return this; +}); + +var non_converting_unary = makePredicate("! typeof void"); +def_eval(AST_UnaryPrefix, function (compressor, depth) { + var e = this.expression; + if (compressor.option("typeofs") + && this.operator == "typeof") { + // Function would be evaluated to an array and so typeof would + // incorrectly return 'object'. Hence making is a special case. + if (e instanceof AST_Lambda + || e instanceof AST_SymbolRef + && e.fixed_value() instanceof AST_Lambda) { + return typeof function () { }; + } + if ( + (e instanceof AST_Object + || e instanceof AST_Array + || (e instanceof AST_SymbolRef + && (e.fixed_value() instanceof AST_Object + || e.fixed_value() instanceof AST_Array))) + && !e.has_side_effects(compressor) + ) { + return typeof {}; + } + } + if (!non_converting_unary.has(this.operator)) + depth++; + e = e._eval(compressor, depth); + if (e === this.expression) + return this; + switch (this.operator) { + case "!": return !e; + case "typeof": + // typeof returns "object" or "function" on different platforms + // so cannot evaluate reliably + if (e instanceof RegExp) + return this; + return typeof e; + case "void": return void e; + case "~": return ~e; + case "-": return -e; + case "+": return +e; + } + return this; +}); + +var non_converting_binary = makePredicate("&& || ?? === !=="); +const identity_comparison = makePredicate("== != === !=="); +const has_identity = value => typeof value === "object" + || typeof value === "function" + || typeof value === "symbol"; + +def_eval(AST_Binary, function (compressor, depth) { + if (!non_converting_binary.has(this.operator)) + depth++; + + var left = this.left._eval(compressor, depth); + if (left === this.left) + return this; + var right = this.right._eval(compressor, depth); + if (right === this.right) + return this; + + if (left != null + && right != null + && identity_comparison.has(this.operator) + && has_identity(left) + && has_identity(right) + && typeof left === typeof right) { + // Do not compare by reference + return this; + } + + // Do not mix BigInt and Number; Don't use `>>>` on BigInt or `/ 0n` + if ( + (typeof left === "bigint") !== (typeof right === "bigint") + || typeof left === "bigint" + && (this.operator === ">>>" + || this.operator === "/" && Number(right) === 0) + ) { + return this; + } + + var result; + switch (this.operator) { + case "&&": result = left && right; break; + case "||": result = left || right; break; + case "??": result = left != null ? left : right; break; + case "|": result = left | right; break; + case "&": result = left & right; break; + case "^": result = left ^ right; break; + case "+": result = left + right; break; + case "*": result = left * right; break; + case "**": result = left ** right; break; + case "/": result = left / right; break; + case "%": result = left % right; break; + case "-": result = left - right; break; + case "<<": result = left << right; break; + case ">>": result = left >> right; break; + case ">>>": result = left >>> right; break; + case "==": result = left == right; break; + case "===": result = left === right; break; + case "!=": result = left != right; break; + case "!==": result = left !== right; break; + case "<": result = left < right; break; + case "<=": result = left <= right; break; + case ">": result = left > right; break; + case ">=": result = left >= right; break; + default: + return this; + } + if (typeof result === "number" && isNaN(result) && compressor.find_parent(AST_With)) { + // leave original expression as is + return this; + } + return result; +}); + +def_eval(AST_Conditional, function (compressor, depth) { + var condition = this.condition._eval(compressor, depth); + if (condition === this.condition) + return this; + var node = condition ? this.consequent : this.alternative; + var value = node._eval(compressor, depth); + return value === node ? this : value; +}); + +// Set of AST_SymbolRef which are currently being evaluated. +// Avoids infinite recursion of ._eval() +const reentrant_ref_eval = new Set(); +def_eval(AST_SymbolRef, function (compressor, depth) { + if (reentrant_ref_eval.has(this)) + return this; + + var fixed = this.fixed_value(); + if (!fixed) + return this; + + reentrant_ref_eval.add(this); + const value = fixed._eval(compressor, depth); + reentrant_ref_eval.delete(this); + + if (value === fixed) + return this; + + if (value && typeof value == "object") { + var escaped = this.definition().escaped; + if (escaped && depth > escaped) + return this; + } + return value; +}); + +const global_objs = { Array, Math, Number, Object, String }; + +const regexp_flags = new Set([ + "dotAll", + "global", + "ignoreCase", + "multiline", + "sticky", + "unicode", +]); + +def_eval(AST_PropAccess, function (compressor, depth) { + let obj = this.expression._eval(compressor, depth + 1); + if (obj === nullish || (this.optional && obj == null)) return nullish; + + // `.length` of strings and arrays is always safe + if (this.property === "length") { + if (typeof obj === "string") { + return obj.length; + } + + const is_spreadless_array = + obj instanceof AST_Array + && obj.elements.every(el => !(el instanceof AST_Expansion)); + + if ( + is_spreadless_array + && obj.elements.every(el => !el.has_side_effects(compressor)) + ) { + return obj.elements.length; + } + } + + if (compressor.option("unsafe")) { + var key = this.property; + if (key instanceof AST_Node) { + key = key._eval(compressor, depth); + if (key === this.property) + return this; + } + + var exp = this.expression; + if (is_undeclared_ref(exp)) { + var aa; + var first_arg = exp.name === "hasOwnProperty" + && key === "call" + && (aa = compressor.parent() && compressor.parent().args) + && (aa && aa[0] + && aa[0].evaluate(compressor)); + + first_arg = first_arg instanceof AST_Dot ? first_arg.expression : first_arg; + + if (first_arg == null || first_arg.thedef && first_arg.thedef.undeclared) { + return this.clone(); + } + if (!is_pure_native_value(exp.name, key)) + return this; + obj = global_objs[exp.name]; + } else { + if (obj instanceof RegExp) { + if (key == "source") { + return regexp_source_fix(obj.source); + } else if (key == "flags" || regexp_flags.has(key)) { + return obj[key]; + } + } + if (!obj || obj === exp || !HOP(obj, key)) + return this; + + if (typeof obj == "function") + switch (key) { + case "name": + return obj.node.name ? obj.node.name.name : ""; + case "length": + return obj.node.length_property(); + default: + return this; + } + } + return obj[key]; + } + return this; +}); + +def_eval(AST_Chain, function (compressor, depth) { + const evaluated = this.expression._eval(compressor, depth); + return evaluated === nullish + ? undefined + : evaluated === this.expression + ? this + : evaluated; +}); + +def_eval(AST_Call, function (compressor, depth) { + var exp = this.expression; + + const callee = exp._eval(compressor, depth); + if (callee === nullish || (this.optional && callee == null)) return nullish; + + if (compressor.option("unsafe") && exp instanceof AST_PropAccess) { + var key = exp.property; + if (key instanceof AST_Node) { + key = key._eval(compressor, depth); + if (key === exp.property) + return this; + } + var val; + var e = exp.expression; + if (is_undeclared_ref(e)) { + var first_arg = e.name === "hasOwnProperty" && + key === "call" && + (this.args[0] && this.args[0].evaluate(compressor)); + + first_arg = first_arg instanceof AST_Dot ? first_arg.expression : first_arg; + + if ((first_arg == null || first_arg.thedef && first_arg.thedef.undeclared)) { + return this.clone(); + } + if (!is_pure_native_fn(e.name, key)) return this; + val = global_objs[e.name]; + } else { + val = e._eval(compressor, depth + 1); + if (val === e || !val) + return this; + if (!is_pure_native_method(val.constructor.name, key)) + return this; + } + var args = []; + for (var i = 0, len = this.args.length; i < len; i++) { + var arg = this.args[i]; + var value = arg._eval(compressor, depth); + if (arg === value) + return this; + if (arg instanceof AST_Lambda) + return this; + args.push(value); + } + try { + return val[key].apply(val, args); + } catch (ex) { + // We don't really care + } + } + return this; +}); + +// Also a subclass of AST_Call +def_eval(AST_New, return_this); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +// AST_Node#drop_side_effect_free() gets called when we don't care about the value, +// only about side effects. We'll be defining this method for each node type in this module +// +// Examples: +// foo++ -> foo++ +// 1 + func() -> func() +// 10 -> (nothing) +// knownPureFunc(foo++) -> foo++ + +function def_drop_side_effect_free(node, func) { + node.DEFMETHOD("drop_side_effect_free", func); +} + +// Drop side-effect-free elements from an array of expressions. +// Returns an array of expressions with side-effects or null +// if all elements were dropped. Note: original array may be +// returned if nothing changed. +function trim(nodes, compressor, first_in_statement) { + var len = nodes.length; + if (!len) return null; + + var ret = [], changed = false; + for (var i = 0; i < len; i++) { + var node = nodes[i].drop_side_effect_free(compressor, first_in_statement); + changed |= node !== nodes[i]; + if (node) { + ret.push(node); + first_in_statement = false; + } + } + return changed ? ret.length ? ret : null : nodes; +} + +def_drop_side_effect_free(AST_Node, return_this); +def_drop_side_effect_free(AST_Constant, return_null); +def_drop_side_effect_free(AST_This, return_null); + +def_drop_side_effect_free(AST_Call, function (compressor, first_in_statement) { + if (is_nullish_shortcircuited(this, compressor)) { + return this.expression.drop_side_effect_free(compressor, first_in_statement); + } + + if (!this.is_callee_pure(compressor)) { + if (this.expression.is_call_pure(compressor)) { + var exprs = this.args.slice(); + exprs.unshift(this.expression.expression); + exprs = trim(exprs, compressor, first_in_statement); + return exprs && make_sequence(this, exprs); + } + if (is_func_expr(this.expression) + && (!this.expression.name || !this.expression.name.definition().references.length)) { + var node = this.clone(); + node.expression.process_expression(false, compressor); + return node; + } + return this; + } + + var args = trim(this.args, compressor, first_in_statement); + return args && make_sequence(this, args); +}); + +def_drop_side_effect_free(AST_Accessor, return_null); + +def_drop_side_effect_free(AST_Function, return_null); + +def_drop_side_effect_free(AST_Arrow, return_null); + +def_drop_side_effect_free(AST_Class, function (compressor) { + const with_effects = []; + + if (this.is_self_referential() && this.has_side_effects(compressor)) { + return this; + } + + const trimmed_extends = this.extends && this.extends.drop_side_effect_free(compressor); + if (trimmed_extends) with_effects.push(trimmed_extends); + + for (const prop of this.properties) { + if (prop instanceof AST_ClassStaticBlock) { + if (prop.has_side_effects(compressor)) { + return this; // Be cautious about these + } + } else { + const trimmed_prop = prop.drop_side_effect_free(compressor); + if (trimmed_prop) with_effects.push(trimmed_prop); + } + } + + if (!with_effects.length) + return null; + + const exprs = make_sequence(this, with_effects); + if (this instanceof AST_DefClass) { + // We want a statement + return make_node(AST_SimpleStatement, this, { body: exprs }); + } else { + return exprs; + } +}); + +def_drop_side_effect_free(AST_ClassProperty, function (compressor) { + const key = this.computed_key() && this.key.drop_side_effect_free(compressor); + + const value = this.static && this.value + && this.value.drop_side_effect_free(compressor); + + if (key && value) + return make_sequence(this, [key, value]); + return key || value || null; +}); + +def_drop_side_effect_free(AST_Binary, function (compressor, first_in_statement) { + var right = this.right.drop_side_effect_free(compressor); + if (!right) + return this.left.drop_side_effect_free(compressor, first_in_statement); + if (lazy_op.has(this.operator)) { + if (right === this.right) + return this; + var node = this.clone(); + node.right = right; + return node; + } else { + var left = this.left.drop_side_effect_free(compressor, first_in_statement); + if (!left) + return this.right.drop_side_effect_free(compressor, first_in_statement); + return make_sequence(this, [left, right]); + } +}); + +def_drop_side_effect_free(AST_Assign, function (compressor) { + if (this.logical) + return this; + + var left = this.left; + if (left.has_side_effects(compressor) + || compressor.has_directive("use strict") + && left instanceof AST_PropAccess + && left.expression.is_constant()) { + return this; + } + set_flag(this, WRITE_ONLY); + while (left instanceof AST_PropAccess) { + left = left.expression; + } + if (left.is_constant_expression(compressor.find_parent(AST_Scope))) { + return this.right.drop_side_effect_free(compressor); + } + return this; +}); + +def_drop_side_effect_free(AST_Conditional, function (compressor) { + var consequent = this.consequent.drop_side_effect_free(compressor); + var alternative = this.alternative.drop_side_effect_free(compressor); + if (consequent === this.consequent && alternative === this.alternative) + return this; + if (!consequent) + return alternative ? make_node(AST_Binary, this, { + operator: "||", + left: this.condition, + right: alternative + }) : this.condition.drop_side_effect_free(compressor); + if (!alternative) + return make_node(AST_Binary, this, { + operator: "&&", + left: this.condition, + right: consequent + }); + var node = this.clone(); + node.consequent = consequent; + node.alternative = alternative; + return node; +}); + +def_drop_side_effect_free(AST_Unary, function (compressor, first_in_statement) { + if (unary_side_effects.has(this.operator)) { + if (!this.expression.has_side_effects(compressor)) { + set_flag(this, WRITE_ONLY); + } else { + clear_flag(this, WRITE_ONLY); + } + return this; + } + if (this.operator == "typeof" && this.expression instanceof AST_SymbolRef) + return null; + var expression = this.expression.drop_side_effect_free(compressor, first_in_statement); + if (first_in_statement && expression && is_iife_call(expression)) { + if (expression === this.expression && this.operator == "!") + return this; + return expression.negate(compressor, first_in_statement); + } + return expression; +}); + +def_drop_side_effect_free(AST_SymbolRef, function (compressor) { + const safe_access = this.is_declared(compressor) + || pure_prop_access_globals.has(this.name); + return safe_access ? null : this; +}); + +def_drop_side_effect_free(AST_Object, function (compressor, first_in_statement) { + var values = trim(this.properties, compressor, first_in_statement); + return values && make_sequence(this, values); +}); + +def_drop_side_effect_free(AST_ObjectProperty, function (compressor, first_in_statement) { + const computed_key = this instanceof AST_ObjectKeyVal && this.key instanceof AST_Node; + const key = computed_key && this.key.drop_side_effect_free(compressor, first_in_statement); + const value = this.value && this.value.drop_side_effect_free(compressor, first_in_statement); + if (key && value) { + return make_sequence(this, [key, value]); + } + return key || value; +}); + +def_drop_side_effect_free(AST_ConciseMethod, function () { + return this.computed_key() ? this.key : null; +}); + +def_drop_side_effect_free(AST_ObjectGetter, function () { + return this.computed_key() ? this.key : null; +}); + +def_drop_side_effect_free(AST_ObjectSetter, function () { + return this.computed_key() ? this.key : null; +}); + +def_drop_side_effect_free(AST_Array, function (compressor, first_in_statement) { + var values = trim(this.elements, compressor, first_in_statement); + return values && make_sequence(this, values); +}); + +def_drop_side_effect_free(AST_Dot, function (compressor, first_in_statement) { + if (is_nullish_shortcircuited(this, compressor)) { + return this.expression.drop_side_effect_free(compressor, first_in_statement); + } + if (!this.optional && this.expression.may_throw_on_access(compressor)) { + return this; + } + + return this.expression.drop_side_effect_free(compressor, first_in_statement); +}); + +def_drop_side_effect_free(AST_Sub, function (compressor, first_in_statement) { + if (is_nullish_shortcircuited(this, compressor)) { + return this.expression.drop_side_effect_free(compressor, first_in_statement); + } + if (!this.optional && this.expression.may_throw_on_access(compressor)) { + return this; + } + + var property = this.property.drop_side_effect_free(compressor); + if (property && this.optional) return this; + + var expression = this.expression.drop_side_effect_free(compressor, first_in_statement); + + if (expression && property) return make_sequence(this, [expression, property]); + return expression || property; +}); + +def_drop_side_effect_free(AST_Chain, function (compressor, first_in_statement) { + return this.expression.drop_side_effect_free(compressor, first_in_statement); +}); + +def_drop_side_effect_free(AST_Sequence, function (compressor) { + var last = this.tail_node(); + var expr = last.drop_side_effect_free(compressor); + if (expr === last) + return this; + var expressions = this.expressions.slice(0, -1); + if (expr) + expressions.push(expr); + if (!expressions.length) { + return make_node(AST_Number, this, { value: 0 }); + } + return make_sequence(this, expressions); +}); + +def_drop_side_effect_free(AST_Expansion, function (compressor, first_in_statement) { + return this.expression.drop_side_effect_free(compressor, first_in_statement); +}); + +def_drop_side_effect_free(AST_TemplateSegment, return_null); + +def_drop_side_effect_free(AST_TemplateString, function (compressor) { + var values = trim(this.segments, compressor, first_in_statement); + return values && make_sequence(this, values); +}); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +const r_keep_assign = /keep_assign/; + +/** Drop unused variables from this scope */ +AST_Scope.DEFMETHOD("drop_unused", function(compressor) { + if (!compressor.option("unused")) return; + if (compressor.has_directive("use asm")) return; + if (!this.variables) return; // not really a scope (eg: AST_Class) + + var self = this; + if (self.pinned()) return; + var drop_funcs = !(self instanceof AST_Toplevel) || compressor.toplevel.funcs; + var drop_vars = !(self instanceof AST_Toplevel) || compressor.toplevel.vars; + const assign_as_unused = r_keep_assign.test(compressor.option("unused")) ? return_false : function(node) { + if (node instanceof AST_Assign + && !node.logical + && (has_flag(node, WRITE_ONLY) || node.operator == "=") + ) { + return node.left; + } + if (node instanceof AST_Unary && has_flag(node, WRITE_ONLY)) { + return node.expression; + } + }; + var in_use_ids = new Map(); + var fixed_ids = new Map(); + if (self instanceof AST_Toplevel && compressor.top_retain) { + self.variables.forEach(function(def) { + if (compressor.top_retain(def)) { + in_use_ids.set(def.id, def); + } + }); + } + var var_defs_by_id = new Map(); + var initializations = new Map(); + + // pass 1: find out which symbols are directly used in + // this scope (not in nested scopes). + var scope = this; + var tw = new TreeWalker(function(node, descend) { + if (node instanceof AST_Lambda && node.uses_arguments && !tw.has_directive("use strict")) { + node.argnames.forEach(function(argname) { + if (!(argname instanceof AST_SymbolDeclaration)) return; + var def = argname.definition(); + in_use_ids.set(def.id, def); + }); + } + if (node === self) return; + if (node instanceof AST_Class && node.has_side_effects(compressor)) { + if (node.is_self_referential()) { + descend(); + } else { + node.visit_nondeferred_class_parts(tw); + } + } + if (node instanceof AST_Defun || node instanceof AST_DefClass) { + var node_def = node.name.definition(); + const in_export = tw.parent() instanceof AST_Export; + if (in_export || !drop_funcs && scope === self) { + if (node_def.global) { + in_use_ids.set(node_def.id, node_def); + } + } + + map_add(initializations, node_def.id, node); + return true; // don't go in nested scopes + } + // In the root scope, we drop things. In inner scopes, we just check for uses. + const in_root_scope = scope === self; + if (node instanceof AST_SymbolFunarg && in_root_scope) { + map_add(var_defs_by_id, node.definition().id, node); + } + if (node instanceof AST_Definitions && in_root_scope) { + const in_export = tw.parent() instanceof AST_Export; + node.definitions.forEach(function(def) { + if (def.name instanceof AST_SymbolVar) { + map_add(var_defs_by_id, def.name.definition().id, def); + } + if (in_export || !drop_vars) { + walk(def.name, node => { + if (node instanceof AST_SymbolDeclaration) { + const def = node.definition(); + if (def.global) { + in_use_ids.set(def.id, def); + } + } + }); + } + if (def.name instanceof AST_Destructuring) { + def.walk(tw); + } + if (def.name instanceof AST_SymbolDeclaration && def.value) { + var node_def = def.name.definition(); + map_add(initializations, node_def.id, def.value); + if (!node_def.chained && def.name.fixed_value() === def.value) { + fixed_ids.set(node_def.id, def); + } + if (def.value.has_side_effects(compressor)) { + def.value.walk(tw); + } + } + }); + return true; + } + return scan_ref_scoped(node, descend); + }); + self.walk(tw); + // pass 2: for every used symbol we need to walk its + // initialization code to figure out if it uses other + // symbols (that may not be in_use). + tw = new TreeWalker(scan_ref_scoped); + in_use_ids.forEach(function (def) { + var init = initializations.get(def.id); + if (init) init.forEach(function(init) { + init.walk(tw); + }); + }); + // pass 3: we should drop declarations not in_use + var tt = new TreeTransformer( + function before(node, descend, in_list) { + var parent = tt.parent(); + if (drop_vars) { + const sym = assign_as_unused(node); + if (sym instanceof AST_SymbolRef) { + var def = sym.definition(); + var in_use = in_use_ids.has(def.id); + if (node instanceof AST_Assign) { + if (!in_use || fixed_ids.has(def.id) && fixed_ids.get(def.id) !== node) { + const assignee = node.right.transform(tt); + if (!in_use && !assignee.has_side_effects(compressor) && !is_used_in_expression(tt)) { + return in_list ? MAP.skip : make_node(AST_Number, node, { value: 0 }); + } + return maintain_this_binding(parent, node, assignee); + } + } else if (!in_use) { + return in_list ? MAP.skip : make_node(AST_Number, node, { value: 0 }); + } + } + } + if (scope !== self) return; + var def; + if (node.name + && (node instanceof AST_ClassExpression + && !keep_name(compressor.option("keep_classnames"), (def = node.name.definition()).name) + || node instanceof AST_Function + && !keep_name(compressor.option("keep_fnames"), (def = node.name.definition()).name))) { + // any declarations with same name will overshadow + // name of this anonymous function and can therefore + // never be used anywhere + if (!in_use_ids.has(def.id) || def.orig.length > 1) node.name = null; + } + if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) { + var trim = + !compressor.option("keep_fargs") + // Is this an IIFE that won't refer to its name? + || parent instanceof AST_Call + && parent.expression === node + && !node.pinned() + && (!node.name || node.name.unreferenced()); + for (var a = node.argnames, i = a.length; --i >= 0;) { + var sym = a[i]; + if (sym instanceof AST_Expansion) { + sym = sym.expression; + } + if (sym instanceof AST_DefaultAssign) { + sym = sym.left; + } + // Do not drop destructuring arguments. + // They constitute a type assertion of sorts + if ( + !(sym instanceof AST_Destructuring) + && !in_use_ids.has(sym.definition().id) + ) { + set_flag(sym, UNUSED); + if (trim) { + a.pop(); + } + } else { + trim = false; + } + } + } + if (node instanceof AST_DefClass && node !== self) { + const def = node.name.definition(); + descend(node, this); + const keep_class = def.global && !drop_funcs || in_use_ids.has(def.id); + if (!keep_class) { + const kept = node.drop_side_effect_free(compressor); + if (kept == null) { + def.eliminated++; + return in_list ? MAP.skip : make_node(AST_EmptyStatement, node); + } + return kept; + } + return node; + } + if (node instanceof AST_Defun && node !== self) { + const def = node.name.definition(); + const keep = def.global && !drop_funcs || in_use_ids.has(def.id); + if (!keep) { + def.eliminated++; + return in_list ? MAP.skip : make_node(AST_EmptyStatement, node); + } + } + if (node instanceof AST_Definitions && !(parent instanceof AST_ForIn && parent.init === node)) { + var drop_block = !(parent instanceof AST_Toplevel) && !(node instanceof AST_Var); + // place uninitialized names at the start + var body = [], head = [], tail = []; + // for unused names whose initialization has + // side effects, we can cascade the init. code + // into the next one, or next statement. + var side_effects = []; + node.definitions.forEach(function(def) { + if (def.value) def.value = def.value.transform(tt); + var is_destructure = def.name instanceof AST_Destructuring; + var sym = is_destructure + ? new SymbolDef(null, { name: "" }) /* fake SymbolDef */ + : def.name.definition(); + if (drop_block && sym.global) return tail.push(def); + if (!(drop_vars || drop_block) + || is_destructure + && (def.name.names.length + || def.name.is_array + || compressor.option("pure_getters") != true) + || in_use_ids.has(sym.id) + ) { + if (def.value && fixed_ids.has(sym.id) && fixed_ids.get(sym.id) !== def) { + def.value = def.value.drop_side_effect_free(compressor); + } + if (def.name instanceof AST_SymbolVar) { + var var_defs = var_defs_by_id.get(sym.id); + if (var_defs.length > 1 && (!def.value || sym.orig.indexOf(def.name) > sym.eliminated)) { + if (def.value) { + var ref = make_node(AST_SymbolRef, def.name, def.name); + sym.references.push(ref); + var assign = make_node(AST_Assign, def, { + operator: "=", + logical: false, + left: ref, + right: def.value + }); + if (fixed_ids.get(sym.id) === def) { + fixed_ids.set(sym.id, assign); + } + side_effects.push(assign.transform(tt)); + } + remove(var_defs, def); + sym.eliminated++; + return; + } + } + if (def.value) { + if (side_effects.length > 0) { + if (tail.length > 0) { + side_effects.push(def.value); + def.value = make_sequence(def.value, side_effects); + } else { + body.push(make_node(AST_SimpleStatement, node, { + body: make_sequence(node, side_effects) + })); + } + side_effects = []; + } + tail.push(def); + } else { + head.push(def); + } + } else if (sym.orig[0] instanceof AST_SymbolCatch) { + var value = def.value && def.value.drop_side_effect_free(compressor); + if (value) side_effects.push(value); + def.value = null; + head.push(def); + } else { + var value = def.value && def.value.drop_side_effect_free(compressor); + if (value) { + side_effects.push(value); + } + sym.eliminated++; + } + }); + if (head.length > 0 || tail.length > 0) { + node.definitions = head.concat(tail); + body.push(node); + } + if (side_effects.length > 0) { + body.push(make_node(AST_SimpleStatement, node, { + body: make_sequence(node, side_effects) + })); + } + switch (body.length) { + case 0: + return in_list ? MAP.skip : make_node(AST_EmptyStatement, node); + case 1: + return body[0]; + default: + return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, { body }); + } + } + // certain combination of unused name + side effect leads to: + // https://github.com/mishoo/UglifyJS2/issues/44 + // https://github.com/mishoo/UglifyJS2/issues/1830 + // https://github.com/mishoo/UglifyJS2/issues/1838 + // that's an invalid AST. + // We fix it at this stage by moving the `var` outside the `for`. + if (node instanceof AST_For) { + descend(node, this); + var block; + if (node.init instanceof AST_BlockStatement) { + block = node.init; + node.init = block.body.pop(); + block.body.push(node); + } + if (node.init instanceof AST_SimpleStatement) { + node.init = node.init.body; + } else if (is_empty(node.init)) { + node.init = null; + } + return !block ? node : in_list ? MAP.splice(block.body) : block; + } + if (node instanceof AST_LabeledStatement + && node.body instanceof AST_For + ) { + descend(node, this); + if (node.body instanceof AST_BlockStatement) { + var block = node.body; + node.body = block.body.pop(); + block.body.push(node); + return in_list ? MAP.splice(block.body) : block; + } + return node; + } + if (node instanceof AST_BlockStatement) { + descend(node, this); + if (in_list && node.body.every(can_be_evicted_from_block)) { + return MAP.splice(node.body); + } + return node; + } + if (node instanceof AST_Scope && !(node instanceof AST_ClassStaticBlock)) { + const save_scope = scope; + scope = node; + descend(node, this); + scope = save_scope; + return node; + } + }, + function after(node, in_list) { + if (node instanceof AST_Sequence) { + switch (node.expressions.length) { + case 0: return in_list ? MAP.skip : make_node(AST_Number, node, { value: 0 }); + case 1: return node.expressions[0]; + } + } + } + ); + + self.transform(tt); + + function scan_ref_scoped(node, descend) { + var node_def; + const sym = assign_as_unused(node); + if (sym instanceof AST_SymbolRef + && !is_ref_of(node.left, AST_SymbolBlockDeclaration) + && self.variables.get(sym.name) === (node_def = sym.definition()) + ) { + if (node instanceof AST_Assign) { + node.right.walk(tw); + if (!node_def.chained && node.left.fixed_value() === node.right) { + fixed_ids.set(node_def.id, node); + } + } + return true; + } + if (node instanceof AST_SymbolRef) { + node_def = node.definition(); + if (!in_use_ids.has(node_def.id)) { + in_use_ids.set(node_def.id, node_def); + if (node_def.orig[0] instanceof AST_SymbolCatch) { + const redef = node_def.scope.is_block_scope() + && node_def.scope.get_defun_scope().variables.get(node_def.name); + if (redef) in_use_ids.set(redef.id, redef); + } + } + return true; + } + if (node instanceof AST_Class) { + descend(); + return true; + } + if (node instanceof AST_Scope && !(node instanceof AST_ClassStaticBlock)) { + var save_scope = scope; + scope = node; + descend(); + scope = save_scope; + return true; + } + } +}); + +/** + * Check if a node may be used by the expression it's in + * void (0, 1, {node}, 2) -> false + * console.log(0, {node}) -> true + */ +function is_used_in_expression(tw) { + for (let p = -1, node, parent; node = tw.parent(p), parent = tw.parent(p + 1); p++) { + if (parent instanceof AST_Sequence) { + const nth_expression = parent.expressions.indexOf(node); + if (nth_expression !== parent.expressions.length - 1) { + // Detect (0, x.noThis)() constructs + const grandparent = tw.parent(p + 2); + if ( + parent.expressions.length > 2 + || parent.expressions.length === 1 + || !requires_sequence_to_maintain_binding(grandparent, parent, parent.expressions[1]) + ) { + return false; + } + return true; + } else { + continue; + } + } + if (parent instanceof AST_Unary) { + const op = parent.operator; + if (op === "void") { + return false; + } + if (op === "typeof" || op === "+" || op === "-" || op === "!" || op === "~") { + continue; + } + } + return true; + } + + return true; +} + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +/** + * Define the method AST_Node#reduce_vars, which goes through the AST in + * execution order to perform basic flow analysis + */ +function def_reduce_vars(node, func) { + node.DEFMETHOD("reduce_vars", func); +} + +def_reduce_vars(AST_Node, noop); + +/** Clear definition properties */ +function reset_def(compressor, def) { + def.assignments = 0; + def.chained = false; + def.direct_access = false; + def.escaped = 0; + def.recursive_refs = 0; + def.references = []; + def.single_use = undefined; + if ( + def.scope.pinned() + || (def.orig[0] instanceof AST_SymbolFunarg && def.scope.uses_arguments) + ) { + def.fixed = false; + } else if (def.orig[0] instanceof AST_SymbolConst || !compressor.exposed(def)) { + def.fixed = def.init; + } else { + def.fixed = false; + } +} + +function reset_variables(tw, compressor, node) { + node.variables.forEach(function(def) { + reset_def(compressor, def); + if (def.fixed === null) { + tw.defs_to_safe_ids.set(def.id, tw.safe_ids); + mark(tw, def, true); + } else if (def.fixed) { + tw.loop_ids.set(def.id, tw.in_loop); + mark(tw, def, true); + } + }); +} + +function reset_block_variables(compressor, node) { + if (node.block_scope) node.block_scope.variables.forEach((def) => { + reset_def(compressor, def); + }); +} + +function push(tw) { + tw.safe_ids = Object.create(tw.safe_ids); +} + +function pop(tw) { + tw.safe_ids = Object.getPrototypeOf(tw.safe_ids); +} + +function mark(tw, def, safe) { + tw.safe_ids[def.id] = safe; +} + +function safe_to_read(tw, def) { + if (def.single_use == "m") return false; + if (tw.safe_ids[def.id]) { + if (def.fixed == null) { + var orig = def.orig[0]; + if (orig instanceof AST_SymbolFunarg || orig.name == "arguments") return false; + def.fixed = make_node(AST_Undefined, orig); + } + return true; + } + return def.fixed instanceof AST_Defun; +} + +function safe_to_assign(tw, def, scope, value) { + if (def.fixed === undefined) return true; + let def_safe_ids; + if (def.fixed === null + && (def_safe_ids = tw.defs_to_safe_ids.get(def.id)) + ) { + def_safe_ids[def.id] = false; + tw.defs_to_safe_ids.delete(def.id); + return true; + } + if (!HOP(tw.safe_ids, def.id)) return false; + if (!safe_to_read(tw, def)) return false; + if (def.fixed === false) return false; + if (def.fixed != null && (!value || def.references.length > def.assignments)) return false; + if (def.fixed instanceof AST_Defun) { + return value instanceof AST_Node && def.fixed.parent_scope === scope; + } + return def.orig.every((sym) => { + return !(sym instanceof AST_SymbolConst + || sym instanceof AST_SymbolDefun + || sym instanceof AST_SymbolLambda); + }); +} + +function ref_once(tw, compressor, def) { + return compressor.option("unused") + && !def.scope.pinned() + && def.references.length - def.recursive_refs == 1 + && tw.loop_ids.get(def.id) === tw.in_loop; +} + +function is_immutable(value) { + if (!value) return false; + return value.is_constant() + || value instanceof AST_Lambda + || value instanceof AST_This; +} + +// A definition "escapes" when its value can leave the point of use. +// Example: `a = b || c` +// In this example, "b" and "c" are escaping, because they're going into "a" +// +// def.escaped is != 0 when it escapes. +// +// When greater than 1, it means that N chained properties will be read off +// of that def before an escape occurs. This is useful for evaluating +// property accesses, where you need to know when to stop. +function mark_escaped(tw, d, scope, node, value, level = 0, depth = 1) { + var parent = tw.parent(level); + if (value) { + if (value.is_constant()) return; + if (value instanceof AST_ClassExpression) return; + } + + if ( + parent instanceof AST_Assign && (parent.operator === "=" || parent.logical) && node === parent.right + || parent instanceof AST_Call && (node !== parent.expression || parent instanceof AST_New) + || parent instanceof AST_Exit && node === parent.value && node.scope !== d.scope + || parent instanceof AST_VarDef && node === parent.value + || parent instanceof AST_Yield && node === parent.value && node.scope !== d.scope + ) { + if (depth > 1 && !(value && value.is_constant_expression(scope))) depth = 1; + if (!d.escaped || d.escaped > depth) d.escaped = depth; + return; + } else if ( + parent instanceof AST_Array + || parent instanceof AST_Await + || parent instanceof AST_Binary && lazy_op.has(parent.operator) + || parent instanceof AST_Conditional && node !== parent.condition + || parent instanceof AST_Expansion + || parent instanceof AST_Sequence && node === parent.tail_node() + ) { + mark_escaped(tw, d, scope, parent, parent, level + 1, depth); + } else if (parent instanceof AST_ObjectKeyVal && node === parent.value) { + var obj = tw.parent(level + 1); + + mark_escaped(tw, d, scope, obj, obj, level + 2, depth); + } else if (parent instanceof AST_PropAccess && node === parent.expression) { + value = read_property(value, parent.property); + + mark_escaped(tw, d, scope, parent, value, level + 1, depth + 1); + if (value) return; + } + + if (level > 0) return; + if (parent instanceof AST_Sequence && node !== parent.tail_node()) return; + if (parent instanceof AST_SimpleStatement) return; + + d.direct_access = true; +} + +const suppress = node => walk(node, node => { + if (!(node instanceof AST_Symbol)) return; + var d = node.definition(); + if (!d) return; + if (node instanceof AST_SymbolRef) d.references.push(node); + d.fixed = false; +}); + +def_reduce_vars(AST_Accessor, function(tw, descend, compressor) { + push(tw); + reset_variables(tw, compressor, this); + descend(); + pop(tw); + return true; +}); + +def_reduce_vars(AST_Assign, function(tw, descend, compressor) { + var node = this; + if (node.left instanceof AST_Destructuring) { + suppress(node.left); + return; + } + + const finish_walk = () => { + if (node.logical) { + node.left.walk(tw); + + push(tw); + node.right.walk(tw); + pop(tw); + + return true; + } + }; + + var sym = node.left; + if (!(sym instanceof AST_SymbolRef)) return finish_walk(); + + var def = sym.definition(); + var safe = safe_to_assign(tw, def, sym.scope, node.right); + def.assignments++; + if (!safe) return finish_walk(); + + var fixed = def.fixed; + if (!fixed && node.operator != "=" && !node.logical) return finish_walk(); + + var eq = node.operator == "="; + var value = eq ? node.right : node; + if (is_modified(compressor, tw, node, value, 0)) return finish_walk(); + + def.references.push(sym); + + if (!node.logical) { + if (!eq) def.chained = true; + + def.fixed = eq ? function() { + return node.right; + } : function() { + return make_node(AST_Binary, node, { + operator: node.operator.slice(0, -1), + left: fixed instanceof AST_Node ? fixed : fixed(), + right: node.right + }); + }; + } + + if (node.logical) { + mark(tw, def, false); + push(tw); + node.right.walk(tw); + pop(tw); + return true; + } + + mark(tw, def, false); + node.right.walk(tw); + mark(tw, def, true); + + mark_escaped(tw, def, sym.scope, node, value, 0, 1); + + return true; +}); + +def_reduce_vars(AST_Binary, function(tw) { + if (!lazy_op.has(this.operator)) return; + this.left.walk(tw); + push(tw); + this.right.walk(tw); + pop(tw); + return true; +}); + +def_reduce_vars(AST_Block, function(tw, descend, compressor) { + reset_block_variables(compressor, this); +}); + +def_reduce_vars(AST_Case, function(tw) { + push(tw); + this.expression.walk(tw); + pop(tw); + push(tw); + walk_body(this, tw); + pop(tw); + return true; +}); + +def_reduce_vars(AST_Class, function(tw, descend) { + clear_flag(this, INLINED); + push(tw); + descend(); + pop(tw); + return true; +}); + +def_reduce_vars(AST_ClassStaticBlock, function(tw, descend, compressor) { + reset_block_variables(compressor, this); +}); + +def_reduce_vars(AST_Conditional, function(tw) { + this.condition.walk(tw); + push(tw); + this.consequent.walk(tw); + pop(tw); + push(tw); + this.alternative.walk(tw); + pop(tw); + return true; +}); + +def_reduce_vars(AST_Chain, function(tw, descend) { + // Chains' conditions apply left-to-right, cumulatively. + // If we walk normally we don't go in that order because we would pop before pushing again + // Solution: AST_PropAccess and AST_Call push when they are optional, and never pop. + // Then we pop everything when they are done being walked. + const safe_ids = tw.safe_ids; + + descend(); + + // Unroll back to start + tw.safe_ids = safe_ids; + return true; +}); + +def_reduce_vars(AST_Call, function (tw) { + this.expression.walk(tw); + + if (this.optional) { + // Never pop -- it's popped at AST_Chain above + push(tw); + } + + for (const arg of this.args) arg.walk(tw); + + return true; +}); + +def_reduce_vars(AST_PropAccess, function (tw) { + if (!this.optional) return; + + this.expression.walk(tw); + + // Never pop -- it's popped at AST_Chain above + push(tw); + + if (this.property instanceof AST_Node) this.property.walk(tw); + + return true; +}); + +def_reduce_vars(AST_Default, function(tw, descend) { + push(tw); + descend(); + pop(tw); + return true; +}); + +function mark_lambda(tw, descend, compressor) { + clear_flag(this, INLINED); + push(tw); + reset_variables(tw, compressor, this); + + var iife; + if (!this.name + && !this.uses_arguments + && !this.pinned() + && (iife = tw.parent()) instanceof AST_Call + && iife.expression === this + && !iife.args.some(arg => arg instanceof AST_Expansion) + && this.argnames.every(arg_name => arg_name instanceof AST_Symbol) + ) { + // Virtually turn IIFE parameters into variable definitions: + // (function(a,b) {...})(c,d) => (function() {var a=c,b=d; ...})() + // So existing transformation rules can work on them. + this.argnames.forEach((arg, i) => { + if (!arg.definition) return; + var d = arg.definition(); + // Avoid setting fixed when there's more than one origin for a variable value + if (d.orig.length > 1) return; + if (d.fixed === undefined && (!this.uses_arguments || tw.has_directive("use strict"))) { + d.fixed = function() { + return iife.args[i] || make_node(AST_Undefined, iife); + }; + tw.loop_ids.set(d.id, tw.in_loop); + mark(tw, d, true); + } else { + d.fixed = false; + } + }); + } + + descend(); + pop(tw); + + handle_defined_after_hoist(this); + + return true; +} + +/** + * It's possible for a hoisted function to use something that's not defined yet. Example: + * + * hoisted(); + * var defined_after = true; + * function hoisted() { + * // use defined_after + * } + * + * Or even indirectly: + * + * B(); + * var defined_after = true; + * function A() { + * // use defined_after + * } + * function B() { + * A(); + * } + * + * Access a variable before declaration will either throw a ReferenceError + * (if the variable is declared with `let` or `const`), + * or get an `undefined` (if the variable is declared with `var`). + * + * If the variable is inlined into the function, the behavior will change. + * + * This function is called on the parent to disallow inlining of such variables, + */ +function handle_defined_after_hoist(parent) { + const defuns = []; + walk(parent, node => { + if (node === parent) return; + if (node instanceof AST_Defun) { + defuns.push(node); + return true; + } + if ( + node instanceof AST_Scope + || node instanceof AST_SimpleStatement + ) return true; + }); + + // `defun` id to array of `defun` it uses + const defun_dependencies_map = new Map(); + // `defun` id to array of enclosing `def` that are used by the function + const dependencies_map = new Map(); + // all symbol ids that will be tracked for read/write + const symbols_of_interest = new Set(); + const defuns_of_interest = new Set(); + + for (const defun of defuns) { + const fname_def = defun.name.definition(); + const enclosing_defs = []; + + for (const def of defun.enclosed) { + if ( + def.fixed === false + || def === fname_def + || def.scope.get_defun_scope() !== parent + ) { + continue; + } + + symbols_of_interest.add(def.id); + + // found a reference to another function + if ( + def.assignments === 0 + && def.orig.length === 1 + && def.orig[0] instanceof AST_SymbolDefun + ) { + defuns_of_interest.add(def.id); + symbols_of_interest.add(def.id); + + defuns_of_interest.add(fname_def.id); + symbols_of_interest.add(fname_def.id); + + if (!defun_dependencies_map.has(fname_def.id)) { + defun_dependencies_map.set(fname_def.id, []); + } + defun_dependencies_map.get(fname_def.id).push(def.id); + + continue; + } + + enclosing_defs.push(def); + } + + if (enclosing_defs.length) { + dependencies_map.set(fname_def.id, enclosing_defs); + defuns_of_interest.add(fname_def.id); + symbols_of_interest.add(fname_def.id); + } + } + + // No defuns use outside constants + if (!dependencies_map.size) { + return; + } + + // Increment to count "symbols of interest" (defuns or defs) that we found. + // These are tracked in AST order so we can check which is after which. + let symbol_index = 1; + // Map a defun ID to its first read (a `symbol_index`) + const defun_first_read_map = new Map(); + // Map a symbol ID to its last write (a `symbol_index`) + const symbol_last_write_map = new Map(); + + walk_parent(parent, (node, walk_info) => { + if (node instanceof AST_Symbol && node.thedef) { + const id = node.definition().id; + + symbol_index++; + + // Track last-writes to symbols + if (symbols_of_interest.has(id)) { + if (node instanceof AST_SymbolDeclaration || is_lhs(node, walk_info.parent())) { + symbol_last_write_map.set(id, symbol_index); + } + } + + // Track first-reads of defuns (refined later) + if (defuns_of_interest.has(id)) { + if (!defun_first_read_map.has(id) && !is_recursive_ref(walk_info, id)) { + defun_first_read_map.set(id, symbol_index); + } + } + } + }); + + // Refine `defun_first_read_map` to be as high as possible + for (const [defun, defun_first_read] of defun_first_read_map) { + // Update all depdencies of `defun` + const queue = new Set(defun_dependencies_map.get(defun)); + for (const enclosed_defun of queue) { + let enclosed_defun_first_read = defun_first_read_map.get(enclosed_defun); + if (enclosed_defun_first_read != null && enclosed_defun_first_read < defun_first_read) { + continue; + } + + defun_first_read_map.set(enclosed_defun, defun_first_read); + + for (const enclosed_enclosed_defun of defun_dependencies_map.get(enclosed_defun) || []) { + queue.add(enclosed_enclosed_defun); + } + } + } + + // ensure write-then-read order, otherwise clear `fixed` + // This is safe because last-writes (found_symbol_writes) are assumed to be as late as possible, and first-reads (defun_first_read_map) are assumed to be as early as possible. + for (const [defun, defs] of dependencies_map) { + const defun_first_read = defun_first_read_map.get(defun); + if (defun_first_read === undefined) { + continue; + } + + for (const def of defs) { + if (def.fixed === false) { + continue; + } + + let def_last_write = symbol_last_write_map.get(def.id) || 0; + + if (defun_first_read < def_last_write) { + def.fixed = false; + } + } + } +} + +def_reduce_vars(AST_Lambda, mark_lambda); + +def_reduce_vars(AST_Do, function(tw, descend, compressor) { + reset_block_variables(compressor, this); + const saved_loop = tw.in_loop; + tw.in_loop = this; + push(tw); + this.body.walk(tw); + if (has_break_or_continue(this)) { + pop(tw); + push(tw); + } + this.condition.walk(tw); + pop(tw); + tw.in_loop = saved_loop; + return true; +}); + +def_reduce_vars(AST_For, function(tw, descend, compressor) { + reset_block_variables(compressor, this); + if (this.init) this.init.walk(tw); + const saved_loop = tw.in_loop; + tw.in_loop = this; + push(tw); + if (this.condition) this.condition.walk(tw); + this.body.walk(tw); + if (this.step) { + if (has_break_or_continue(this)) { + pop(tw); + push(tw); + } + this.step.walk(tw); + } + pop(tw); + tw.in_loop = saved_loop; + return true; +}); + +def_reduce_vars(AST_ForIn, function(tw, descend, compressor) { + reset_block_variables(compressor, this); + suppress(this.init); + this.object.walk(tw); + const saved_loop = tw.in_loop; + tw.in_loop = this; + push(tw); + this.body.walk(tw); + pop(tw); + tw.in_loop = saved_loop; + return true; +}); + +def_reduce_vars(AST_If, function(tw) { + this.condition.walk(tw); + push(tw); + this.body.walk(tw); + pop(tw); + if (this.alternative) { + push(tw); + this.alternative.walk(tw); + pop(tw); + } + return true; +}); + +def_reduce_vars(AST_LabeledStatement, function(tw) { + push(tw); + this.body.walk(tw); + pop(tw); + return true; +}); + +def_reduce_vars(AST_SymbolCatch, function() { + this.definition().fixed = false; +}); + +def_reduce_vars(AST_SymbolRef, function(tw, descend, compressor) { + var d = this.definition(); + d.references.push(this); + if (d.references.length == 1 + && !d.fixed + && d.orig[0] instanceof AST_SymbolDefun) { + tw.loop_ids.set(d.id, tw.in_loop); + } + var fixed_value; + if (d.fixed === undefined || !safe_to_read(tw, d)) { + d.fixed = false; + } else if (d.fixed) { + fixed_value = this.fixed_value(); + if ( + fixed_value instanceof AST_Lambda + && is_recursive_ref(tw, d) + ) { + d.recursive_refs++; + } else if (fixed_value + && !compressor.exposed(d) + && ref_once(tw, compressor, d) + ) { + d.single_use = + fixed_value instanceof AST_Lambda && !fixed_value.pinned() + || fixed_value instanceof AST_Class + || d.scope === this.scope && fixed_value.is_constant_expression(); + } else { + d.single_use = false; + } + if (is_modified(compressor, tw, this, fixed_value, 0, is_immutable(fixed_value))) { + if (d.single_use) { + d.single_use = "m"; + } else { + d.fixed = false; + } + } + } + mark_escaped(tw, d, this.scope, this, fixed_value, 0, 1); +}); + +def_reduce_vars(AST_Toplevel, function(tw, descend, compressor) { + this.globals.forEach(function(def) { + reset_def(compressor, def); + }); + reset_variables(tw, compressor, this); + descend(); + handle_defined_after_hoist(this); + return true; +}); + +def_reduce_vars(AST_Try, function(tw, descend, compressor) { + reset_block_variables(compressor, this); + push(tw); + this.body.walk(tw); + pop(tw); + if (this.bcatch) { + push(tw); + this.bcatch.walk(tw); + pop(tw); + } + if (this.bfinally) this.bfinally.walk(tw); + return true; +}); + +def_reduce_vars(AST_Unary, function(tw) { + var node = this; + if (node.operator !== "++" && node.operator !== "--") return; + var exp = node.expression; + if (!(exp instanceof AST_SymbolRef)) return; + var def = exp.definition(); + var safe = safe_to_assign(tw, def, exp.scope, true); + def.assignments++; + if (!safe) return; + var fixed = def.fixed; + if (!fixed) return; + def.references.push(exp); + def.chained = true; + def.fixed = function() { + return make_node(AST_Binary, node, { + operator: node.operator.slice(0, -1), + left: make_node(AST_UnaryPrefix, node, { + operator: "+", + expression: fixed instanceof AST_Node ? fixed : fixed() + }), + right: make_node(AST_Number, node, { + value: 1 + }) + }); + }; + mark(tw, def, true); + return true; +}); + +def_reduce_vars(AST_VarDef, function(tw, descend) { + var node = this; + if (node.name instanceof AST_Destructuring) { + suppress(node.name); + return; + } + var d = node.name.definition(); + if (node.value) { + if (safe_to_assign(tw, d, node.name.scope, node.value)) { + d.fixed = function() { + return node.value; + }; + tw.loop_ids.set(d.id, tw.in_loop); + mark(tw, d, false); + descend(); + mark(tw, d, true); + return true; + } else { + d.fixed = false; + } + } +}); + +def_reduce_vars(AST_While, function(tw, descend, compressor) { + reset_block_variables(compressor, this); + const saved_loop = tw.in_loop; + tw.in_loop = this; + push(tw); + descend(); + pop(tw); + tw.in_loop = saved_loop; + return true; +}); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +function loop_body(x) { + if (x instanceof AST_IterationStatement) { + return x.body instanceof AST_BlockStatement ? x.body : x; + } + return x; +} + +function is_lhs_read_only(lhs) { + if (lhs instanceof AST_This) return true; + if (lhs instanceof AST_SymbolRef) return lhs.definition().orig[0] instanceof AST_SymbolLambda; + if (lhs instanceof AST_PropAccess) { + lhs = lhs.expression; + if (lhs instanceof AST_SymbolRef) { + if (lhs.is_immutable()) return false; + lhs = lhs.fixed_value(); + } + if (!lhs) return true; + if (lhs instanceof AST_RegExp) return false; + if (lhs instanceof AST_Constant) return true; + return is_lhs_read_only(lhs); + } + return false; +} + +/** var a = 1 --> var a*/ +function remove_initializers(var_statement) { + var decls = []; + var_statement.definitions.forEach(function(def) { + if (def.name instanceof AST_SymbolDeclaration) { + def.value = null; + decls.push(def); + } else { + def.declarations_as_names().forEach(name => { + decls.push(make_node(AST_VarDef, def, { + name, + value: null + })); + }); + } + }); + return decls.length ? make_node(AST_Var, var_statement, { definitions: decls }) : null; +} + +/** Called on code which we know is unreachable, to keep elements that affect outside of it. */ +function trim_unreachable_code(compressor, stat, target) { + walk(stat, node => { + if (node instanceof AST_Var) { + const no_initializers = remove_initializers(node); + if (no_initializers) target.push(no_initializers); + return true; + } + if ( + node instanceof AST_Defun + && (node === stat || !compressor.has_directive("use strict")) + ) { + target.push(node === stat ? node : make_node(AST_Var, node, { + definitions: [ + make_node(AST_VarDef, node, { + name: make_node(AST_SymbolVar, node.name, node.name), + value: null + }) + ] + })); + return true; + } + if (node instanceof AST_Export || node instanceof AST_Import) { + target.push(node); + return true; + } + if (node instanceof AST_Scope) { + return true; + } + }); +} + +/** Tighten a bunch of statements together, and perform statement-level optimization. */ +function tighten_body(statements, compressor) { + const nearest_scope = compressor.find_scope(); + const defun_scope = nearest_scope.get_defun_scope(); + const { in_loop, in_try } = find_loop_scope_try(); + + var CHANGED, max_iter = 10; + do { + CHANGED = false; + eliminate_spurious_blocks(statements); + if (compressor.option("dead_code")) { + eliminate_dead_code(statements, compressor); + } + if (compressor.option("if_return")) { + handle_if_return(statements, compressor); + } + if (compressor.sequences_limit > 0) { + sequencesize(statements, compressor); + sequencesize_2(statements, compressor); + } + if (compressor.option("join_vars")) { + join_consecutive_vars(statements); + } + if (compressor.option("collapse_vars")) { + collapse(statements, compressor); + } + } while (CHANGED && max_iter-- > 0); + + function find_loop_scope_try() { + var node = compressor.self(), level = 0, in_loop = false, in_try = false; + do { + if (node instanceof AST_IterationStatement) { + in_loop = true; + } else if (node instanceof AST_Scope) { + break; + } else if (node instanceof AST_TryBlock) { + in_try = true; + } + } while (node = compressor.parent(level++)); + + return { in_loop, in_try }; + } + + // Search from right to left for assignment-like expressions: + // - `var a = x;` + // - `a = x;` + // - `++a` + // For each candidate, scan from left to right for first usage, then try + // to fold assignment into the site for compression. + // Will not attempt to collapse assignments into or past code blocks + // which are not sequentially executed, e.g. loops and conditionals. + function collapse(statements, compressor) { + if (nearest_scope.pinned() || defun_scope.pinned()) + return statements; + var args; + var candidates = []; + var stat_index = statements.length; + var scanner = new TreeTransformer(function (node) { + if (abort) + return node; + // Skip nodes before `candidate` as quickly as possible + if (!hit) { + if (node !== hit_stack[hit_index]) + return node; + hit_index++; + if (hit_index < hit_stack.length) + return handle_custom_scan_order(node); + hit = true; + stop_after = find_stop(node, 0); + if (stop_after === node) + abort = true; + return node; + } + // Stop immediately if these node types are encountered + var parent = scanner.parent(); + if (node instanceof AST_Assign + && (node.logical || node.operator != "=" && lhs.equivalent_to(node.left)) + || node instanceof AST_Await + || node instanceof AST_Call && lhs instanceof AST_PropAccess && lhs.equivalent_to(node.expression) + || + (node instanceof AST_Call || node instanceof AST_PropAccess) + && node.optional + || node instanceof AST_Debugger + || node instanceof AST_Destructuring + || node instanceof AST_Expansion + && node.expression instanceof AST_Symbol + && ( + node.expression instanceof AST_This + || node.expression.definition().references.length > 1 + ) + || node instanceof AST_IterationStatement && !(node instanceof AST_For) + || node instanceof AST_LoopControl + || node instanceof AST_Try + || node instanceof AST_With + || node instanceof AST_Yield + || node instanceof AST_Export + || node instanceof AST_Class + || parent instanceof AST_For && node !== parent.init + || !replace_all + && ( + node instanceof AST_SymbolRef + && !node.is_declared(compressor) + && !pure_prop_access_globals.has(node) + ) + || node instanceof AST_SymbolRef + && parent instanceof AST_Call + && has_annotation(parent, _NOINLINE) + || node instanceof AST_ObjectProperty && node.key instanceof AST_Node + ) { + abort = true; + return node; + } + // Stop only if candidate is found within conditional branches + if (!stop_if_hit && (!lhs_local || !replace_all) + && (parent instanceof AST_Binary && lazy_op.has(parent.operator) && parent.left !== node + || parent instanceof AST_Conditional && parent.condition !== node + || parent instanceof AST_If && parent.condition !== node)) { + stop_if_hit = parent; + } + // Replace variable with assignment when found + if ( + can_replace + && !(node instanceof AST_SymbolDeclaration) + && lhs.equivalent_to(node) + && !shadows(scanner.find_scope() || nearest_scope, lvalues) + ) { + if (stop_if_hit) { + abort = true; + return node; + } + if (is_lhs(node, parent)) { + if (value_def) + replaced++; + return node; + } else { + replaced++; + if (value_def && candidate instanceof AST_VarDef) + return node; + } + CHANGED = abort = true; + if (candidate instanceof AST_UnaryPostfix) { + return make_node(AST_UnaryPrefix, candidate, candidate); + } + if (candidate instanceof AST_VarDef) { + var def = candidate.name.definition(); + var value = candidate.value; + if (def.references.length - def.replaced == 1 && !compressor.exposed(def)) { + def.replaced++; + if (funarg && is_identifier_atom(value)) { + return value.transform(compressor); + } else { + return maintain_this_binding(parent, node, value); + } + } + return make_node(AST_Assign, candidate, { + operator: "=", + logical: false, + left: make_node(AST_SymbolRef, candidate.name, candidate.name), + right: value + }); + } + clear_flag(candidate, WRITE_ONLY); + return candidate; + } + // These node types have child nodes that execute sequentially, + // but are otherwise not safe to scan into or beyond them. + var sym; + if (node instanceof AST_Call + || node instanceof AST_Exit + && (side_effects || lhs instanceof AST_PropAccess || may_modify(lhs)) + || node instanceof AST_PropAccess + && (side_effects || node.expression.may_throw_on_access(compressor)) + || node instanceof AST_SymbolRef + && ((lvalues.has(node.name) && lvalues.get(node.name).modified) || side_effects && may_modify(node)) + || node instanceof AST_VarDef && node.value + && (lvalues.has(node.name.name) || side_effects && may_modify(node.name)) + || (sym = is_lhs(node.left, node)) + && (sym instanceof AST_PropAccess || lvalues.has(sym.name)) + || may_throw + && (in_try ? node.has_side_effects(compressor) : side_effects_external(node))) { + stop_after = node; + if (node instanceof AST_Scope) + abort = true; + } + return handle_custom_scan_order(node); + }, function (node) { + if (abort) + return; + if (stop_after === node) + abort = true; + if (stop_if_hit === node) + stop_if_hit = null; + }); + + var multi_replacer = new TreeTransformer(function (node) { + if (abort) + return node; + // Skip nodes before `candidate` as quickly as possible + if (!hit) { + if (node !== hit_stack[hit_index]) + return node; + hit_index++; + if (hit_index < hit_stack.length) + return; + hit = true; + return node; + } + // Replace variable when found + if (node instanceof AST_SymbolRef + && node.name == def.name) { + if (!--replaced) + abort = true; + if (is_lhs(node, multi_replacer.parent())) + return node; + def.replaced++; + value_def.replaced--; + return candidate.value; + } + // Skip (non-executed) functions and (leading) default case in switch statements + if (node instanceof AST_Default || node instanceof AST_Scope) + return node; + }); + + while (--stat_index >= 0) { + // Treat parameters as collapsible in IIFE, i.e. + // function(a, b){ ... }(x()); + // would be translated into equivalent assignments: + // var a = x(), b = undefined; + if (stat_index == 0 && compressor.option("unused")) + extract_args(); + // Find collapsible assignments + var hit_stack = []; + extract_candidates(statements[stat_index]); + while (candidates.length > 0) { + hit_stack = candidates.pop(); + var hit_index = 0; + var candidate = hit_stack[hit_stack.length - 1]; + var value_def = null; + var stop_after = null; + var stop_if_hit = null; + var lhs = get_lhs(candidate); + if (!lhs || is_lhs_read_only(lhs) || lhs.has_side_effects(compressor)) + continue; + // Locate symbols which may execute code outside of scanning range + var lvalues = get_lvalues(candidate); + var lhs_local = is_lhs_local(lhs); + if (lhs instanceof AST_SymbolRef) { + lvalues.set(lhs.name, { def: lhs.definition(), modified: false }); + } + var side_effects = value_has_side_effects(candidate); + var replace_all = replace_all_symbols(); + var may_throw = candidate.may_throw(compressor); + var funarg = candidate.name instanceof AST_SymbolFunarg; + var hit = funarg; + var abort = false, replaced = 0, can_replace = !args || !hit; + if (!can_replace) { + for ( + let j = compressor.self().argnames.lastIndexOf(candidate.name) + 1; + !abort && j < args.length; + j++ + ) { + args[j].transform(scanner); + } + can_replace = true; + } + for (var i = stat_index; !abort && i < statements.length; i++) { + statements[i].transform(scanner); + } + if (value_def) { + var def = candidate.name.definition(); + if (abort && def.references.length - def.replaced > replaced) + replaced = false; + else { + abort = false; + hit_index = 0; + hit = funarg; + for (var i = stat_index; !abort && i < statements.length; i++) { + statements[i].transform(multi_replacer); + } + value_def.single_use = false; + } + } + if (replaced && !remove_candidate(candidate)) + statements.splice(stat_index, 1); + } + } + + function handle_custom_scan_order(node) { + // Skip (non-executed) functions + if (node instanceof AST_Scope) + return node; + + // Scan case expressions first in a switch statement + if (node instanceof AST_Switch) { + node.expression = node.expression.transform(scanner); + for (var i = 0, len = node.body.length; !abort && i < len; i++) { + var branch = node.body[i]; + if (branch instanceof AST_Case) { + if (!hit) { + if (branch !== hit_stack[hit_index]) + continue; + hit_index++; + } + branch.expression = branch.expression.transform(scanner); + if (!replace_all) + break; + } + } + abort = true; + return node; + } + } + + function redefined_within_scope(def, scope) { + if (def.global) + return false; + let cur_scope = def.scope; + while (cur_scope && cur_scope !== scope) { + if (cur_scope.variables.has(def.name)) { + return true; + } + cur_scope = cur_scope.parent_scope; + } + return false; + } + + function has_overlapping_symbol(fn, arg, fn_strict) { + var found = false, scan_this = !(fn instanceof AST_Arrow); + arg.walk(new TreeWalker(function (node, descend) { + if (found) + return true; + if (node instanceof AST_SymbolRef && (fn.variables.has(node.name) || redefined_within_scope(node.definition(), fn))) { + var s = node.definition().scope; + if (s !== defun_scope) + while (s = s.parent_scope) { + if (s === defun_scope) + return true; + } + return found = true; + } + if ((fn_strict || scan_this) && node instanceof AST_This) { + return found = true; + } + if (node instanceof AST_Scope && !(node instanceof AST_Arrow)) { + var prev = scan_this; + scan_this = false; + descend(); + scan_this = prev; + return true; + } + })); + return found; + } + + function arg_is_injectable(arg) { + if (arg instanceof AST_Expansion) return false; + const contains_await = walk(arg, (node) => { + if (node instanceof AST_Await) return walk_abort; + }); + if (contains_await) return false; + return true; + } + function extract_args() { + var iife, fn = compressor.self(); + if (is_func_expr(fn) + && !fn.name + && !fn.uses_arguments + && !fn.pinned() + && (iife = compressor.parent()) instanceof AST_Call + && iife.expression === fn + && iife.args.every(arg_is_injectable) + ) { + var fn_strict = compressor.has_directive("use strict"); + if (fn_strict && !member(fn_strict, fn.body)) + fn_strict = false; + var len = fn.argnames.length; + args = iife.args.slice(len); + var names = new Set(); + for (var i = len; --i >= 0;) { + var sym = fn.argnames[i]; + var arg = iife.args[i]; + // The following two line fix is a duplicate of the fix at + // https://github.com/terser/terser/commit/011d3eb08cefe6922c7d1bdfa113fc4aeaca1b75 + // This might mean that these two pieces of code (one here in collapse_vars and another in reduce_vars + // Might be doing the exact same thing. + const def = sym.definition && sym.definition(); + const is_reassigned = def && def.orig.length > 1; + if (is_reassigned) + continue; + args.unshift(make_node(AST_VarDef, sym, { + name: sym, + value: arg + })); + if (names.has(sym.name)) + continue; + names.add(sym.name); + if (sym instanceof AST_Expansion) { + var elements = iife.args.slice(i); + if (elements.every((arg) => !has_overlapping_symbol(fn, arg, fn_strict) + )) { + candidates.unshift([make_node(AST_VarDef, sym, { + name: sym.expression, + value: make_node(AST_Array, iife, { + elements: elements + }) + })]); + } + } else { + if (!arg) { + arg = make_node(AST_Undefined, sym).transform(compressor); + } else if (arg instanceof AST_Lambda && arg.pinned() + || has_overlapping_symbol(fn, arg, fn_strict)) { + arg = null; + } + if (arg) + candidates.unshift([make_node(AST_VarDef, sym, { + name: sym, + value: arg + })]); + } + } + } + } + + function extract_candidates(expr) { + hit_stack.push(expr); + if (expr instanceof AST_Assign) { + if (!expr.left.has_side_effects(compressor) + && !(expr.right instanceof AST_Chain)) { + candidates.push(hit_stack.slice()); + } + extract_candidates(expr.right); + } else if (expr instanceof AST_Binary) { + extract_candidates(expr.left); + extract_candidates(expr.right); + } else if (expr instanceof AST_Call && !has_annotation(expr, _NOINLINE)) { + extract_candidates(expr.expression); + expr.args.forEach(extract_candidates); + } else if (expr instanceof AST_Case) { + extract_candidates(expr.expression); + } else if (expr instanceof AST_Conditional) { + extract_candidates(expr.condition); + extract_candidates(expr.consequent); + extract_candidates(expr.alternative); + } else if (expr instanceof AST_Definitions) { + var len = expr.definitions.length; + // limit number of trailing variable definitions for consideration + var i = len - 200; + if (i < 0) + i = 0; + for (; i < len; i++) { + extract_candidates(expr.definitions[i]); + } + } else if (expr instanceof AST_DWLoop) { + extract_candidates(expr.condition); + if (!(expr.body instanceof AST_Block)) { + extract_candidates(expr.body); + } + } else if (expr instanceof AST_Exit) { + if (expr.value) + extract_candidates(expr.value); + } else if (expr instanceof AST_For) { + if (expr.init) + extract_candidates(expr.init); + if (expr.condition) + extract_candidates(expr.condition); + if (expr.step) + extract_candidates(expr.step); + if (!(expr.body instanceof AST_Block)) { + extract_candidates(expr.body); + } + } else if (expr instanceof AST_ForIn) { + extract_candidates(expr.object); + if (!(expr.body instanceof AST_Block)) { + extract_candidates(expr.body); + } + } else if (expr instanceof AST_If) { + extract_candidates(expr.condition); + if (!(expr.body instanceof AST_Block)) { + extract_candidates(expr.body); + } + if (expr.alternative && !(expr.alternative instanceof AST_Block)) { + extract_candidates(expr.alternative); + } + } else if (expr instanceof AST_Sequence) { + expr.expressions.forEach(extract_candidates); + } else if (expr instanceof AST_SimpleStatement) { + extract_candidates(expr.body); + } else if (expr instanceof AST_Switch) { + extract_candidates(expr.expression); + expr.body.forEach(extract_candidates); + } else if (expr instanceof AST_Unary) { + if (expr.operator == "++" || expr.operator == "--") { + candidates.push(hit_stack.slice()); + } + } else if (expr instanceof AST_VarDef) { + if (expr.value && !(expr.value instanceof AST_Chain)) { + candidates.push(hit_stack.slice()); + extract_candidates(expr.value); + } + } + hit_stack.pop(); + } + + function find_stop(node, level, write_only) { + var parent = scanner.parent(level); + if (parent instanceof AST_Assign) { + if (write_only + && !parent.logical + && !(parent.left instanceof AST_PropAccess + || lvalues.has(parent.left.name))) { + return find_stop(parent, level + 1, write_only); + } + return node; + } + if (parent instanceof AST_Binary) { + if (write_only && (!lazy_op.has(parent.operator) || parent.left === node)) { + return find_stop(parent, level + 1, write_only); + } + return node; + } + if (parent instanceof AST_Call) + return node; + if (parent instanceof AST_Case) + return node; + if (parent instanceof AST_Conditional) { + if (write_only && parent.condition === node) { + return find_stop(parent, level + 1, write_only); + } + return node; + } + if (parent instanceof AST_Definitions) { + return find_stop(parent, level + 1, true); + } + if (parent instanceof AST_Exit) { + return write_only ? find_stop(parent, level + 1, write_only) : node; + } + if (parent instanceof AST_If) { + if (write_only && parent.condition === node) { + return find_stop(parent, level + 1, write_only); + } + return node; + } + if (parent instanceof AST_IterationStatement) + return node; + if (parent instanceof AST_Sequence) { + return find_stop(parent, level + 1, parent.tail_node() !== node); + } + if (parent instanceof AST_SimpleStatement) { + return find_stop(parent, level + 1, true); + } + if (parent instanceof AST_Switch) + return node; + if (parent instanceof AST_VarDef) + return node; + return null; + } + + function mangleable_var(var_def) { + var value = var_def.value; + if (!(value instanceof AST_SymbolRef)) + return; + if (value.name == "arguments") + return; + var def = value.definition(); + if (def.undeclared) + return; + return value_def = def; + } + + function get_lhs(expr) { + if (expr instanceof AST_Assign && expr.logical) { + return false; + } else if (expr instanceof AST_VarDef && expr.name instanceof AST_SymbolDeclaration) { + var def = expr.name.definition(); + if (!member(expr.name, def.orig)) + return; + var referenced = def.references.length - def.replaced; + if (!referenced) + return; + var declared = def.orig.length - def.eliminated; + if (declared > 1 && !(expr.name instanceof AST_SymbolFunarg) + || (referenced > 1 ? mangleable_var(expr) : !compressor.exposed(def))) { + return make_node(AST_SymbolRef, expr.name, expr.name); + } + } else { + const lhs = expr instanceof AST_Assign + ? expr.left + : expr.expression; + return !is_ref_of(lhs, AST_SymbolConst) + && !is_ref_of(lhs, AST_SymbolLet) && lhs; + } + } + + function get_rvalue(expr) { + if (expr instanceof AST_Assign) { + return expr.right; + } else { + return expr.value; + } + } + + function get_lvalues(expr) { + var lvalues = new Map(); + if (expr instanceof AST_Unary) + return lvalues; + var tw = new TreeWalker(function (node) { + var sym = node; + while (sym instanceof AST_PropAccess) + sym = sym.expression; + if (sym instanceof AST_SymbolRef) { + const prev = lvalues.get(sym.name); + if (!prev || !prev.modified) { + lvalues.set(sym.name, { + def: sym.definition(), + modified: is_modified(compressor, tw, node, node, 0) + }); + } + } + }); + get_rvalue(expr).walk(tw); + return lvalues; + } + + function remove_candidate(expr) { + if (expr.name instanceof AST_SymbolFunarg) { + var iife = compressor.parent(), argnames = compressor.self().argnames; + var index = argnames.indexOf(expr.name); + if (index < 0) { + iife.args.length = Math.min(iife.args.length, argnames.length - 1); + } else { + var args = iife.args; + if (args[index]) + args[index] = make_node(AST_Number, args[index], { + value: 0 + }); + } + return true; + } + var found = false; + return statements[stat_index].transform(new TreeTransformer(function (node, descend, in_list) { + if (found) + return node; + if (node === expr || node.body === expr) { + found = true; + if (node instanceof AST_VarDef) { + node.value = node.name instanceof AST_SymbolConst + ? make_node(AST_Undefined, node.value) // `const` always needs value. + : null; + return node; + } + return in_list ? MAP.skip : null; + } + }, function (node) { + if (node instanceof AST_Sequence) + switch (node.expressions.length) { + case 0: return null; + case 1: return node.expressions[0]; + } + })); + } + + function is_lhs_local(lhs) { + while (lhs instanceof AST_PropAccess) + lhs = lhs.expression; + return lhs instanceof AST_SymbolRef + && lhs.definition().scope.get_defun_scope() === defun_scope + && !(in_loop + && (lvalues.has(lhs.name) + || candidate instanceof AST_Unary + || (candidate instanceof AST_Assign + && !candidate.logical + && candidate.operator != "="))); + } + + function value_has_side_effects(expr) { + if (expr instanceof AST_Unary) + return unary_side_effects.has(expr.operator); + return get_rvalue(expr).has_side_effects(compressor); + } + + function replace_all_symbols() { + if (side_effects) + return false; + if (value_def) + return true; + if (lhs instanceof AST_SymbolRef) { + var def = lhs.definition(); + if (def.references.length - def.replaced == (candidate instanceof AST_VarDef ? 1 : 2)) { + return true; + } + } + return false; + } + + function may_modify(sym) { + if (!sym.definition) + return true; // AST_Destructuring + var def = sym.definition(); + if (def.orig.length == 1 && def.orig[0] instanceof AST_SymbolDefun) + return false; + if (def.scope.get_defun_scope() !== defun_scope) + return true; + return def.references.some((ref) => + ref.scope.get_defun_scope() !== defun_scope + ); + } + + function side_effects_external(node, lhs) { + if (node instanceof AST_Assign) + return side_effects_external(node.left, true); + if (node instanceof AST_Unary) + return side_effects_external(node.expression, true); + if (node instanceof AST_VarDef) + return node.value && side_effects_external(node.value); + if (lhs) { + if (node instanceof AST_Dot) + return side_effects_external(node.expression, true); + if (node instanceof AST_Sub) + return side_effects_external(node.expression, true); + if (node instanceof AST_SymbolRef) + return node.definition().scope.get_defun_scope() !== defun_scope; + } + return false; + } + + /** + * Will any of the pulled-in lvalues shadow a variable in newScope or parents? + * similar to scope_encloses_variables_in_this_scope */ + function shadows(my_scope, lvalues) { + for (const { def } of lvalues.values()) { + const looked_up = my_scope.find_variable(def.name); + if (looked_up) { + if (looked_up === def) continue; + return true; + } + } + return false; + } + } + + function eliminate_spurious_blocks(statements) { + var seen_dirs = []; + for (var i = 0; i < statements.length;) { + var stat = statements[i]; + if (stat instanceof AST_BlockStatement && stat.body.every(can_be_evicted_from_block)) { + CHANGED = true; + eliminate_spurious_blocks(stat.body); + statements.splice(i, 1, ...stat.body); + i += stat.body.length; + } else if (stat instanceof AST_EmptyStatement) { + CHANGED = true; + statements.splice(i, 1); + } else if (stat instanceof AST_Directive) { + if (seen_dirs.indexOf(stat.value) < 0) { + i++; + seen_dirs.push(stat.value); + } else { + CHANGED = true; + statements.splice(i, 1); + } + } else + i++; + } + } + + function handle_if_return(statements, compressor) { + var self = compressor.self(); + var multiple_if_returns = has_multiple_if_returns(statements); + var in_lambda = self instanceof AST_Lambda; + // Prevent extremely deep nesting + // https://github.com/terser/terser/issues/1432 + // https://github.com/webpack/webpack/issues/17548 + const iteration_start = Math.min(statements.length, 500); + for (var i = iteration_start; --i >= 0;) { + var stat = statements[i]; + var j = next_index(i); + var next = statements[j]; + + if (in_lambda && !next && stat instanceof AST_Return) { + if (!stat.value) { + CHANGED = true; + statements.splice(i, 1); + continue; + } + if (stat.value instanceof AST_UnaryPrefix && stat.value.operator == "void") { + CHANGED = true; + statements[i] = make_node(AST_SimpleStatement, stat, { + body: stat.value.expression + }); + continue; + } + } + + if (stat instanceof AST_If) { + let ab, new_else; + + ab = aborts(stat.body); + if ( + can_merge_flow(ab) + && (new_else = as_statement_array_with_return(stat.body, ab)) + ) { + if (ab.label) { + remove(ab.label.thedef.references, ab); + } + CHANGED = true; + stat = stat.clone(); + stat.condition = stat.condition.negate(compressor); + stat.body = make_node(AST_BlockStatement, stat, { + body: as_statement_array(stat.alternative).concat(extract_functions()) + }); + stat.alternative = make_node(AST_BlockStatement, stat, { + body: new_else + }); + statements[i] = stat.transform(compressor); + continue; + } + + ab = aborts(stat.alternative); + if ( + can_merge_flow(ab) + && (new_else = as_statement_array_with_return(stat.alternative, ab)) + ) { + if (ab.label) { + remove(ab.label.thedef.references, ab); + } + CHANGED = true; + stat = stat.clone(); + stat.body = make_node(AST_BlockStatement, stat.body, { + body: as_statement_array(stat.body).concat(extract_functions()) + }); + stat.alternative = make_node(AST_BlockStatement, stat.alternative, { + body: new_else + }); + statements[i] = stat.transform(compressor); + continue; + } + } + + if (stat instanceof AST_If && stat.body instanceof AST_Return) { + var value = stat.body.value; + //--- + // pretty silly case, but: + // if (foo()) return; return; ==> foo(); return; + if (!value && !stat.alternative + && (in_lambda && !next || next instanceof AST_Return && !next.value)) { + CHANGED = true; + statements[i] = make_node(AST_SimpleStatement, stat.condition, { + body: stat.condition + }); + continue; + } + //--- + // if (foo()) return x; return y; ==> return foo() ? x : y; + if (value && !stat.alternative && next instanceof AST_Return && next.value) { + CHANGED = true; + stat = stat.clone(); + stat.alternative = next; + statements[i] = stat.transform(compressor); + statements.splice(j, 1); + continue; + } + //--- + // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined; + if (value && !stat.alternative + && (!next && in_lambda && multiple_if_returns + || next instanceof AST_Return)) { + CHANGED = true; + stat = stat.clone(); + stat.alternative = next || make_node(AST_Return, stat, { + value: null + }); + statements[i] = stat.transform(compressor); + if (next) + statements.splice(j, 1); + continue; + } + //--- + // if (a) return b; if (c) return d; e; ==> return a ? b : c ? d : void e; + // + // if sequences is not enabled, this can lead to an endless loop (issue #866). + // however, with sequences on this helps producing slightly better output for + // the example code. + var prev = statements[prev_index(i)]; + if (compressor.option("sequences") && in_lambda && !stat.alternative + && prev instanceof AST_If && prev.body instanceof AST_Return + && next_index(j) == statements.length && next instanceof AST_SimpleStatement) { + CHANGED = true; + stat = stat.clone(); + stat.alternative = make_node(AST_BlockStatement, next, { + body: [ + next, + make_node(AST_Return, next, { + value: null + }) + ] + }); + statements[i] = stat.transform(compressor); + statements.splice(j, 1); + continue; + } + } + } + + function has_multiple_if_returns(statements) { + var n = 0; + for (var i = statements.length; --i >= 0;) { + var stat = statements[i]; + if (stat instanceof AST_If && stat.body instanceof AST_Return) { + if (++n > 1) + return true; + } + } + return false; + } + + function is_return_void(value) { + return !value || value instanceof AST_UnaryPrefix && value.operator == "void"; + } + + function can_merge_flow(ab) { + if (!ab) + return false; + for (var j = i + 1, len = statements.length; j < len; j++) { + var stat = statements[j]; + if (stat instanceof AST_Const || stat instanceof AST_Let) + return false; + } + var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab) : null; + return ab instanceof AST_Return && in_lambda && is_return_void(ab.value) + || ab instanceof AST_Continue && self === loop_body(lct) + || ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct; + } + + function extract_functions() { + var tail = statements.slice(i + 1); + statements.length = i + 1; + return tail.filter(function (stat) { + if (stat instanceof AST_Defun) { + statements.push(stat); + return false; + } + return true; + }); + } + + function as_statement_array_with_return(node, ab) { + var body = as_statement_array(node); + if (ab !== body[body.length - 1]) { + return undefined; + } + body = body.slice(0, -1); + if (ab.value) { + body.push(make_node(AST_SimpleStatement, ab.value, { + body: ab.value.expression + })); + } + return body; + } + + function next_index(i) { + for (var j = i + 1, len = statements.length; j < len; j++) { + var stat = statements[j]; + if (!(stat instanceof AST_Var && declarations_only(stat))) { + break; + } + } + return j; + } + + function prev_index(i) { + for (var j = i; --j >= 0;) { + var stat = statements[j]; + if (!(stat instanceof AST_Var && declarations_only(stat))) { + break; + } + } + return j; + } + } + + function eliminate_dead_code(statements, compressor) { + var has_quit; + var self = compressor.self(); + for (var i = 0, n = 0, len = statements.length; i < len; i++) { + var stat = statements[i]; + if (stat instanceof AST_LoopControl) { + var lct = compressor.loopcontrol_target(stat); + if (stat instanceof AST_Break + && !(lct instanceof AST_IterationStatement) + && loop_body(lct) === self + || stat instanceof AST_Continue + && loop_body(lct) === self) { + if (stat.label) { + remove(stat.label.thedef.references, stat); + } + } else { + statements[n++] = stat; + } + } else { + statements[n++] = stat; + } + if (aborts(stat)) { + has_quit = statements.slice(i + 1); + break; + } + } + statements.length = n; + CHANGED = n != len; + if (has_quit) + has_quit.forEach(function (stat) { + trim_unreachable_code(compressor, stat, statements); + }); + } + + function declarations_only(node) { + return node.definitions.every((var_def) => !var_def.value); + } + + function sequencesize(statements, compressor) { + if (statements.length < 2) + return; + var seq = [], n = 0; + function push_seq() { + if (!seq.length) + return; + var body = make_sequence(seq[0], seq); + statements[n++] = make_node(AST_SimpleStatement, body, { body: body }); + seq = []; + } + for (var i = 0, len = statements.length; i < len; i++) { + var stat = statements[i]; + if (stat instanceof AST_SimpleStatement) { + if (seq.length >= compressor.sequences_limit) + push_seq(); + var body = stat.body; + if (seq.length > 0) + body = body.drop_side_effect_free(compressor); + if (body) + merge_sequence(seq, body); + } else if (stat instanceof AST_Definitions && declarations_only(stat) + || stat instanceof AST_Defun) { + statements[n++] = stat; + } else { + push_seq(); + statements[n++] = stat; + } + } + push_seq(); + statements.length = n; + if (n != len) + CHANGED = true; + } + + function to_simple_statement(block, decls) { + if (!(block instanceof AST_BlockStatement)) + return block; + var stat = null; + for (var i = 0, len = block.body.length; i < len; i++) { + var line = block.body[i]; + if (line instanceof AST_Var && declarations_only(line)) { + decls.push(line); + } else if (stat || line instanceof AST_Const || line instanceof AST_Let) { + return false; + } else { + stat = line; + } + } + return stat; + } + + function sequencesize_2(statements, compressor) { + function cons_seq(right) { + n--; + CHANGED = true; + var left = prev.body; + return make_sequence(left, [left, right]).transform(compressor); + } + var n = 0, prev; + for (var i = 0; i < statements.length; i++) { + var stat = statements[i]; + if (prev) { + if (stat instanceof AST_Exit) { + stat.value = cons_seq(stat.value || make_node(AST_Undefined, stat).transform(compressor)); + } else if (stat instanceof AST_For) { + if (!(stat.init instanceof AST_Definitions)) { + const abort = walk(prev.body, node => { + if (node instanceof AST_Scope) + return true; + if (node instanceof AST_Binary + && node.operator === "in") { + return walk_abort; + } + }); + if (!abort) { + if (stat.init) + stat.init = cons_seq(stat.init); + else { + stat.init = prev.body; + n--; + CHANGED = true; + } + } + } + } else if (stat instanceof AST_ForIn) { + if (!(stat.init instanceof AST_Const) && !(stat.init instanceof AST_Let)) { + stat.object = cons_seq(stat.object); + } + } else if (stat instanceof AST_If) { + stat.condition = cons_seq(stat.condition); + } else if (stat instanceof AST_Switch) { + stat.expression = cons_seq(stat.expression); + } else if (stat instanceof AST_With) { + stat.expression = cons_seq(stat.expression); + } + } + if (compressor.option("conditionals") && stat instanceof AST_If) { + var decls = []; + var body = to_simple_statement(stat.body, decls); + var alt = to_simple_statement(stat.alternative, decls); + if (body !== false && alt !== false && decls.length > 0) { + var len = decls.length; + decls.push(make_node(AST_If, stat, { + condition: stat.condition, + body: body || make_node(AST_EmptyStatement, stat.body), + alternative: alt + })); + decls.unshift(n, 1); + [].splice.apply(statements, decls); + i += len; + n += len + 1; + prev = null; + CHANGED = true; + continue; + } + } + statements[n++] = stat; + prev = stat instanceof AST_SimpleStatement ? stat : null; + } + statements.length = n; + } + + function join_object_assignments(defn, body) { + if (!(defn instanceof AST_Definitions)) + return; + var def = defn.definitions[defn.definitions.length - 1]; + if (!(def.value instanceof AST_Object)) + return; + var exprs; + if (body instanceof AST_Assign && !body.logical) { + exprs = [body]; + } else if (body instanceof AST_Sequence) { + exprs = body.expressions.slice(); + } + if (!exprs) + return; + var trimmed = false; + do { + var node = exprs[0]; + if (!(node instanceof AST_Assign)) + break; + if (node.operator != "=") + break; + if (!(node.left instanceof AST_PropAccess)) + break; + var sym = node.left.expression; + if (!(sym instanceof AST_SymbolRef)) + break; + if (def.name.name != sym.name) + break; + if (!node.right.is_constant_expression(nearest_scope)) + break; + var prop = node.left.property; + if (prop instanceof AST_Node) { + prop = prop.evaluate(compressor); + } + if (prop instanceof AST_Node) + break; + prop = "" + prop; + var diff = compressor.option("ecma") < 2015 + && compressor.has_directive("use strict") ? function (node) { + return node.key != prop && (node.key && node.key.name != prop); + } : function (node) { + return node.key && node.key.name != prop; + }; + if (!def.value.properties.every(diff)) + break; + var p = def.value.properties.filter(function (p) { return p.key === prop; })[0]; + if (!p) { + def.value.properties.push(make_node(AST_ObjectKeyVal, node, { + key: prop, + value: node.right + })); + } else { + p.value = new AST_Sequence({ + start: p.start, + expressions: [p.value.clone(), node.right.clone()], + end: p.end + }); + } + exprs.shift(); + trimmed = true; + } while (exprs.length); + return trimmed && exprs; + } + + function join_consecutive_vars(statements) { + var defs; + for (var i = 0, j = -1, len = statements.length; i < len; i++) { + var stat = statements[i]; + var prev = statements[j]; + if (stat instanceof AST_Definitions) { + if (prev && prev.TYPE == stat.TYPE) { + prev.definitions = prev.definitions.concat(stat.definitions); + CHANGED = true; + } else if (defs && defs.TYPE == stat.TYPE && declarations_only(stat)) { + defs.definitions = defs.definitions.concat(stat.definitions); + CHANGED = true; + } else { + statements[++j] = stat; + defs = stat; + } + } else if (stat instanceof AST_Exit) { + stat.value = extract_object_assignments(stat.value); + } else if (stat instanceof AST_For) { + var exprs = join_object_assignments(prev, stat.init); + if (exprs) { + CHANGED = true; + stat.init = exprs.length ? make_sequence(stat.init, exprs) : null; + statements[++j] = stat; + } else if ( + prev instanceof AST_Var + && (!stat.init || stat.init.TYPE == prev.TYPE) + ) { + if (stat.init) { + prev.definitions = prev.definitions.concat(stat.init.definitions); + } + stat.init = prev; + statements[j] = stat; + CHANGED = true; + } else if ( + defs instanceof AST_Var + && stat.init instanceof AST_Var + && declarations_only(stat.init) + ) { + defs.definitions = defs.definitions.concat(stat.init.definitions); + stat.init = null; + statements[++j] = stat; + CHANGED = true; + } else { + statements[++j] = stat; + } + } else if (stat instanceof AST_ForIn) { + stat.object = extract_object_assignments(stat.object); + } else if (stat instanceof AST_If) { + stat.condition = extract_object_assignments(stat.condition); + } else if (stat instanceof AST_SimpleStatement) { + var exprs = join_object_assignments(prev, stat.body); + if (exprs) { + CHANGED = true; + if (!exprs.length) + continue; + stat.body = make_sequence(stat.body, exprs); + } + statements[++j] = stat; + } else if (stat instanceof AST_Switch) { + stat.expression = extract_object_assignments(stat.expression); + } else if (stat instanceof AST_With) { + stat.expression = extract_object_assignments(stat.expression); + } else { + statements[++j] = stat; + } + } + statements.length = j + 1; + + function extract_object_assignments(value) { + statements[++j] = stat; + var exprs = join_object_assignments(prev, value); + if (exprs) { + CHANGED = true; + if (exprs.length) { + return make_sequence(value, exprs); + } else if (value instanceof AST_Sequence) { + return value.tail_node().left; + } else { + return value.left; + } + } + return value; + } + } +} + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +/** + * Module that contains the inlining logic. + * + * @module + * + * The stars of the show are `inline_into_symbolref` and `inline_into_call`. + */ + +function within_array_or_object_literal(compressor) { + var node, level = 0; + while (node = compressor.parent(level++)) { + if (node instanceof AST_Statement) return false; + if (node instanceof AST_Array + || node instanceof AST_ObjectKeyVal + || node instanceof AST_Object) { + return true; + } + } + return false; +} + +function scope_encloses_variables_in_this_scope(scope, pulled_scope) { + for (const enclosed of pulled_scope.enclosed) { + if (pulled_scope.variables.has(enclosed.name)) { + continue; + } + const looked_up = scope.find_variable(enclosed.name); + if (looked_up) { + if (looked_up === enclosed) continue; + return true; + } + } + return false; +} + +/** + * An extra check function for `top_retain` option, compare the length of const identifier + * and init value length and return true if init value is longer than identifier. for example: + * ``` + * // top_retain: ["example"] + * const example = 100 + * ``` + * it will return false because length of "100" is short than identifier "example". + */ +function is_const_symbol_short_than_init_value(def, fixed_value) { + if (def.orig.length === 1 && fixed_value) { + const init_value_length = fixed_value.size(); + const identifer_length = def.name.length; + return init_value_length > identifer_length; + } + return true; +} + +function inline_into_symbolref(self, compressor) { + if (compressor.in_computed_key()) return self; + + const parent = compressor.parent(); + const def = self.definition(); + const nearest_scope = compressor.find_scope(); + let fixed = self.fixed_value(); + if ( + compressor.top_retain && + def.global && + compressor.top_retain(def) && + // when identifier is in top_retain option dose not mean we can always inline it. + // if identifier name is longer then init value, we can replace it. + is_const_symbol_short_than_init_value(def, fixed) + ) { + // keep it + def.fixed = false; + def.single_use = false; + return self; + } + + let single_use = def.single_use + && !(parent instanceof AST_Call + && (parent.is_callee_pure(compressor)) + || has_annotation(parent, _NOINLINE)) + && !(parent instanceof AST_Export + && fixed instanceof AST_Lambda + && fixed.name); + + if (single_use && fixed instanceof AST_Node) { + single_use = + !fixed.has_side_effects(compressor) + && !fixed.may_throw(compressor); + } + + if (fixed instanceof AST_Class && def.scope !== self.scope) { + return self; + } + + if (single_use && (fixed instanceof AST_Lambda || fixed instanceof AST_Class)) { + if (retain_top_func(fixed, compressor)) { + single_use = false; + } else if (def.scope !== self.scope + && (def.escaped == 1 + || has_flag(fixed, INLINED) + || within_array_or_object_literal(compressor) + || !compressor.option("reduce_funcs"))) { + single_use = false; + } else if (is_recursive_ref(compressor, def)) { + single_use = false; + } else if (def.scope !== self.scope || def.orig[0] instanceof AST_SymbolFunarg) { + single_use = fixed.is_constant_expression(self.scope); + if (single_use == "f") { + var scope = self.scope; + do { + if (scope instanceof AST_Defun || is_func_expr(scope)) { + set_flag(scope, INLINED); + } + } while (scope = scope.parent_scope); + } + } + } + + if (single_use && (fixed instanceof AST_Lambda || fixed instanceof AST_Class)) { + single_use = + def.scope === self.scope + && !scope_encloses_variables_in_this_scope(nearest_scope, fixed) + || parent instanceof AST_Call + && parent.expression === self + && !scope_encloses_variables_in_this_scope(nearest_scope, fixed) + && !(fixed.name && fixed.name.definition().recursive_refs > 0); + } + + if (single_use && fixed) { + if (fixed instanceof AST_DefClass) { + set_flag(fixed, SQUEEZED); + fixed = make_node(AST_ClassExpression, fixed, fixed); + } + if (fixed instanceof AST_Defun) { + set_flag(fixed, SQUEEZED); + fixed = make_node(AST_Function, fixed, fixed); + } + if (def.recursive_refs > 0 && fixed.name instanceof AST_SymbolDefun) { + const defun_def = fixed.name.definition(); + let lambda_def = fixed.variables.get(fixed.name.name); + let name = lambda_def && lambda_def.orig[0]; + if (!(name instanceof AST_SymbolLambda)) { + name = make_node(AST_SymbolLambda, fixed.name, fixed.name); + name.scope = fixed; + fixed.name = name; + lambda_def = fixed.def_function(name); + } + walk(fixed, node => { + if (node instanceof AST_SymbolRef && node.definition() === defun_def) { + node.thedef = lambda_def; + lambda_def.references.push(node); + } + }); + } + if ( + (fixed instanceof AST_Lambda || fixed instanceof AST_Class) + && fixed.parent_scope !== nearest_scope + ) { + fixed = fixed.clone(true, compressor.get_toplevel()); + + nearest_scope.add_child_scope(fixed); + } + return fixed.optimize(compressor); + } + + // multiple uses + if (fixed) { + let replace; + + if (fixed instanceof AST_This) { + if (!(def.orig[0] instanceof AST_SymbolFunarg) + && def.references.every((ref) => + def.scope === ref.scope + )) { + replace = fixed; + } + } else { + var ev = fixed.evaluate(compressor); + if ( + ev !== fixed + && (compressor.option("unsafe_regexp") || !(ev instanceof RegExp)) + ) { + replace = make_node_from_constant(ev, fixed); + } + } + + if (replace) { + const name_length = self.size(compressor); + const replace_size = replace.size(compressor); + + let overhead = 0; + if (compressor.option("unused") && !compressor.exposed(def)) { + overhead = + (name_length + 2 + fixed.size(compressor)) / + (def.references.length - def.assignments); + } + + if (replace_size <= name_length + overhead) { + return replace; + } + } + } + + return self; +} + +function inline_into_call(self, compressor) { + if (compressor.in_computed_key()) return self; + + var exp = self.expression; + var fn = exp; + var simple_args = self.args.every((arg) => !(arg instanceof AST_Expansion)); + + if (compressor.option("reduce_vars") + && fn instanceof AST_SymbolRef + && !has_annotation(self, _NOINLINE) + ) { + const fixed = fn.fixed_value(); + + if ( + retain_top_func(fixed, compressor) + || !compressor.toplevel.funcs && exp.definition().global + ) { + return self; + } + + fn = fixed; + } + + var is_func = fn instanceof AST_Lambda; + + var stat = is_func && fn.body[0]; + var is_regular_func = is_func && !fn.is_generator && !fn.async; + var can_inline = is_regular_func && compressor.option("inline") && !self.is_callee_pure(compressor); + if (can_inline && stat instanceof AST_Return) { + let returned = stat.value; + if (!returned || returned.is_constant_expression()) { + if (returned) { + returned = returned.clone(true); + } else { + returned = make_node(AST_Undefined, self); + } + const args = self.args.concat(returned); + return make_sequence(self, args).optimize(compressor); + } + + // optimize identity function + if ( + fn.argnames.length === 1 + && (fn.argnames[0] instanceof AST_SymbolFunarg) + && self.args.length < 2 + && !(self.args[0] instanceof AST_Expansion) + && returned instanceof AST_SymbolRef + && returned.name === fn.argnames[0].name + ) { + const replacement = + (self.args[0] || make_node(AST_Undefined)).optimize(compressor); + + let parent; + if ( + replacement instanceof AST_PropAccess + && (parent = compressor.parent()) instanceof AST_Call + && parent.expression === self + ) { + // identity function was being used to remove `this`, like in + // + // id(bag.no_this)(...) + // + // Replace with a larger but more effish (0, bag.no_this) wrapper. + + return make_sequence(self, [ + make_node(AST_Number, self, { value: 0 }), + replacement + ]); + } + // replace call with first argument or undefined if none passed + return replacement; + } + } + + if (can_inline) { + var scope, in_loop, level = -1; + let def; + let returned_value; + let nearest_scope; + if (simple_args + && !fn.uses_arguments + && !(compressor.parent() instanceof AST_Class) + && !(fn.name && fn instanceof AST_Function) + && (returned_value = can_flatten_body(stat)) + && (exp === fn + || has_annotation(self, _INLINE) + || compressor.option("unused") + && (def = exp.definition()).references.length == 1 + && !is_recursive_ref(compressor, def) + && fn.is_constant_expression(exp.scope)) + && !has_annotation(self, _PURE | _NOINLINE) + && !fn.contains_this() + && can_inject_symbols() + && (nearest_scope = compressor.find_scope()) + && !scope_encloses_variables_in_this_scope(nearest_scope, fn) + && !(function in_default_assign() { + // Due to the fact function parameters have their own scope + // which can't use `var something` in the function body within, + // we simply don't inline into DefaultAssign. + let i = 0; + let p; + while ((p = compressor.parent(i++))) { + if (p instanceof AST_DefaultAssign) return true; + if (p instanceof AST_Block) break; + } + return false; + })() + && !(scope instanceof AST_Class) + ) { + set_flag(fn, SQUEEZED); + nearest_scope.add_child_scope(fn); + return make_sequence(self, flatten_fn(returned_value)).optimize(compressor); + } + } + + if (can_inline && has_annotation(self, _INLINE)) { + set_flag(fn, SQUEEZED); + fn = make_node(fn.CTOR === AST_Defun ? AST_Function : fn.CTOR, fn, fn); + fn = fn.clone(true); + fn.figure_out_scope({}, { + parent_scope: compressor.find_scope(), + toplevel: compressor.get_toplevel() + }); + + return make_node(AST_Call, self, { + expression: fn, + args: self.args, + }).optimize(compressor); + } + + const can_drop_this_call = is_regular_func && compressor.option("side_effects") && fn.body.every(is_empty); + if (can_drop_this_call) { + var args = self.args.concat(make_node(AST_Undefined, self)); + return make_sequence(self, args).optimize(compressor); + } + + if (compressor.option("negate_iife") + && compressor.parent() instanceof AST_SimpleStatement + && is_iife_call(self)) { + return self.negate(compressor, true); + } + + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + + return self; + + function return_value(stat) { + if (!stat) return make_node(AST_Undefined, self); + if (stat instanceof AST_Return) { + if (!stat.value) return make_node(AST_Undefined, self); + return stat.value.clone(true); + } + if (stat instanceof AST_SimpleStatement) { + return make_node(AST_UnaryPrefix, stat, { + operator: "void", + expression: stat.body.clone(true) + }); + } + } + + function can_flatten_body(stat) { + var body = fn.body; + var len = body.length; + if (compressor.option("inline") < 3) { + return len == 1 && return_value(stat); + } + stat = null; + for (var i = 0; i < len; i++) { + var line = body[i]; + if (line instanceof AST_Var) { + if (stat && !line.definitions.every((var_def) => + !var_def.value + )) { + return false; + } + } else if (stat) { + return false; + } else if (!(line instanceof AST_EmptyStatement)) { + stat = line; + } + } + return return_value(stat); + } + + function can_inject_args(block_scoped, safe_to_inject) { + for (var i = 0, len = fn.argnames.length; i < len; i++) { + var arg = fn.argnames[i]; + if (arg instanceof AST_DefaultAssign) { + if (has_flag(arg.left, UNUSED)) continue; + return false; + } + if (arg instanceof AST_Destructuring) return false; + if (arg instanceof AST_Expansion) { + if (has_flag(arg.expression, UNUSED)) continue; + return false; + } + if (has_flag(arg, UNUSED)) continue; + if (!safe_to_inject + || block_scoped.has(arg.name) + || identifier_atom.has(arg.name) + || scope.conflicting_def(arg.name)) { + return false; + } + if (in_loop) in_loop.push(arg.definition()); + } + return true; + } + + function can_inject_vars(block_scoped, safe_to_inject) { + var len = fn.body.length; + for (var i = 0; i < len; i++) { + var stat = fn.body[i]; + if (!(stat instanceof AST_Var)) continue; + if (!safe_to_inject) return false; + for (var j = stat.definitions.length; --j >= 0;) { + var name = stat.definitions[j].name; + if (name instanceof AST_Destructuring + || block_scoped.has(name.name) + || identifier_atom.has(name.name) + || scope.conflicting_def(name.name)) { + return false; + } + if (in_loop) in_loop.push(name.definition()); + } + } + return true; + } + + function can_inject_symbols() { + var block_scoped = new Set(); + do { + scope = compressor.parent(++level); + if (scope.is_block_scope() && scope.block_scope) { + // TODO this is sometimes undefined during compression. + // But it should always have a value! + scope.block_scope.variables.forEach(function (variable) { + block_scoped.add(variable.name); + }); + } + if (scope instanceof AST_Catch) { + // TODO can we delete? AST_Catch is a block scope. + if (scope.argname) { + block_scoped.add(scope.argname.name); + } + } else if (scope instanceof AST_IterationStatement) { + in_loop = []; + } else if (scope instanceof AST_SymbolRef) { + if (scope.fixed_value() instanceof AST_Scope) return false; + } + } while (!(scope instanceof AST_Scope)); + + var safe_to_inject = !(scope instanceof AST_Toplevel) || compressor.toplevel.vars; + var inline = compressor.option("inline"); + if (!can_inject_vars(block_scoped, inline >= 3 && safe_to_inject)) return false; + if (!can_inject_args(block_scoped, inline >= 2 && safe_to_inject)) return false; + return !in_loop || in_loop.length == 0 || !is_reachable(fn, in_loop); + } + + function append_var(decls, expressions, name, value) { + var def = name.definition(); + + // Name already exists, only when a function argument had the same name + const already_appended = scope.variables.has(name.name); + if (!already_appended) { + scope.variables.set(name.name, def); + scope.enclosed.push(def); + decls.push(make_node(AST_VarDef, name, { + name: name, + value: null + })); + } + + var sym = make_node(AST_SymbolRef, name, name); + def.references.push(sym); + if (value) expressions.push(make_node(AST_Assign, self, { + operator: "=", + logical: false, + left: sym, + right: value.clone() + })); + } + + function flatten_args(decls, expressions) { + var len = fn.argnames.length; + for (var i = self.args.length; --i >= len;) { + expressions.push(self.args[i]); + } + for (i = len; --i >= 0;) { + var name = fn.argnames[i]; + var value = self.args[i]; + if (has_flag(name, UNUSED) || !name.name || scope.conflicting_def(name.name)) { + if (value) expressions.push(value); + } else { + var symbol = make_node(AST_SymbolVar, name, name); + name.definition().orig.push(symbol); + if (!value && in_loop) value = make_node(AST_Undefined, self); + append_var(decls, expressions, symbol, value); + } + } + decls.reverse(); + expressions.reverse(); + } + + function flatten_vars(decls, expressions) { + var pos = expressions.length; + for (var i = 0, lines = fn.body.length; i < lines; i++) { + var stat = fn.body[i]; + if (!(stat instanceof AST_Var)) continue; + for (var j = 0, defs = stat.definitions.length; j < defs; j++) { + var var_def = stat.definitions[j]; + var name = var_def.name; + append_var(decls, expressions, name, var_def.value); + if (in_loop && fn.argnames.every((argname) => + argname.name != name.name + )) { + var def = fn.variables.get(name.name); + var sym = make_node(AST_SymbolRef, name, name); + def.references.push(sym); + expressions.splice(pos++, 0, make_node(AST_Assign, var_def, { + operator: "=", + logical: false, + left: sym, + right: make_node(AST_Undefined, name) + })); + } + } + } + } + + function flatten_fn(returned_value) { + var decls = []; + var expressions = []; + flatten_args(decls, expressions); + flatten_vars(decls, expressions); + expressions.push(returned_value); + + if (decls.length) { + const i = scope.body.indexOf(compressor.parent(level - 1)) + 1; + scope.body.splice(i, 0, make_node(AST_Var, fn, { + definitions: decls + })); + } + + return expressions.map(exp => exp.clone(true)); + } +} + +(function(def_find_defs) { + function to_node(value, orig) { + if (value instanceof AST_Node) { + if (!(value instanceof AST_Constant)) { + // Value may be a function, an array including functions and even a complex assign / block expression, + // so it should never be shared in different places. + // Otherwise wrong information may be used in the compression phase + value = value.clone(true); + } + return make_node(value.CTOR, orig, value); + } + if (Array.isArray(value)) return make_node(AST_Array, orig, { + elements: value.map(function(value) { + return to_node(value, orig); + }) + }); + if (value && typeof value == "object") { + var props = []; + for (var key in value) if (HOP(value, key)) { + props.push(make_node(AST_ObjectKeyVal, orig, { + key: key, + value: to_node(value[key], orig) + })); + } + return make_node(AST_Object, orig, { + properties: props + }); + } + return make_node_from_constant(value, orig); + } + + AST_Toplevel.DEFMETHOD("resolve_defines", function(compressor) { + if (!compressor.option("global_defs")) return this; + this.figure_out_scope({ ie8: compressor.option("ie8") }); + return this.transform(new TreeTransformer(function(node) { + var def = node._find_defs(compressor, ""); + if (!def) return; + var level = 0, child = node, parent; + while (parent = this.parent(level++)) { + if (!(parent instanceof AST_PropAccess)) break; + if (parent.expression !== child) break; + child = parent; + } + if (is_lhs(child, parent)) { + return; + } + return def; + })); + }); + def_find_defs(AST_Node, noop); + def_find_defs(AST_Chain, function(compressor, suffix) { + return this.expression._find_defs(compressor, suffix); + }); + def_find_defs(AST_Dot, function(compressor, suffix) { + return this.expression._find_defs(compressor, "." + this.property + suffix); + }); + def_find_defs(AST_SymbolDeclaration, function() { + if (!this.global()) return; + }); + def_find_defs(AST_SymbolRef, function(compressor, suffix) { + if (!this.global()) return; + var defines = compressor.option("global_defs"); + var name = this.name + suffix; + if (HOP(defines, name)) return to_node(defines[name], this); + }); + def_find_defs(AST_ImportMeta, function(compressor, suffix) { + var defines = compressor.option("global_defs"); + var name = "import.meta" + suffix; + if (HOP(defines, name)) return to_node(defines[name], this); + }); +})(function(node, func) { + node.DEFMETHOD("_find_defs", func); +}); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +class Compressor extends TreeWalker { + constructor(options, { false_by_default = false, mangle_options = false }) { + super(); + if (options.defaults !== undefined && !options.defaults) false_by_default = true; + this.options = defaults(options, { + arguments : false, + arrows : !false_by_default, + booleans : !false_by_default, + booleans_as_integers : false, + collapse_vars : !false_by_default, + comparisons : !false_by_default, + computed_props: !false_by_default, + conditionals : !false_by_default, + dead_code : !false_by_default, + defaults : true, + directives : !false_by_default, + drop_console : false, + drop_debugger : !false_by_default, + ecma : 5, + evaluate : !false_by_default, + expression : false, + global_defs : false, + hoist_funs : false, + hoist_props : !false_by_default, + hoist_vars : false, + ie8 : false, + if_return : !false_by_default, + inline : !false_by_default, + join_vars : !false_by_default, + keep_classnames: false, + keep_fargs : true, + keep_fnames : false, + keep_infinity : false, + lhs_constants : !false_by_default, + loops : !false_by_default, + module : false, + negate_iife : !false_by_default, + passes : 1, + properties : !false_by_default, + pure_getters : !false_by_default && "strict", + pure_funcs : null, + pure_new : false, + reduce_funcs : !false_by_default, + reduce_vars : !false_by_default, + sequences : !false_by_default, + side_effects : !false_by_default, + switches : !false_by_default, + top_retain : null, + toplevel : !!(options && options["top_retain"]), + typeofs : !false_by_default, + unsafe : false, + unsafe_arrows : false, + unsafe_comps : false, + unsafe_Function: false, + unsafe_math : false, + unsafe_symbols: false, + unsafe_methods: false, + unsafe_proto : false, + unsafe_regexp : false, + unsafe_undefined: false, + unused : !false_by_default, + warnings : false // legacy + }, true); + var global_defs = this.options["global_defs"]; + if (typeof global_defs == "object") for (var key in global_defs) { + if (key[0] === "@" && HOP(global_defs, key)) { + global_defs[key.slice(1)] = parse(global_defs[key], { + expression: true + }); + } + } + if (this.options["inline"] === true) this.options["inline"] = 3; + var pure_funcs = this.options["pure_funcs"]; + if (typeof pure_funcs == "function") { + this.pure_funcs = pure_funcs; + } else { + this.pure_funcs = pure_funcs ? function(node) { + return !pure_funcs.includes(node.expression.print_to_string()); + } : return_true; + } + var top_retain = this.options["top_retain"]; + if (top_retain instanceof RegExp) { + this.top_retain = function(def) { + return top_retain.test(def.name); + }; + } else if (typeof top_retain == "function") { + this.top_retain = top_retain; + } else if (top_retain) { + if (typeof top_retain == "string") { + top_retain = top_retain.split(/,/); + } + this.top_retain = function(def) { + return top_retain.includes(def.name); + }; + } + if (this.options["module"]) { + this.directives["use strict"] = true; + this.options["toplevel"] = true; + } + var toplevel = this.options["toplevel"]; + this.toplevel = typeof toplevel == "string" ? { + funcs: /funcs/.test(toplevel), + vars: /vars/.test(toplevel) + } : { + funcs: toplevel, + vars: toplevel + }; + var sequences = this.options["sequences"]; + this.sequences_limit = sequences == 1 ? 800 : sequences | 0; + this.evaluated_regexps = new Map(); + this._toplevel = undefined; + this._mangle_options = mangle_options + ? format_mangler_options(mangle_options) + : mangle_options; + } + + mangle_options() { + var nth_identifier = this._mangle_options && this._mangle_options.nth_identifier || base54; + var module = this._mangle_options && this._mangle_options.module || this.option("module"); + return { ie8: this.option("ie8"), nth_identifier, module }; + } + + option(key) { + return this.options[key]; + } + + exposed(def) { + if (def.export) return true; + if (def.global) for (var i = 0, len = def.orig.length; i < len; i++) + if (!this.toplevel[def.orig[i] instanceof AST_SymbolDefun ? "funcs" : "vars"]) + return true; + return false; + } + + in_boolean_context() { + if (!this.option("booleans")) return false; + var self = this.self(); + for (var i = 0, p; p = this.parent(i); i++) { + if (p instanceof AST_SimpleStatement + || p instanceof AST_Conditional && p.condition === self + || p instanceof AST_DWLoop && p.condition === self + || p instanceof AST_For && p.condition === self + || p instanceof AST_If && p.condition === self + || p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self) { + return true; + } + if ( + p instanceof AST_Binary + && ( + p.operator == "&&" + || p.operator == "||" + || p.operator == "??" + ) + || p instanceof AST_Conditional + || p.tail_node() === self + ) { + self = p; + } else { + return false; + } + } + } + + in_32_bit_context() { + if (!this.option("evaluate")) return false; + var self = this.self(); + for (var i = 0, p; p = this.parent(i); i++) { + if (p instanceof AST_Binary && bitwise_binop.has(p.operator)) { + return true; + } + if (p instanceof AST_UnaryPrefix) { + return p.operator === "~"; + } + if ( + p instanceof AST_Binary + && ( + p.operator == "&&" + || p.operator == "||" + || p.operator == "??" + ) + || p instanceof AST_Conditional && p.condition !== self + || p.tail_node() === self + ) { + self = p; + } else { + return false; + } + } + } + + in_computed_key() { + if (!this.option("evaluate")) return false; + var self = this.self(); + for (var i = 0, p; p = this.parent(i); i++) { + if (p instanceof AST_ObjectProperty && p.key === self) { + return true; + } + } + return false; + } + + get_toplevel() { + return this._toplevel; + } + + compress(toplevel) { + toplevel = toplevel.resolve_defines(this); + this._toplevel = toplevel; + if (this.option("expression")) { + this._toplevel.process_expression(true); + } + var passes = +this.options.passes || 1; + var min_count = 1 / 0; + var stopping = false; + var mangle = this.mangle_options(); + for (var pass = 0; pass < passes; pass++) { + this._toplevel.figure_out_scope(mangle); + if (pass === 0 && this.option("drop_console")) { + // must be run before reduce_vars and compress pass + this._toplevel = this._toplevel.drop_console(this.option("drop_console")); + } + if (pass > 0 || this.option("reduce_vars")) { + this._toplevel.reset_opt_flags(this); + } + this._toplevel = this._toplevel.transform(this); + if (passes > 1) { + let count = 0; + walk(this._toplevel, () => { count++; }); + if (count < min_count) { + min_count = count; + stopping = false; + } else if (stopping) { + break; + } else { + stopping = true; + } + } + } + if (this.option("expression")) { + this._toplevel.process_expression(false); + } + toplevel = this._toplevel; + this._toplevel = undefined; + return toplevel; + } + + before(node, descend) { + if (has_flag(node, SQUEEZED)) return node; + var was_scope = false; + if (node instanceof AST_Scope) { + node = node.hoist_properties(this); + node = node.hoist_declarations(this); + was_scope = true; + } + // Before https://github.com/mishoo/UglifyJS2/pull/1602 AST_Node.optimize() + // would call AST_Node.transform() if a different instance of AST_Node is + // produced after def_optimize(). + // This corrupts TreeWalker.stack, which cause AST look-ups to malfunction. + // Migrate and defer all children's AST_Node.transform() to below, which + // will now happen after this parent AST_Node has been properly substituted + // thus gives a consistent AST snapshot. + descend(node, this); + // Existing code relies on how AST_Node.optimize() worked, and omitting the + // following replacement call would result in degraded efficiency of both + // output and performance. + descend(node, this); + var opt = node.optimize(this); + if (was_scope && opt instanceof AST_Scope) { + opt.drop_unused(this); + descend(opt, this); + } + if (opt === node) set_flag(opt, SQUEEZED); + return opt; + } + + /** Alternative to plain is_lhs() which doesn't work within .optimize() */ + is_lhs() { + const self = this.stack[this.stack.length - 1]; + const parent = this.stack[this.stack.length - 2]; + return is_lhs(self, parent); + } +} + +function def_optimize(node, optimizer) { + node.DEFMETHOD("optimize", function(compressor) { + var self = this; + if (has_flag(self, OPTIMIZED)) return self; + if (compressor.has_directive("use asm")) return self; + var opt = optimizer(self, compressor); + set_flag(opt, OPTIMIZED); + return opt; + }); +} + +def_optimize(AST_Node, function(self) { + return self; +}); + +AST_Toplevel.DEFMETHOD("drop_console", function(options) { + var isArray = Array.isArray(options); + + return this.transform(new TreeTransformer(function(self) { + if (self.TYPE !== "Call") { + return; + } + + var exp = self.expression; + + if (!(exp instanceof AST_PropAccess)) { + return; + } + + if (isArray && options.indexOf(exp.property) === -1) { + return; + } + + var name = exp.expression; + while (name.expression) { + name = name.expression; + } + if (is_undeclared_ref(name) && name.name == "console") { + return make_node(AST_Undefined, self); + } + })); +}); + +AST_Node.DEFMETHOD("equivalent_to", function(node) { + return equivalent_to(this, node); +}); + +AST_Scope.DEFMETHOD("process_expression", function(insert, compressor) { + var self = this; + var tt = new TreeTransformer(function(node) { + if (insert && node instanceof AST_SimpleStatement) { + return make_node(AST_Return, node, { + value: node.body + }); + } + if (!insert && node instanceof AST_Return) { + if (compressor) { + var value = node.value && node.value.drop_side_effect_free(compressor, true); + return value + ? make_node(AST_SimpleStatement, node, { body: value }) + : make_node(AST_EmptyStatement, node); + } + return make_node(AST_SimpleStatement, node, { + body: node.value || make_node(AST_UnaryPrefix, node, { + operator: "void", + expression: make_node(AST_Number, node, { + value: 0 + }) + }) + }); + } + if (node instanceof AST_Class || node instanceof AST_Lambda && node !== self) { + return node; + } + if (node instanceof AST_Block) { + var index = node.body.length - 1; + if (index >= 0) { + node.body[index] = node.body[index].transform(tt); + } + } else if (node instanceof AST_If) { + node.body = node.body.transform(tt); + if (node.alternative) { + node.alternative = node.alternative.transform(tt); + } + } else if (node instanceof AST_With) { + node.body = node.body.transform(tt); + } + return node; + }); + self.transform(tt); +}); + +AST_Toplevel.DEFMETHOD("reset_opt_flags", function(compressor) { + const self = this; + const reduce_vars = compressor.option("reduce_vars"); + + const preparation = new TreeWalker(function(node, descend) { + clear_flag(node, CLEAR_BETWEEN_PASSES); + if (reduce_vars) { + if (compressor.top_retain + && node instanceof AST_Defun // Only functions are retained + && preparation.parent() === self + ) { + set_flag(node, TOP); + } + return node.reduce_vars(preparation, descend, compressor); + } + }); + // Stack of look-up tables to keep track of whether a `SymbolDef` has been + // properly assigned before use: + // - `push()` & `pop()` when visiting conditional branches + preparation.safe_ids = Object.create(null); + preparation.in_loop = null; + preparation.loop_ids = new Map(); + preparation.defs_to_safe_ids = new Map(); + self.walk(preparation); +}); + +AST_Symbol.DEFMETHOD("fixed_value", function() { + var fixed = this.thedef.fixed; + if (!fixed || fixed instanceof AST_Node) return fixed; + return fixed(); +}); + +AST_SymbolRef.DEFMETHOD("is_immutable", function() { + var orig = this.definition().orig; + return orig.length == 1 && orig[0] instanceof AST_SymbolLambda; +}); + +function find_variable(compressor, name) { + var scope, i = 0; + while (scope = compressor.parent(i++)) { + if (scope instanceof AST_Scope) break; + if (scope instanceof AST_Catch && scope.argname) { + scope = scope.argname.definition().scope; + break; + } + } + return scope.find_variable(name); +} + +var global_names = makePredicate("Array Boolean clearInterval clearTimeout console Date decodeURI decodeURIComponent encodeURI encodeURIComponent Error escape eval EvalError Function isFinite isNaN JSON Math Number parseFloat parseInt RangeError ReferenceError RegExp Object setInterval setTimeout String SyntaxError TypeError unescape URIError"); +AST_SymbolRef.DEFMETHOD("is_declared", function(compressor) { + return !this.definition().undeclared + || compressor.option("unsafe") && global_names.has(this.name); +}); + +/* -----[ optimizers ]----- */ + +var directives = new Set(["use asm", "use strict"]); +def_optimize(AST_Directive, function(self, compressor) { + if (compressor.option("directives") + && (!directives.has(self.value) || compressor.has_directive(self.value) !== self)) { + return make_node(AST_EmptyStatement, self); + } + return self; +}); + +def_optimize(AST_Debugger, function(self, compressor) { + if (compressor.option("drop_debugger")) + return make_node(AST_EmptyStatement, self); + return self; +}); + +def_optimize(AST_LabeledStatement, function(self, compressor) { + if (self.body instanceof AST_Break + && compressor.loopcontrol_target(self.body) === self.body) { + return make_node(AST_EmptyStatement, self); + } + return self.label.references.length == 0 ? self.body : self; +}); + +def_optimize(AST_Block, function(self, compressor) { + tighten_body(self.body, compressor); + return self; +}); + +function can_be_extracted_from_if_block(node) { + return !( + node instanceof AST_Const + || node instanceof AST_Let + || node instanceof AST_Class + ); +} + +def_optimize(AST_BlockStatement, function(self, compressor) { + tighten_body(self.body, compressor); + switch (self.body.length) { + case 1: + if (!compressor.has_directive("use strict") + && compressor.parent() instanceof AST_If + && can_be_extracted_from_if_block(self.body[0]) + || can_be_evicted_from_block(self.body[0])) { + return self.body[0]; + } + break; + case 0: return make_node(AST_EmptyStatement, self); + } + return self; +}); + +function opt_AST_Lambda(self, compressor) { + tighten_body(self.body, compressor); + if (compressor.option("side_effects") + && self.body.length == 1 + && self.body[0] === compressor.has_directive("use strict")) { + self.body.length = 0; + } + return self; +} +def_optimize(AST_Lambda, opt_AST_Lambda); + +AST_Scope.DEFMETHOD("hoist_declarations", function(compressor) { + var self = this; + if (compressor.has_directive("use asm")) return self; + + var hoist_funs = compressor.option("hoist_funs"); + var hoist_vars = compressor.option("hoist_vars"); + + if (hoist_funs || hoist_vars) { + var dirs = []; + var hoisted = []; + var vars = new Map(), vars_found = 0, var_decl = 0; + // let's count var_decl first, we seem to waste a lot of + // space if we hoist `var` when there's only one. + walk(self, node => { + if (node instanceof AST_Scope && node !== self) + return true; + if (node instanceof AST_Var) { + ++var_decl; + return true; + } + }); + hoist_vars = hoist_vars && var_decl > 1; + var tt = new TreeTransformer( + function before(node) { + if (node !== self) { + if (node instanceof AST_Directive) { + dirs.push(node); + return make_node(AST_EmptyStatement, node); + } + if (hoist_funs && node instanceof AST_Defun + && !(tt.parent() instanceof AST_Export) + && tt.parent() === self) { + hoisted.push(node); + return make_node(AST_EmptyStatement, node); + } + if ( + hoist_vars + && node instanceof AST_Var + && !node.definitions.some(def => def.name instanceof AST_Destructuring) + ) { + node.definitions.forEach(function(def) { + vars.set(def.name.name, def); + ++vars_found; + }); + var seq = node.to_assignments(compressor); + var p = tt.parent(); + if (p instanceof AST_ForIn && p.init === node) { + if (seq == null) { + var def = node.definitions[0].name; + return make_node(AST_SymbolRef, def, def); + } + return seq; + } + if (p instanceof AST_For && p.init === node) { + return seq; + } + if (!seq) return make_node(AST_EmptyStatement, node); + return make_node(AST_SimpleStatement, node, { + body: seq + }); + } + if (node instanceof AST_Scope) + return node; // to avoid descending in nested scopes + } + } + ); + self = self.transform(tt); + if (vars_found > 0) { + // collect only vars which don't show up in self's arguments list + var defs = []; + const is_lambda = self instanceof AST_Lambda; + const args_as_names = is_lambda ? self.args_as_names() : null; + vars.forEach((def, name) => { + if (is_lambda && args_as_names.some((x) => x.name === def.name.name)) { + vars.delete(name); + } else { + def = def.clone(); + def.value = null; + defs.push(def); + vars.set(name, def); + } + }); + if (defs.length > 0) { + // try to merge in assignments + for (var i = 0; i < self.body.length;) { + if (self.body[i] instanceof AST_SimpleStatement) { + var expr = self.body[i].body, sym, assign; + if (expr instanceof AST_Assign + && expr.operator == "=" + && (sym = expr.left) instanceof AST_Symbol + && vars.has(sym.name) + ) { + var def = vars.get(sym.name); + if (def.value) break; + def.value = expr.right; + remove(defs, def); + defs.push(def); + self.body.splice(i, 1); + continue; + } + if (expr instanceof AST_Sequence + && (assign = expr.expressions[0]) instanceof AST_Assign + && assign.operator == "=" + && (sym = assign.left) instanceof AST_Symbol + && vars.has(sym.name) + ) { + var def = vars.get(sym.name); + if (def.value) break; + def.value = assign.right; + remove(defs, def); + defs.push(def); + self.body[i].body = make_sequence(expr, expr.expressions.slice(1)); + continue; + } + } + if (self.body[i] instanceof AST_EmptyStatement) { + self.body.splice(i, 1); + continue; + } + if (self.body[i] instanceof AST_BlockStatement) { + self.body.splice(i, 1, ...self.body[i].body); + continue; + } + break; + } + defs = make_node(AST_Var, self, { + definitions: defs + }); + hoisted.push(defs); + } + } + self.body = dirs.concat(hoisted, self.body); + } + return self; +}); + +AST_Scope.DEFMETHOD("hoist_properties", function(compressor) { + var self = this; + if (!compressor.option("hoist_props") || compressor.has_directive("use asm")) return self; + var top_retain = self instanceof AST_Toplevel && compressor.top_retain || return_false; + var defs_by_id = new Map(); + var hoister = new TreeTransformer(function(node, descend) { + if (node instanceof AST_VarDef) { + const sym = node.name; + let def; + let value; + if (sym.scope === self + && (def = sym.definition()).escaped != 1 + && !def.assignments + && !def.direct_access + && !def.single_use + && !compressor.exposed(def) + && !top_retain(def) + && (value = sym.fixed_value()) === node.value + && value instanceof AST_Object + && !value.properties.some(prop => + prop instanceof AST_Expansion || prop.computed_key() + ) + ) { + descend(node, this); + const defs = new Map(); + const assignments = []; + value.properties.forEach(({ key, value }) => { + const scope = hoister.find_scope(); + const symbol = self.create_symbol(sym.CTOR, { + source: sym, + scope, + conflict_scopes: new Set([ + scope, + ...sym.definition().references.map(ref => ref.scope) + ]), + tentative_name: sym.name + "_" + key + }); + + defs.set(String(key), symbol.definition()); + + assignments.push(make_node(AST_VarDef, node, { + name: symbol, + value + })); + }); + defs_by_id.set(def.id, defs); + return MAP.splice(assignments); + } + } else if (node instanceof AST_PropAccess + && node.expression instanceof AST_SymbolRef + ) { + const defs = defs_by_id.get(node.expression.definition().id); + if (defs) { + const def = defs.get(String(get_simple_key(node.property))); + const sym = make_node(AST_SymbolRef, node, { + name: def.name, + scope: node.expression.scope, + thedef: def + }); + sym.reference({}); + return sym; + } + } + }); + return self.transform(hoister); +}); + +def_optimize(AST_SimpleStatement, function(self, compressor) { + if (compressor.option("side_effects")) { + var body = self.body; + var node = body.drop_side_effect_free(compressor, true); + if (!node) { + return make_node(AST_EmptyStatement, self); + } + if (node !== body) { + return make_node(AST_SimpleStatement, self, { body: node }); + } + } + return self; +}); + +def_optimize(AST_While, function(self, compressor) { + return compressor.option("loops") ? make_node(AST_For, self, self).optimize(compressor) : self; +}); + +def_optimize(AST_Do, function(self, compressor) { + if (!compressor.option("loops")) return self; + var cond = self.condition.tail_node().evaluate(compressor); + if (!(cond instanceof AST_Node)) { + if (cond) return make_node(AST_For, self, { + body: make_node(AST_BlockStatement, self.body, { + body: [ + self.body, + make_node(AST_SimpleStatement, self.condition, { + body: self.condition + }) + ] + }) + }).optimize(compressor); + if (!has_break_or_continue(self, compressor.parent())) { + return make_node(AST_BlockStatement, self.body, { + body: [ + self.body, + make_node(AST_SimpleStatement, self.condition, { + body: self.condition + }) + ] + }).optimize(compressor); + } + } + return self; +}); + +function if_break_in_loop(self, compressor) { + var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body; + if (compressor.option("dead_code") && is_break(first)) { + var body = []; + if (self.init instanceof AST_Statement) { + body.push(self.init); + } else if (self.init) { + body.push(make_node(AST_SimpleStatement, self.init, { + body: self.init + })); + } + if (self.condition) { + body.push(make_node(AST_SimpleStatement, self.condition, { + body: self.condition + })); + } + trim_unreachable_code(compressor, self.body, body); + return make_node(AST_BlockStatement, self, { + body: body + }); + } + if (first instanceof AST_If) { + if (is_break(first.body)) { + if (self.condition) { + self.condition = make_node(AST_Binary, self.condition, { + left: self.condition, + operator: "&&", + right: first.condition.negate(compressor), + }); + } else { + self.condition = first.condition.negate(compressor); + } + drop_it(first.alternative); + } else if (is_break(first.alternative)) { + if (self.condition) { + self.condition = make_node(AST_Binary, self.condition, { + left: self.condition, + operator: "&&", + right: first.condition, + }); + } else { + self.condition = first.condition; + } + drop_it(first.body); + } + } + return self; + + function is_break(node) { + return node instanceof AST_Break + && compressor.loopcontrol_target(node) === compressor.self(); + } + + function drop_it(rest) { + rest = as_statement_array(rest); + if (self.body instanceof AST_BlockStatement) { + self.body = self.body.clone(); + self.body.body = rest.concat(self.body.body.slice(1)); + self.body = self.body.transform(compressor); + } else { + self.body = make_node(AST_BlockStatement, self.body, { + body: rest + }).transform(compressor); + } + self = if_break_in_loop(self, compressor); + } +} + +def_optimize(AST_For, function(self, compressor) { + if (!compressor.option("loops")) return self; + if (compressor.option("side_effects") && self.init) { + self.init = self.init.drop_side_effect_free(compressor); + } + if (self.condition) { + var cond = self.condition.evaluate(compressor); + if (!(cond instanceof AST_Node)) { + if (cond) self.condition = null; + else if (!compressor.option("dead_code")) { + var orig = self.condition; + self.condition = make_node_from_constant(cond, self.condition); + self.condition = best_of_expression(self.condition.transform(compressor), orig); + } + } + if (compressor.option("dead_code")) { + if (cond instanceof AST_Node) cond = self.condition.tail_node().evaluate(compressor); + if (!cond) { + var body = []; + trim_unreachable_code(compressor, self.body, body); + if (self.init instanceof AST_Statement) { + body.push(self.init); + } else if (self.init) { + body.push(make_node(AST_SimpleStatement, self.init, { + body: self.init + })); + } + body.push(make_node(AST_SimpleStatement, self.condition, { + body: self.condition + })); + return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor); + } + } + } + return if_break_in_loop(self, compressor); +}); + +def_optimize(AST_If, function(self, compressor) { + if (is_empty(self.alternative)) self.alternative = null; + + if (!compressor.option("conditionals")) return self; + // if condition can be statically determined, drop + // one of the blocks. note, statically determined implies + // “has no side effects”; also it doesn't work for cases like + // `x && true`, though it probably should. + var cond = self.condition.evaluate(compressor); + if (!compressor.option("dead_code") && !(cond instanceof AST_Node)) { + var orig = self.condition; + self.condition = make_node_from_constant(cond, orig); + self.condition = best_of_expression(self.condition.transform(compressor), orig); + } + if (compressor.option("dead_code")) { + if (cond instanceof AST_Node) cond = self.condition.tail_node().evaluate(compressor); + if (!cond) { + var body = []; + trim_unreachable_code(compressor, self.body, body); + body.push(make_node(AST_SimpleStatement, self.condition, { + body: self.condition + })); + if (self.alternative) body.push(self.alternative); + return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor); + } else if (!(cond instanceof AST_Node)) { + var body = []; + body.push(make_node(AST_SimpleStatement, self.condition, { + body: self.condition + })); + body.push(self.body); + if (self.alternative) { + trim_unreachable_code(compressor, self.alternative, body); + } + return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor); + } + } + var negated = self.condition.negate(compressor); + var self_condition_length = self.condition.size(); + var negated_length = negated.size(); + var negated_is_best = negated_length < self_condition_length; + if (self.alternative && negated_is_best) { + negated_is_best = false; // because we already do the switch here. + // no need to swap values of self_condition_length and negated_length + // here because they are only used in an equality comparison later on. + self.condition = negated; + var tmp = self.body; + self.body = self.alternative || make_node(AST_EmptyStatement, self); + self.alternative = tmp; + } + if (is_empty(self.body) && is_empty(self.alternative)) { + return make_node(AST_SimpleStatement, self.condition, { + body: self.condition.clone() + }).optimize(compressor); + } + if (self.body instanceof AST_SimpleStatement + && self.alternative instanceof AST_SimpleStatement) { + return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Conditional, self, { + condition : self.condition, + consequent : self.body.body, + alternative : self.alternative.body + }) + }).optimize(compressor); + } + if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) { + if (self_condition_length === negated_length && !negated_is_best + && self.condition instanceof AST_Binary && self.condition.operator == "||") { + // although the code length of self.condition and negated are the same, + // negated does not require additional surrounding parentheses. + // see https://github.com/mishoo/UglifyJS2/issues/979 + negated_is_best = true; + } + if (negated_is_best) return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Binary, self, { + operator : "||", + left : negated, + right : self.body.body + }) + }).optimize(compressor); + return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Binary, self, { + operator : "&&", + left : self.condition, + right : self.body.body + }) + }).optimize(compressor); + } + if (self.body instanceof AST_EmptyStatement + && self.alternative instanceof AST_SimpleStatement) { + return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Binary, self, { + operator : "||", + left : self.condition, + right : self.alternative.body + }) + }).optimize(compressor); + } + if (self.body instanceof AST_Exit + && self.alternative instanceof AST_Exit + && self.body.TYPE == self.alternative.TYPE) { + return make_node(self.body.CTOR, self, { + value: make_node(AST_Conditional, self, { + condition : self.condition, + consequent : self.body.value || make_node(AST_Undefined, self.body), + alternative : self.alternative.value || make_node(AST_Undefined, self.alternative) + }).transform(compressor) + }).optimize(compressor); + } + if (self.body instanceof AST_If + && !self.body.alternative + && !self.alternative) { + self = make_node(AST_If, self, { + condition: make_node(AST_Binary, self.condition, { + operator: "&&", + left: self.condition, + right: self.body.condition + }), + body: self.body.body, + alternative: null + }); + } + if (aborts(self.body)) { + if (self.alternative) { + var alt = self.alternative; + self.alternative = null; + return make_node(AST_BlockStatement, self, { + body: [ self, alt ] + }).optimize(compressor); + } + } + if (aborts(self.alternative)) { + var body = self.body; + self.body = self.alternative; + self.condition = negated_is_best ? negated : self.condition.negate(compressor); + self.alternative = null; + return make_node(AST_BlockStatement, self, { + body: [ self, body ] + }).optimize(compressor); + } + return self; +}); + +def_optimize(AST_Switch, function(self, compressor) { + if (!compressor.option("switches")) return self; + var branch; + var value = self.expression.evaluate(compressor); + if (!(value instanceof AST_Node)) { + var orig = self.expression; + self.expression = make_node_from_constant(value, orig); + self.expression = best_of_expression(self.expression.transform(compressor), orig); + } + if (!compressor.option("dead_code")) return self; + if (value instanceof AST_Node) { + value = self.expression.tail_node().evaluate(compressor); + } + var decl = []; + var body = []; + var default_branch; + var exact_match; + for (var i = 0, len = self.body.length; i < len && !exact_match; i++) { + branch = self.body[i]; + if (branch instanceof AST_Default) { + if (!default_branch) { + default_branch = branch; + } else { + eliminate_branch(branch, body[body.length - 1]); + } + } else if (!(value instanceof AST_Node)) { + var exp = branch.expression.evaluate(compressor); + if (!(exp instanceof AST_Node) && exp !== value) { + eliminate_branch(branch, body[body.length - 1]); + continue; + } + if (exp instanceof AST_Node && !exp.has_side_effects(compressor)) { + exp = branch.expression.tail_node().evaluate(compressor); + } + if (exp === value) { + exact_match = branch; + if (default_branch) { + var default_index = body.indexOf(default_branch); + body.splice(default_index, 1); + eliminate_branch(default_branch, body[default_index - 1]); + default_branch = null; + } + } + } + body.push(branch); + } + while (i < len) eliminate_branch(self.body[i++], body[body.length - 1]); + self.body = body; + + let default_or_exact = default_branch || exact_match; + default_branch = null; + exact_match = null; + + // group equivalent branches so they will be located next to each other, + // that way the next micro-optimization will merge them. + // ** bail micro-optimization if not a simple switch case with breaks + if (body.every((branch, i) => + (branch === default_or_exact || branch.expression instanceof AST_Constant) + && (branch.body.length === 0 || aborts(branch) || body.length - 1 === i)) + ) { + for (let i = 0; i < body.length; i++) { + const branch = body[i]; + for (let j = i + 1; j < body.length; j++) { + const next = body[j]; + if (next.body.length === 0) continue; + const last_branch = j === (body.length - 1); + const equivalentBranch = branches_equivalent(next, branch, false); + if (equivalentBranch || (last_branch && branches_equivalent(next, branch, true))) { + if (!equivalentBranch && last_branch) { + next.body.push(make_node(AST_Break)); + } + + // let's find previous siblings with inert fallthrough... + let x = j - 1; + let fallthroughDepth = 0; + while (x > i) { + if (is_inert_body(body[x--])) { + fallthroughDepth++; + } else { + break; + } + } + + const plucked = body.splice(j - fallthroughDepth, 1 + fallthroughDepth); + body.splice(i + 1, 0, ...plucked); + i += plucked.length; + } + } + } + } + + // merge equivalent branches in a row + for (let i = 0; i < body.length; i++) { + let branch = body[i]; + if (branch.body.length === 0) continue; + if (!aborts(branch)) continue; + + for (let j = i + 1; j < body.length; i++, j++) { + let next = body[j]; + if (next.body.length === 0) continue; + if ( + branches_equivalent(next, branch, false) + || (j === body.length - 1 && branches_equivalent(next, branch, true)) + ) { + branch.body = []; + branch = next; + continue; + } + break; + } + } + + // Prune any empty branches at the end of the switch statement. + { + let i = body.length - 1; + for (; i >= 0; i--) { + let bbody = body[i].body; + if (is_break(bbody[bbody.length - 1], compressor)) bbody.pop(); + if (!is_inert_body(body[i])) break; + } + // i now points to the index of a branch that contains a body. By incrementing, it's + // pointing to the first branch that's empty. + i++; + if (!default_or_exact || body.indexOf(default_or_exact) >= i) { + // The default behavior is to do nothing. We can take advantage of that to + // remove all case expressions that are side-effect free that also do + // nothing, since they'll default to doing nothing. But we can't remove any + // case expressions before one that would side-effect, since they may cause + // the side-effect to be skipped. + for (let j = body.length - 1; j >= i; j--) { + let branch = body[j]; + if (branch === default_or_exact) { + default_or_exact = null; + body.pop(); + } else if (!branch.expression.has_side_effects(compressor)) { + body.pop(); + } else { + break; + } + } + } + } + + + // Prune side-effect free branches that fall into default. + DEFAULT: if (default_or_exact) { + let default_index = body.indexOf(default_or_exact); + let default_body_index = default_index; + for (; default_body_index < body.length - 1; default_body_index++) { + if (!is_inert_body(body[default_body_index])) break; + } + if (default_body_index < body.length - 1) { + break DEFAULT; + } + + let side_effect_index = body.length - 1; + for (; side_effect_index >= 0; side_effect_index--) { + let branch = body[side_effect_index]; + if (branch === default_or_exact) continue; + if (branch.expression.has_side_effects(compressor)) break; + } + // If the default behavior comes after any side-effect case expressions, + // then we can fold all side-effect free cases into the default branch. + // If the side-effect case is after the default, then any side-effect + // free cases could prevent the side-effect from occurring. + if (default_body_index > side_effect_index) { + let prev_body_index = default_index - 1; + for (; prev_body_index >= 0; prev_body_index--) { + if (!is_inert_body(body[prev_body_index])) break; + } + let before = Math.max(side_effect_index, prev_body_index) + 1; + let after = default_index; + if (side_effect_index > default_index) { + // If the default falls into the same body as a side-effect + // case, then we need preserve that case and only prune the + // cases after it. + after = side_effect_index; + body[side_effect_index].body = body[default_body_index].body; + } else { + // The default will be the last branch. + default_or_exact.body = body[default_body_index].body; + } + + // Prune everything after the default (or last side-effect case) + // until the next case with a body. + body.splice(after + 1, default_body_index - after); + // Prune everything before the default that falls into it. + body.splice(before, default_index - before); + } + } + + // See if we can remove the switch entirely if all cases (the default) fall into the same case body. + DEFAULT: if (default_or_exact) { + let i = body.findIndex(branch => !is_inert_body(branch)); + let caseBody; + // `i` is equal to one of the following: + // - `-1`, there is no body in the switch statement. + // - `body.length - 1`, all cases fall into the same body. + // - anything else, there are multiple bodies in the switch. + if (i === body.length - 1) { + // All cases fall into the case body. + let branch = body[i]; + if (has_nested_break(self)) break DEFAULT; + + // This is the last case body, and we've already pruned any breaks, so it's + // safe to hoist. + caseBody = make_node(AST_BlockStatement, branch, { + body: branch.body + }); + branch.body = []; + } else if (i !== -1) { + // If there are multiple bodies, then we cannot optimize anything. + break DEFAULT; + } + + let sideEffect = body.find( + branch => branch !== default_or_exact && branch.expression.has_side_effects(compressor) + ); + // If no cases cause a side-effect, we can eliminate the switch entirely. + if (!sideEffect) { + return make_node(AST_BlockStatement, self, { + body: decl.concat( + statement(self.expression), + default_or_exact.expression ? statement(default_or_exact.expression) : [], + caseBody || [] + ) + }).optimize(compressor); + } + + // If we're this far, either there was no body or all cases fell into the same body. + // If there was no body, then we don't need a default branch (because the default is + // do nothing). If there was a body, we'll extract it to after the switch, so the + // switch's new default is to do nothing and we can still prune it. + const default_index = body.indexOf(default_or_exact); + body.splice(default_index, 1); + default_or_exact = null; + + if (caseBody) { + // Recurse into switch statement one more time so that we can append the case body + // outside of the switch. This recursion will only happen once since we've pruned + // the default case. + return make_node(AST_BlockStatement, self, { + body: decl.concat(self, caseBody) + }).optimize(compressor); + } + // If we fall here, there is a default branch somewhere, there are no case bodies, + // and there's a side-effect somewhere. Just let the below paths take care of it. + } + + if (body.length > 0) { + body[0].body = decl.concat(body[0].body); + } + + if (body.length == 0) { + return make_node(AST_BlockStatement, self, { + body: decl.concat(statement(self.expression)) + }).optimize(compressor); + } + if (body.length == 1 && !has_nested_break(self)) { + // This is the last case body, and we've already pruned any breaks, so it's + // safe to hoist. + let branch = body[0]; + return make_node(AST_If, self, { + condition: make_node(AST_Binary, self, { + operator: "===", + left: self.expression, + right: branch.expression, + }), + body: make_node(AST_BlockStatement, branch, { + body: branch.body + }), + alternative: null + }).optimize(compressor); + } + if (body.length === 2 && default_or_exact && !has_nested_break(self)) { + let branch = body[0] === default_or_exact ? body[1] : body[0]; + let exact_exp = default_or_exact.expression && statement(default_or_exact.expression); + if (aborts(body[0])) { + // Only the first branch body could have a break (at the last statement) + let first = body[0]; + if (is_break(first.body[first.body.length - 1], compressor)) { + first.body.pop(); + } + return make_node(AST_If, self, { + condition: make_node(AST_Binary, self, { + operator: "===", + left: self.expression, + right: branch.expression, + }), + body: make_node(AST_BlockStatement, branch, { + body: branch.body + }), + alternative: make_node(AST_BlockStatement, default_or_exact, { + body: [].concat( + exact_exp || [], + default_or_exact.body + ) + }) + }).optimize(compressor); + } + let operator = "==="; + let consequent = make_node(AST_BlockStatement, branch, { + body: branch.body, + }); + let always = make_node(AST_BlockStatement, default_or_exact, { + body: [].concat( + exact_exp || [], + default_or_exact.body + ) + }); + if (body[0] === default_or_exact) { + operator = "!=="; + let tmp = always; + always = consequent; + consequent = tmp; + } + return make_node(AST_BlockStatement, self, { + body: [ + make_node(AST_If, self, { + condition: make_node(AST_Binary, self, { + operator: operator, + left: self.expression, + right: branch.expression, + }), + body: consequent, + alternative: null, + }), + always, + ], + }).optimize(compressor); + } + return self; + + function eliminate_branch(branch, prev) { + if (prev && !aborts(prev)) { + prev.body = prev.body.concat(branch.body); + } else { + trim_unreachable_code(compressor, branch, decl); + } + } + function branches_equivalent(branch, prev, insertBreak) { + let bbody = branch.body; + let pbody = prev.body; + if (insertBreak) { + bbody = bbody.concat(make_node(AST_Break)); + } + if (bbody.length !== pbody.length) return false; + let bblock = make_node(AST_BlockStatement, branch, { body: bbody }); + let pblock = make_node(AST_BlockStatement, prev, { body: pbody }); + return bblock.equivalent_to(pblock); + } + function statement(body) { + return make_node(AST_SimpleStatement, body, { body }); + } + function has_nested_break(root) { + let has_break = false; + + let tw = new TreeWalker(node => { + if (has_break) return true; + if (node instanceof AST_Lambda) return true; + if (node instanceof AST_SimpleStatement) return true; + if (!is_break(node, tw)) return; + let parent = tw.parent(); + if ( + parent instanceof AST_SwitchBranch + && parent.body[parent.body.length - 1] === node + ) { + return; + } + has_break = true; + }); + root.walk(tw); + return has_break; + } + function is_break(node, stack) { + return node instanceof AST_Break + && stack.loopcontrol_target(node) === self; + } + function is_inert_body(branch) { + return !aborts(branch) && !make_node(AST_BlockStatement, branch, { + body: branch.body + }).has_side_effects(compressor); + } +}); + +def_optimize(AST_Try, function(self, compressor) { + if (self.bcatch && self.bfinally && self.bfinally.body.every(is_empty)) self.bfinally = null; + + if (compressor.option("dead_code") && self.body.body.every(is_empty)) { + var body = []; + if (self.bcatch) { + trim_unreachable_code(compressor, self.bcatch, body); + } + if (self.bfinally) body.push(...self.bfinally.body); + return make_node(AST_BlockStatement, self, { + body: body + }).optimize(compressor); + } + return self; +}); + +AST_Definitions.DEFMETHOD("to_assignments", function(compressor) { + var reduce_vars = compressor.option("reduce_vars"); + var assignments = []; + + for (const def of this.definitions) { + if (def.value) { + var name = make_node(AST_SymbolRef, def.name, def.name); + assignments.push(make_node(AST_Assign, def, { + operator : "=", + logical: false, + left : name, + right : def.value + })); + if (reduce_vars) name.definition().fixed = false; + } + const thedef = def.name.definition(); + thedef.eliminated++; + thedef.replaced--; + } + + if (assignments.length == 0) return null; + return make_sequence(this, assignments); +}); + +def_optimize(AST_Definitions, function(self) { + if (self.definitions.length == 0) { + return make_node(AST_EmptyStatement, self); + } + return self; +}); + +def_optimize(AST_VarDef, function(self, compressor) { + if ( + self.name instanceof AST_SymbolLet + && self.value != null + && is_undefined(self.value, compressor) + ) { + self.value = null; + } + return self; +}); + +def_optimize(AST_Import, function(self) { + return self; +}); + +def_optimize(AST_Call, function(self, compressor) { + var exp = self.expression; + var fn = exp; + inline_array_like_spread(self.args); + var simple_args = self.args.every((arg) => !(arg instanceof AST_Expansion)); + + if (compressor.option("reduce_vars") && fn instanceof AST_SymbolRef) { + fn = fn.fixed_value(); + } + + var is_func = fn instanceof AST_Lambda; + + if (is_func && fn.pinned()) return self; + + if (compressor.option("unused") + && simple_args + && is_func + && !fn.uses_arguments) { + var pos = 0, last = 0; + for (var i = 0, len = self.args.length; i < len; i++) { + if (fn.argnames[i] instanceof AST_Expansion) { + if (has_flag(fn.argnames[i].expression, UNUSED)) while (i < len) { + var node = self.args[i++].drop_side_effect_free(compressor); + if (node) { + self.args[pos++] = node; + } + } else while (i < len) { + self.args[pos++] = self.args[i++]; + } + last = pos; + break; + } + var trim = i >= fn.argnames.length; + if (trim || has_flag(fn.argnames[i], UNUSED)) { + var node = self.args[i].drop_side_effect_free(compressor); + if (node) { + self.args[pos++] = node; + } else if (!trim) { + self.args[pos++] = make_node(AST_Number, self.args[i], { + value: 0 + }); + continue; + } + } else { + self.args[pos++] = self.args[i]; + } + last = pos; + } + self.args.length = last; + } + + if (compressor.option("unsafe") && !exp.contains_optional()) { + if (exp instanceof AST_Dot && exp.start.value === "Array" && exp.property === "from" && self.args.length === 1) { + const [argument] = self.args; + if (argument instanceof AST_Array) { + return make_node(AST_Array, argument, { + elements: argument.elements + }).optimize(compressor); + } + } + if (is_undeclared_ref(exp)) switch (exp.name) { + case "Array": + if (self.args.length != 1) { + return make_node(AST_Array, self, { + elements: self.args + }).optimize(compressor); + } else if (self.args[0] instanceof AST_Number && self.args[0].value <= 11) { + const elements = []; + for (let i = 0; i < self.args[0].value; i++) elements.push(new AST_Hole); + return new AST_Array({ elements }); + } + break; + case "Object": + if (self.args.length == 0) { + return make_node(AST_Object, self, { + properties: [] + }); + } + break; + case "String": + if (self.args.length == 0) return make_node(AST_String, self, { + value: "" + }); + if (self.args.length <= 1) return make_node(AST_Binary, self, { + left: self.args[0], + operator: "+", + right: make_node(AST_String, self, { value: "" }) + }).optimize(compressor); + break; + case "Number": + if (self.args.length == 0) return make_node(AST_Number, self, { + value: 0 + }); + if (self.args.length == 1 && compressor.option("unsafe_math")) { + return make_node(AST_UnaryPrefix, self, { + expression: self.args[0], + operator: "+" + }).optimize(compressor); + } + break; + case "Symbol": + if (self.args.length == 1 && self.args[0] instanceof AST_String && compressor.option("unsafe_symbols")) + self.args.length = 0; + break; + case "Boolean": + if (self.args.length == 0) return make_node(AST_False, self); + if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, { + expression: make_node(AST_UnaryPrefix, self, { + expression: self.args[0], + operator: "!" + }), + operator: "!" + }).optimize(compressor); + break; + case "RegExp": + var params = []; + if (self.args.length >= 1 + && self.args.length <= 2 + && self.args.every((arg) => { + var value = arg.evaluate(compressor); + params.push(value); + return arg !== value; + }) + && regexp_is_safe(params[0]) + ) { + let [ source, flags ] = params; + source = regexp_source_fix(new RegExp(source).source); + const rx = make_node(AST_RegExp, self, { + value: { source, flags } + }); + if (rx._eval(compressor) !== rx) { + return rx; + } + } + break; + } else if (exp instanceof AST_Dot) switch(exp.property) { + case "toString": + if (self.args.length == 0 && !exp.expression.may_throw_on_access(compressor)) { + return make_node(AST_Binary, self, { + left: make_node(AST_String, self, { value: "" }), + operator: "+", + right: exp.expression + }).optimize(compressor); + } + break; + case "join": + if (exp.expression instanceof AST_Array) EXIT: { + var separator; + if (self.args.length > 0) { + separator = self.args[0].evaluate(compressor); + if (separator === self.args[0]) break EXIT; // not a constant + } + var elements = []; + var consts = []; + for (var i = 0, len = exp.expression.elements.length; i < len; i++) { + var el = exp.expression.elements[i]; + if (el instanceof AST_Expansion) break EXIT; + var value = el.evaluate(compressor); + if (value !== el) { + consts.push(value); + } else { + if (consts.length > 0) { + elements.push(make_node(AST_String, self, { + value: consts.join(separator) + })); + consts.length = 0; + } + elements.push(el); + } + } + if (consts.length > 0) { + elements.push(make_node(AST_String, self, { + value: consts.join(separator) + })); + } + if (elements.length == 0) return make_node(AST_String, self, { value: "" }); + if (elements.length == 1) { + if (elements[0].is_string(compressor)) { + return elements[0]; + } + return make_node(AST_Binary, elements[0], { + operator : "+", + left : make_node(AST_String, self, { value: "" }), + right : elements[0] + }); + } + if (separator == "") { + var first; + if (elements[0].is_string(compressor) + || elements[1].is_string(compressor)) { + first = elements.shift(); + } else { + first = make_node(AST_String, self, { value: "" }); + } + return elements.reduce(function(prev, el) { + return make_node(AST_Binary, el, { + operator : "+", + left : prev, + right : el + }); + }, first).optimize(compressor); + } + // need this awkward cloning to not affect original element + // best_of will decide which one to get through. + var node = self.clone(); + node.expression = node.expression.clone(); + node.expression.expression = node.expression.expression.clone(); + node.expression.expression.elements = elements; + return best_of(compressor, self, node); + } + break; + case "charAt": + if (exp.expression.is_string(compressor)) { + var arg = self.args[0]; + var index = arg ? arg.evaluate(compressor) : 0; + if (index !== arg) { + return make_node(AST_Sub, exp, { + expression: exp.expression, + property: make_node_from_constant(index | 0, arg || exp) + }).optimize(compressor); + } + } + break; + case "apply": + if (self.args.length == 2 && self.args[1] instanceof AST_Array) { + var args = self.args[1].elements.slice(); + args.unshift(self.args[0]); + return make_node(AST_Call, self, { + expression: make_node(AST_Dot, exp, { + expression: exp.expression, + optional: false, + property: "call" + }), + args: args + }).optimize(compressor); + } + break; + case "call": + var func = exp.expression; + if (func instanceof AST_SymbolRef) { + func = func.fixed_value(); + } + if (func instanceof AST_Lambda && !func.contains_this()) { + return (self.args.length ? make_sequence(this, [ + self.args[0], + make_node(AST_Call, self, { + expression: exp.expression, + args: self.args.slice(1) + }) + ]) : make_node(AST_Call, self, { + expression: exp.expression, + args: [] + })).optimize(compressor); + } + break; + } + } + + if (compressor.option("unsafe_Function") + && is_undeclared_ref(exp) + && exp.name == "Function") { + // new Function() => function(){} + if (self.args.length == 0) return make_node(AST_Function, self, { + argnames: [], + body: [] + }).optimize(compressor); + if (self.args.every((x) => x instanceof AST_String)) { + // quite a corner-case, but we can handle it: + // https://github.com/mishoo/UglifyJS2/issues/203 + // if the code argument is a constant, then we can minify it. + try { + var code = "n(function(" + self.args.slice(0, -1).map(function(arg) { + return arg.value; + }).join(",") + "){" + self.args[self.args.length - 1].value + "})"; + var ast = parse(code); + var mangle = compressor.mangle_options(); + ast.figure_out_scope(mangle); + var comp = new Compressor(compressor.options, { + mangle_options: compressor._mangle_options + }); + ast = ast.transform(comp); + ast.figure_out_scope(mangle); + ast.compute_char_frequency(mangle); + ast.mangle_names(mangle); + var fun; + walk(ast, node => { + if (is_func_expr(node)) { + fun = node; + return walk_abort; + } + }); + var code = OutputStream(); + AST_BlockStatement.prototype._codegen.call(fun, fun, code); + self.args = [ + make_node(AST_String, self, { + value: fun.argnames.map(function(arg) { + return arg.print_to_string(); + }).join(",") + }), + make_node(AST_String, self.args[self.args.length - 1], { + value: code.get().replace(/^{|}$/g, "") + }) + ]; + return self; + } catch (ex) { + if (!(ex instanceof JS_Parse_Error)) { + throw ex; + } + + // Otherwise, it crashes at runtime. Or maybe it's nonstandard syntax. + } + } + } + + return inline_into_call(self, compressor); +}); + +/** Does this node contain optional property access or optional call? */ +AST_Node.DEFMETHOD("contains_optional", function() { + if ( + this instanceof AST_PropAccess + || this instanceof AST_Call + || this instanceof AST_Chain + ) { + if (this.optional) { + return true; + } else { + return this.expression.contains_optional(); + } + } else { + return false; + } +}); + +def_optimize(AST_New, function(self, compressor) { + if ( + compressor.option("unsafe") && + is_undeclared_ref(self.expression) && + ["Object", "RegExp", "Function", "Error", "Array"].includes(self.expression.name) + ) return make_node(AST_Call, self, self).transform(compressor); + return self; +}); + +def_optimize(AST_Sequence, function(self, compressor) { + if (!compressor.option("side_effects")) return self; + var expressions = []; + filter_for_side_effects(); + var end = expressions.length - 1; + trim_right_for_undefined(); + if (end == 0) { + self = maintain_this_binding(compressor.parent(), compressor.self(), expressions[0]); + if (!(self instanceof AST_Sequence)) self = self.optimize(compressor); + return self; + } + self.expressions = expressions; + return self; + + function filter_for_side_effects() { + var first = first_in_statement(compressor); + var last = self.expressions.length - 1; + self.expressions.forEach(function(expr, index) { + if (index < last) expr = expr.drop_side_effect_free(compressor, first); + if (expr) { + merge_sequence(expressions, expr); + first = false; + } + }); + } + + function trim_right_for_undefined() { + while (end > 0 && is_undefined(expressions[end], compressor)) end--; + if (end < expressions.length - 1) { + expressions[end] = make_node(AST_UnaryPrefix, self, { + operator : "void", + expression : expressions[end] + }); + expressions.length = end + 1; + } + } +}); + +AST_Unary.DEFMETHOD("lift_sequences", function(compressor) { + if (compressor.option("sequences")) { + if (this.expression instanceof AST_Sequence) { + var x = this.expression.expressions.slice(); + var e = this.clone(); + e.expression = x.pop(); + x.push(e); + return make_sequence(this, x).optimize(compressor); + } + } + return this; +}); + +def_optimize(AST_UnaryPostfix, function(self, compressor) { + return self.lift_sequences(compressor); +}); + +def_optimize(AST_UnaryPrefix, function(self, compressor) { + var e = self.expression; + if ( + self.operator == "delete" && + !( + e instanceof AST_SymbolRef || + e instanceof AST_PropAccess || + e instanceof AST_Chain || + is_identifier_atom(e) + ) + ) { + return make_sequence(self, [e, make_node(AST_True, self)]).optimize(compressor); + } + var seq = self.lift_sequences(compressor); + if (seq !== self) { + return seq; + } + if (compressor.option("side_effects") && self.operator == "void") { + e = e.drop_side_effect_free(compressor); + if (e) { + self.expression = e; + return self; + } else { + return make_node(AST_Undefined, self).optimize(compressor); + } + } + if (compressor.in_boolean_context()) { + switch (self.operator) { + case "!": + if (e instanceof AST_UnaryPrefix && e.operator == "!") { + // !!foo ==> foo, if we're in boolean context + return e.expression; + } + if (e instanceof AST_Binary) { + self = best_of(compressor, self, e.negate(compressor, first_in_statement(compressor))); + } + break; + case "typeof": + // typeof always returns a non-empty string, thus it's + // always true in booleans + // And we don't need to check if it's undeclared, because in typeof, that's OK + return (e instanceof AST_SymbolRef ? make_node(AST_True, self) : make_sequence(self, [ + e, + make_node(AST_True, self) + ])).optimize(compressor); + } + } + if (self.operator == "-" && e instanceof AST_Infinity) { + e = e.transform(compressor); + } + if (e instanceof AST_Binary + && (self.operator == "+" || self.operator == "-") + && (e.operator == "*" || e.operator == "/" || e.operator == "%")) { + return make_node(AST_Binary, self, { + operator: e.operator, + left: make_node(AST_UnaryPrefix, e.left, { + operator: self.operator, + expression: e.left + }), + right: e.right + }); + } + + if (compressor.option("evaluate")) { + // ~~x => x (in 32-bit context) + // ~~{32 bit integer} => {32 bit integer} + if ( + self.operator === "~" + && self.expression instanceof AST_UnaryPrefix + && self.expression.operator === "~" + && (compressor.in_32_bit_context() || self.expression.expression.is_32_bit_integer()) + ) { + return self.expression.expression; + } + + // ~(x ^ y) => x ^ ~y + if ( + self.operator === "~" + && e instanceof AST_Binary + && e.operator === "^" + ) { + if (e.left instanceof AST_UnaryPrefix && e.left.operator === "~") { + // ~(~x ^ y) => x ^ y + e.left = e.left.bitwise_negate(true); + } else { + e.right = e.right.bitwise_negate(true); + } + return e; + } + } + + if ( + self.operator != "-" + // avoid infinite recursion of numerals + || !(e instanceof AST_Number || e instanceof AST_Infinity || e instanceof AST_BigInt) + ) { + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + } + return self; +}); + +AST_Binary.DEFMETHOD("lift_sequences", function(compressor) { + if (compressor.option("sequences")) { + if (this.left instanceof AST_Sequence) { + var x = this.left.expressions.slice(); + var e = this.clone(); + e.left = x.pop(); + x.push(e); + return make_sequence(this, x).optimize(compressor); + } + if (this.right instanceof AST_Sequence && !this.left.has_side_effects(compressor)) { + var assign = this.operator == "=" && this.left instanceof AST_SymbolRef; + var x = this.right.expressions; + var last = x.length - 1; + for (var i = 0; i < last; i++) { + if (!assign && x[i].has_side_effects(compressor)) break; + } + if (i == last) { + x = x.slice(); + var e = this.clone(); + e.right = x.pop(); + x.push(e); + return make_sequence(this, x).optimize(compressor); + } else if (i > 0) { + var e = this.clone(); + e.right = make_sequence(this.right, x.slice(i)); + x = x.slice(0, i); + x.push(e); + return make_sequence(this, x).optimize(compressor); + } + } + } + return this; +}); + +var commutativeOperators = makePredicate("== === != !== * & | ^"); +function is_object(node) { + return node instanceof AST_Array + || node instanceof AST_Lambda + || node instanceof AST_Object + || node instanceof AST_Class; +} + +def_optimize(AST_Binary, function(self, compressor) { + function reversible() { + return self.left.is_constant() + || self.right.is_constant() + || !self.left.has_side_effects(compressor) + && !self.right.has_side_effects(compressor); + } + function reverse(op) { + if (reversible()) { + if (op) self.operator = op; + var tmp = self.left; + self.left = self.right; + self.right = tmp; + } + } + if (compressor.option("lhs_constants") && commutativeOperators.has(self.operator)) { + if (self.right.is_constant() + && !self.left.is_constant()) { + // if right is a constant, whatever side effects the + // left side might have could not influence the + // result. hence, force switch. + + if (!(self.left instanceof AST_Binary + && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) { + reverse(); + } + } + } + self = self.lift_sequences(compressor); + if (compressor.option("comparisons")) switch (self.operator) { + case "===": + case "!==": + var is_strict_comparison = true; + if ((self.left.is_string(compressor) && self.right.is_string(compressor)) || + (self.left.is_number(compressor) && self.right.is_number(compressor)) || + (self.left.is_boolean() && self.right.is_boolean()) || + self.left.equivalent_to(self.right)) { + self.operator = self.operator.substr(0, 2); + } + + // XXX: intentionally falling down to the next case + case "==": + case "!=": + // void 0 == x => null == x + if (!is_strict_comparison && is_undefined(self.left, compressor)) { + self.left = make_node(AST_Null, self.left); + // x == void 0 => x == null + } else if (!is_strict_comparison && is_undefined(self.right, compressor)) { + self.right = make_node(AST_Null, self.right); + } else if (compressor.option("typeofs") + // "undefined" == typeof x => undefined === x + && self.left instanceof AST_String + && self.left.value == "undefined" + && self.right instanceof AST_UnaryPrefix + && self.right.operator == "typeof") { + var expr = self.right.expression; + if (expr instanceof AST_SymbolRef ? expr.is_declared(compressor) + : !(expr instanceof AST_PropAccess && compressor.option("ie8"))) { + self.right = expr; + self.left = make_node(AST_Undefined, self.left).optimize(compressor); + if (self.operator.length == 2) self.operator += "="; + } + } else if (compressor.option("typeofs") + // typeof x === "undefined" => x === undefined + && self.left instanceof AST_UnaryPrefix + && self.left.operator == "typeof" + && self.right instanceof AST_String + && self.right.value == "undefined") { + var expr = self.left.expression; + if (expr instanceof AST_SymbolRef ? expr.is_declared(compressor) + : !(expr instanceof AST_PropAccess && compressor.option("ie8"))) { + self.left = expr; + self.right = make_node(AST_Undefined, self.right).optimize(compressor); + if (self.operator.length == 2) self.operator += "="; + } + } else if (self.left instanceof AST_SymbolRef + // obj !== obj => false + && self.right instanceof AST_SymbolRef + && self.left.definition() === self.right.definition() + && is_object(self.left.fixed_value())) { + return make_node(self.operator[0] == "=" ? AST_True : AST_False, self); + } else if (self.left.is_32_bit_integer() && self.right.is_32_bit_integer()) { + const not = node => make_node(AST_UnaryPrefix, node, { + operator: "!", + expression: node + }); + const booleanify = (node, truthy) => { + if (truthy) { + return compressor.in_boolean_context() + ? node + : not(not(node)); + } else { + return not(node); + } + }; + + // The only falsy 32-bit integer is 0 + if (self.left instanceof AST_Number && self.left.value === 0) { + return booleanify(self.right, self.operator[0] === "!"); + } + if (self.right instanceof AST_Number && self.right.value === 0) { + return booleanify(self.left, self.operator[0] === "!"); + } + + // Mask all-bits check + // (x & 0xFF) != 0xFF => !(~x & 0xFF) + let and_op, x, mask; + if ( + (and_op = + self.left instanceof AST_Binary ? self.left + : self.right instanceof AST_Binary ? self.right : null) + && (mask = and_op === self.left ? self.right : self.left) + && and_op.operator === "&" + && mask instanceof AST_Number + && mask.is_32_bit_integer() + && (x = + and_op.left.equivalent_to(mask) ? and_op.right + : and_op.right.equivalent_to(mask) ? and_op.left : null) + ) { + let optimized = booleanify(make_node(AST_Binary, self, { + operator: "&", + left: mask, + right: make_node(AST_UnaryPrefix, self, { + operator: "~", + expression: x + }) + }), self.operator[0] === "!"); + + return best_of(compressor, optimized, self); + } + } + break; + case "&&": + case "||": + var lhs = self.left; + if (lhs.operator == self.operator) { + lhs = lhs.right; + } + if (lhs instanceof AST_Binary + && lhs.operator == (self.operator == "&&" ? "!==" : "===") + && self.right instanceof AST_Binary + && lhs.operator == self.right.operator + && (is_undefined(lhs.left, compressor) && self.right.left instanceof AST_Null + || lhs.left instanceof AST_Null && is_undefined(self.right.left, compressor)) + && !lhs.right.has_side_effects(compressor) + && lhs.right.equivalent_to(self.right.right)) { + var combined = make_node(AST_Binary, self, { + operator: lhs.operator.slice(0, -1), + left: make_node(AST_Null, self), + right: lhs.right + }); + if (lhs !== self.left) { + combined = make_node(AST_Binary, self, { + operator: self.operator, + left: self.left.left, + right: combined + }); + } + return combined; + } + break; + } + if (self.operator == "+" && compressor.in_boolean_context()) { + var ll = self.left.evaluate(compressor); + var rr = self.right.evaluate(compressor); + if (ll && typeof ll == "string") { + return make_sequence(self, [ + self.right, + make_node(AST_True, self) + ]).optimize(compressor); + } + if (rr && typeof rr == "string") { + return make_sequence(self, [ + self.left, + make_node(AST_True, self) + ]).optimize(compressor); + } + } + if (compressor.option("comparisons") && self.is_boolean()) { + if (!(compressor.parent() instanceof AST_Binary) + || compressor.parent() instanceof AST_Assign) { + var negated = make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: self.negate(compressor, first_in_statement(compressor)) + }); + self = best_of(compressor, self, negated); + } + if (compressor.option("unsafe_comps")) { + switch (self.operator) { + case "<": reverse(">"); break; + case "<=": reverse(">="); break; + } + } + } + if (self.operator == "+") { + if (self.right instanceof AST_String + && self.right.getValue() == "" + && self.left.is_string(compressor)) { + return self.left; + } + if (self.left instanceof AST_String + && self.left.getValue() == "" + && self.right.is_string(compressor)) { + return self.right; + } + if (self.left instanceof AST_Binary + && self.left.operator == "+" + && self.left.left instanceof AST_String + && self.left.left.getValue() == "" + && self.right.is_string(compressor)) { + self.left = self.left.right; + return self; + } + } + if (compressor.option("evaluate")) { + switch (self.operator) { + case "&&": + var ll = has_flag(self.left, TRUTHY) + ? true + : has_flag(self.left, FALSY) + ? false + : self.left.evaluate(compressor); + if (!ll) { + return maintain_this_binding(compressor.parent(), compressor.self(), self.left).optimize(compressor); + } else if (!(ll instanceof AST_Node)) { + return make_sequence(self, [ self.left, self.right ]).optimize(compressor); + } + var rr = self.right.evaluate(compressor); + if (!rr) { + if (compressor.in_boolean_context()) { + return make_sequence(self, [ + self.left, + make_node(AST_False, self) + ]).optimize(compressor); + } else { + set_flag(self, FALSY); + } + } else if (!(rr instanceof AST_Node)) { + var parent = compressor.parent(); + if (parent.operator == "&&" && parent.left === compressor.self() || compressor.in_boolean_context()) { + return self.left.optimize(compressor); + } + } + // x || false && y ---> x ? y : false + if (self.left.operator == "||") { + var lr = self.left.right.evaluate(compressor); + if (!lr) return make_node(AST_Conditional, self, { + condition: self.left.left, + consequent: self.right, + alternative: self.left.right + }).optimize(compressor); + } + break; + case "||": + var ll = has_flag(self.left, TRUTHY) + ? true + : has_flag(self.left, FALSY) + ? false + : self.left.evaluate(compressor); + if (!ll) { + return make_sequence(self, [ self.left, self.right ]).optimize(compressor); + } else if (!(ll instanceof AST_Node)) { + return maintain_this_binding(compressor.parent(), compressor.self(), self.left).optimize(compressor); + } + var rr = self.right.evaluate(compressor); + if (!rr) { + var parent = compressor.parent(); + if (parent.operator == "||" && parent.left === compressor.self() || compressor.in_boolean_context()) { + return self.left.optimize(compressor); + } + } else if (!(rr instanceof AST_Node)) { + if (compressor.in_boolean_context()) { + return make_sequence(self, [ + self.left, + make_node(AST_True, self) + ]).optimize(compressor); + } else { + set_flag(self, TRUTHY); + } + } + if (self.left.operator == "&&") { + var lr = self.left.right.evaluate(compressor); + if (lr && !(lr instanceof AST_Node)) return make_node(AST_Conditional, self, { + condition: self.left.left, + consequent: self.left.right, + alternative: self.right + }).optimize(compressor); + } + break; + case "??": + if (is_nullish(self.left, compressor)) { + return self.right; + } + + var ll = self.left.evaluate(compressor); + if (!(ll instanceof AST_Node)) { + // if we know the value for sure we can simply compute right away. + return ll == null ? self.right : self.left; + } + + if (compressor.in_boolean_context()) { + const rr = self.right.evaluate(compressor); + if (!(rr instanceof AST_Node) && !rr) { + return self.left; + } + } + } + var associative = true; + switch (self.operator) { + case "+": + // (x + "foo") + "bar" => x + "foobar" + if (self.right instanceof AST_Constant + && self.left instanceof AST_Binary + && self.left.operator == "+" + && self.left.is_string(compressor)) { + var binary = make_node(AST_Binary, self, { + operator: "+", + left: self.left.right, + right: self.right, + }); + var r = binary.optimize(compressor); + if (binary !== r) { + self = make_node(AST_Binary, self, { + operator: "+", + left: self.left.left, + right: r + }); + } + } + // (x + "foo") + ("bar" + y) => (x + "foobar") + y + if (self.left instanceof AST_Binary + && self.left.operator == "+" + && self.left.is_string(compressor) + && self.right instanceof AST_Binary + && self.right.operator == "+" + && self.right.is_string(compressor)) { + var binary = make_node(AST_Binary, self, { + operator: "+", + left: self.left.right, + right: self.right.left, + }); + var m = binary.optimize(compressor); + if (binary !== m) { + self = make_node(AST_Binary, self, { + operator: "+", + left: make_node(AST_Binary, self.left, { + operator: "+", + left: self.left.left, + right: m + }), + right: self.right.right + }); + } + } + // a + -b => a - b + if (self.right instanceof AST_UnaryPrefix + && self.right.operator == "-" + && self.left.is_number(compressor)) { + self = make_node(AST_Binary, self, { + operator: "-", + left: self.left, + right: self.right.expression + }); + break; + } + // -a + b => b - a + if (self.left instanceof AST_UnaryPrefix + && self.left.operator == "-" + && reversible() + && self.right.is_number(compressor)) { + self = make_node(AST_Binary, self, { + operator: "-", + left: self.right, + right: self.left.expression + }); + break; + } + // `foo${bar}baz` + 1 => `foo${bar}baz1` + if (self.left instanceof AST_TemplateString) { + var l = self.left; + var r = self.right.evaluate(compressor); + if (r != self.right) { + l.segments[l.segments.length - 1].value += String(r); + return l; + } + } + // 1 + `foo${bar}baz` => `1foo${bar}baz` + if (self.right instanceof AST_TemplateString) { + var r = self.right; + var l = self.left.evaluate(compressor); + if (l != self.left) { + r.segments[0].value = String(l) + r.segments[0].value; + return r; + } + } + // `1${bar}2` + `foo${bar}baz` => `1${bar}2foo${bar}baz` + if (self.left instanceof AST_TemplateString + && self.right instanceof AST_TemplateString) { + var l = self.left; + var segments = l.segments; + var r = self.right; + segments[segments.length - 1].value += r.segments[0].value; + for (var i = 1; i < r.segments.length; i++) { + segments.push(r.segments[i]); + } + return l; + } + case "*": + associative = compressor.option("unsafe_math"); + case "&": + case "|": + case "^": + // a + +b => +b + a + if (self.left.is_number(compressor) + && self.right.is_number(compressor) + && reversible() + && !(self.left instanceof AST_Binary + && self.left.operator != self.operator + && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) { + var reversed = make_node(AST_Binary, self, { + operator: self.operator, + left: self.right, + right: self.left + }); + if (self.right instanceof AST_Constant + && !(self.left instanceof AST_Constant)) { + self = best_of(compressor, reversed, self); + } else { + self = best_of(compressor, self, reversed); + } + } + if (associative && self.is_number(compressor)) { + // a + (b + c) => (a + b) + c + if (self.right instanceof AST_Binary + && self.right.operator == self.operator) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: self.left, + right: self.right.left, + start: self.left.start, + end: self.right.left.end + }), + right: self.right.right + }); + } + // (n + 2) + 3 => 5 + n + // (2 * n) * 3 => 6 + n + if (self.right instanceof AST_Constant + && self.left instanceof AST_Binary + && self.left.operator == self.operator) { + if (self.left.left instanceof AST_Constant) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: self.left.left, + right: self.right, + start: self.left.left.start, + end: self.right.end + }), + right: self.left.right + }); + } else if (self.left.right instanceof AST_Constant) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: self.left.right, + right: self.right, + start: self.left.right.start, + end: self.right.end + }), + right: self.left.left + }); + } + } + // (a | 1) | (2 | d) => (3 | a) | b + if (self.left instanceof AST_Binary + && self.left.operator == self.operator + && self.left.right instanceof AST_Constant + && self.right instanceof AST_Binary + && self.right.operator == self.operator + && self.right.left instanceof AST_Constant) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: make_node(AST_Binary, self.left.left, { + operator: self.operator, + left: self.left.right, + right: self.right.left, + start: self.left.right.start, + end: self.right.left.end + }), + right: self.left.left + }), + right: self.right.right + }); + } + } + } + + // bitwise ops + if (bitwise_binop.has(self.operator)) { + // Use De Morgan's laws + // z & (X | y) + // => z & X (given y & z === 0) + // => z & X | {y & z} (given y & z !== 0) + let y, z, x_node, y_node, z_node = self.left; + if ( + self.operator === "&" + && self.right instanceof AST_Binary + && self.right.operator === "|" + && typeof (z = self.left.evaluate(compressor)) === "number" + ) { + if (typeof (y = self.right.right.evaluate(compressor)) === "number") { + // z & (X | y) + x_node = self.right.left; + y_node = self.right.right; + } else if (typeof (y = self.right.left.evaluate(compressor)) === "number") { + // z & (y | X) + x_node = self.right.right; + y_node = self.right.left; + } + + if (x_node && y_node) { + if ((y & z) === 0) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: z_node, + right: x_node + }); + } else { + const reordered_ops = make_node(AST_Binary, self, { + operator: "|", + left: make_node(AST_Binary, self, { + operator: "&", + left: x_node, + right: z_node + }), + right: make_node_from_constant(y & z, y_node), + }); + + self = best_of(compressor, self, reordered_ops); + } + } + } + + // x ^ x => 0 + // x | x => 0 | x + // x & x => 0 | x + const same_operands = self.left.equivalent_to(self.right) && !self.left.has_side_effects(compressor); + if (same_operands) { + if (self.operator === "^") { + return make_node(AST_Number, self, { value: 0 }); + } + if (self.operator === "|" || self.operator === "&") { + self.left = make_node(AST_Number, self, { value: 0 }); + self.operator = "|"; + } + } + + + // Shifts that do nothing + // {anything} >> 0 => {anything} | 0 + // {anything} << 0 => {anything} | 0 + if ( + (self.operator === "<<" || self.operator === ">>") + && self.right instanceof AST_Number && self.right.value === 0 + ) { + self.operator = "|"; + } + + // Find useless to-bitwise conversions + // {32 bit integer} | 0 => {32 bit integer} + // {32 bit integer} ^ 0 => {32 bit integer} + const zero_side = self.right instanceof AST_Number && self.right.value === 0 ? self.right + : self.left instanceof AST_Number && self.left.value === 0 ? self.left + : null; + const non_zero_side = zero_side && (zero_side === self.right ? self.left : self.right); + if ( + zero_side + && (self.operator === "|" || self.operator === "^") + && (non_zero_side.is_32_bit_integer() || compressor.in_32_bit_context()) + ) { + return non_zero_side; + } + + // {anything} & 0 => 0 + if ( + zero_side + && self.operator === "&" + && !non_zero_side.has_side_effects(compressor) + ) { + return zero_side; + } + + const is_full_mask = (node) => + node instanceof AST_Number && node.value === -1 + || + node instanceof AST_UnaryPrefix && ( + node.operator === "-" + && node.expression instanceof AST_Number + && node.expression.value === 1 + || node.operator === "~" + && node.expression instanceof AST_Number + && node.expression.value === 0); + + const full_mask = is_full_mask(self.right) ? self.right + : is_full_mask(self.left) ? self.left + : null; + const non_full_mask_side = full_mask && (full_mask === self.right ? self.left : self.right); + + switch (self.operator) { + case "|": + // {anything} | -1 => -1 + if (full_mask && !non_full_mask_side.has_side_effects(compressor)) { + return full_mask; + } + + break; + case "&": + // {32 bit integer} & -1 => {32 bit integer} + if ( + full_mask + && (non_full_mask_side.is_32_bit_integer() || compressor.in_32_bit_context()) + ) { + return non_full_mask_side; + } + + break; + case "^": + // {anything} ^ -1 => ~{anything} + if (full_mask) { + return non_full_mask_side.bitwise_negate(compressor.in_32_bit_context()); + } + + // ~x ^ ~y => x ^ y + if ( + self.left instanceof AST_UnaryPrefix + && self.left.operator === "~" + && self.right instanceof AST_UnaryPrefix + && self.right.operator === "~" + ) { + self = make_node(AST_Binary, self, { + operator: "^", + left: self.left.expression, + right: self.right.expression + }); + } + + break; + } + } + } + // x && (y && z) ==> x && y && z + // x || (y || z) ==> x || y || z + // x + ("y" + z) ==> x + "y" + z + // "x" + (y + "z")==> "x" + y + "z" + if (self.right instanceof AST_Binary + && self.right.operator == self.operator + && (lazy_op.has(self.operator) + || (self.operator == "+" + && (self.right.left.is_string(compressor) + || (self.left.is_string(compressor) + && self.right.right.is_string(compressor))))) + ) { + self.left = make_node(AST_Binary, self.left, { + operator : self.operator, + left : self.left.transform(compressor), + right : self.right.left.transform(compressor) + }); + self.right = self.right.right.transform(compressor); + return self.transform(compressor); + } + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + return self; +}); + +def_optimize(AST_SymbolExport, function(self) { + return self; +}); + +def_optimize(AST_SymbolRef, function(self, compressor) { + if ( + !compressor.option("ie8") + && is_undeclared_ref(self) + && !compressor.find_parent(AST_With) + ) { + switch (self.name) { + case "undefined": + return make_node(AST_Undefined, self).optimize(compressor); + case "NaN": + return make_node(AST_NaN, self).optimize(compressor); + case "Infinity": + return make_node(AST_Infinity, self).optimize(compressor); + } + } + + if (compressor.option("reduce_vars") && !compressor.is_lhs()) { + return inline_into_symbolref(self, compressor); + } else { + return self; + } +}); + +function is_atomic(lhs, self) { + return lhs instanceof AST_SymbolRef || lhs.TYPE === self.TYPE; +} + +def_optimize(AST_Undefined, function(self, compressor) { + if (compressor.option("unsafe_undefined")) { + var undef = find_variable(compressor, "undefined"); + if (undef) { + var ref = make_node(AST_SymbolRef, self, { + name : "undefined", + scope : undef.scope, + thedef : undef + }); + set_flag(ref, UNDEFINED); + return ref; + } + } + var lhs = compressor.is_lhs(); + if (lhs && is_atomic(lhs, self)) return self; + return make_node(AST_UnaryPrefix, self, { + operator: "void", + expression: make_node(AST_Number, self, { + value: 0 + }) + }); +}); + +def_optimize(AST_Infinity, function(self, compressor) { + var lhs = compressor.is_lhs(); + if (lhs && is_atomic(lhs, self)) return self; + if ( + compressor.option("keep_infinity") + && !(lhs && !is_atomic(lhs, self)) + && !find_variable(compressor, "Infinity") + ) { + return self; + } + return make_node(AST_Binary, self, { + operator: "/", + left: make_node(AST_Number, self, { + value: 1 + }), + right: make_node(AST_Number, self, { + value: 0 + }) + }); +}); + +def_optimize(AST_NaN, function(self, compressor) { + var lhs = compressor.is_lhs(); + if (lhs && !is_atomic(lhs, self) + || find_variable(compressor, "NaN")) { + return make_node(AST_Binary, self, { + operator: "/", + left: make_node(AST_Number, self, { + value: 0 + }), + right: make_node(AST_Number, self, { + value: 0 + }) + }); + } + return self; +}); + +const ASSIGN_OPS = makePredicate("+ - / * % >> << >>> | ^ &"); +const ASSIGN_OPS_COMMUTATIVE = makePredicate("* | ^ &"); +def_optimize(AST_Assign, function(self, compressor) { + if (self.logical) { + return self.lift_sequences(compressor); + } + + var def; + // x = x ---> x + if ( + self.operator === "=" + && self.left instanceof AST_SymbolRef + && self.left.name !== "arguments" + && !(def = self.left.definition()).undeclared + && self.right.equivalent_to(self.left) + ) { + return self.right; + } + + if (compressor.option("dead_code") + && self.left instanceof AST_SymbolRef + && (def = self.left.definition()).scope === compressor.find_parent(AST_Lambda)) { + var level = 0, node, parent = self; + do { + node = parent; + parent = compressor.parent(level++); + if (parent instanceof AST_Exit) { + if (in_try(level, parent)) break; + if (is_reachable(def.scope, [ def ])) break; + if (self.operator == "=") return self.right; + def.fixed = false; + return make_node(AST_Binary, self, { + operator: self.operator.slice(0, -1), + left: self.left, + right: self.right + }).optimize(compressor); + } + } while (parent instanceof AST_Binary && parent.right === node + || parent instanceof AST_Sequence && parent.tail_node() === node); + } + self = self.lift_sequences(compressor); + + if (self.operator == "=" && self.left instanceof AST_SymbolRef && self.right instanceof AST_Binary) { + // x = expr1 OP expr2 + if (self.right.left instanceof AST_SymbolRef + && self.right.left.name == self.left.name + && ASSIGN_OPS.has(self.right.operator)) { + // x = x - 2 ---> x -= 2 + self.operator = self.right.operator + "="; + self.right = self.right.right; + } else if (self.right.right instanceof AST_SymbolRef + && self.right.right.name == self.left.name + && ASSIGN_OPS_COMMUTATIVE.has(self.right.operator) + && !self.right.left.has_side_effects(compressor)) { + // x = 2 & x ---> x &= 2 + self.operator = self.right.operator + "="; + self.right = self.right.left; + } + } + return self; + + function in_try(level, node) { + function may_assignment_throw() { + const right = self.right; + self.right = make_node(AST_Null, right); + const may_throw = node.may_throw(compressor); + self.right = right; + + return may_throw; + } + + var stop_at = self.left.definition().scope.get_defun_scope(); + var parent; + while ((parent = compressor.parent(level++)) !== stop_at) { + if (parent instanceof AST_Try) { + if (parent.bfinally) return true; + if (parent.bcatch && may_assignment_throw()) return true; + } + } + } +}); + +def_optimize(AST_DefaultAssign, function(self, compressor) { + if (!compressor.option("evaluate")) { + return self; + } + var evaluateRight = self.right.evaluate(compressor); + + // `[x = undefined] = foo` ---> `[x] = foo` + // `(arg = undefined) => ...` ---> `(arg) => ...` (unless `keep_fargs`) + // `((arg = undefined) => ...)()` ---> `((arg) => ...)()` + let lambda, iife; + if (evaluateRight === undefined) { + if ( + (lambda = compressor.parent()) instanceof AST_Lambda + ? ( + compressor.option("keep_fargs") === false + || (iife = compressor.parent(1)).TYPE === "Call" + && iife.expression === lambda + ) + : true + ) { + self = self.left; + } + } else if (evaluateRight !== self.right) { + evaluateRight = make_node_from_constant(evaluateRight, self.right); + self.right = best_of_expression(evaluateRight, self.right); + } + + return self; +}); + +function is_nullish_check(check, check_subject, compressor) { + if (check_subject.may_throw(compressor)) return false; + + let nullish_side; + + // foo == null + if ( + check instanceof AST_Binary + && check.operator === "==" + // which side is nullish? + && ( + (nullish_side = is_nullish(check.left, compressor) && check.left) + || (nullish_side = is_nullish(check.right, compressor) && check.right) + ) + // is the other side the same as the check_subject + && ( + nullish_side === check.left + ? check.right + : check.left + ).equivalent_to(check_subject) + ) { + return true; + } + + // foo === null || foo === undefined + if (check instanceof AST_Binary && check.operator === "||") { + let null_cmp; + let undefined_cmp; + + const find_comparison = cmp => { + if (!( + cmp instanceof AST_Binary + && (cmp.operator === "===" || cmp.operator === "==") + )) { + return false; + } + + let found = 0; + let defined_side; + + if (cmp.left instanceof AST_Null) { + found++; + null_cmp = cmp; + defined_side = cmp.right; + } + if (cmp.right instanceof AST_Null) { + found++; + null_cmp = cmp; + defined_side = cmp.left; + } + if (is_undefined(cmp.left, compressor)) { + found++; + undefined_cmp = cmp; + defined_side = cmp.right; + } + if (is_undefined(cmp.right, compressor)) { + found++; + undefined_cmp = cmp; + defined_side = cmp.left; + } + + if (found !== 1) { + return false; + } + + if (!defined_side.equivalent_to(check_subject)) { + return false; + } + + return true; + }; + + if (!find_comparison(check.left)) return false; + if (!find_comparison(check.right)) return false; + + if (null_cmp && undefined_cmp && null_cmp !== undefined_cmp) { + return true; + } + } + + return false; +} + +def_optimize(AST_Conditional, function(self, compressor) { + if (!compressor.option("conditionals")) return self; + // This looks like lift_sequences(), should probably be under "sequences" + if (self.condition instanceof AST_Sequence) { + var expressions = self.condition.expressions.slice(); + self.condition = expressions.pop(); + expressions.push(self); + return make_sequence(self, expressions); + } + var cond = self.condition.evaluate(compressor); + if (cond !== self.condition) { + if (cond) { + return maintain_this_binding(compressor.parent(), compressor.self(), self.consequent); + } else { + return maintain_this_binding(compressor.parent(), compressor.self(), self.alternative); + } + } + var negated = cond.negate(compressor, first_in_statement(compressor)); + if (best_of(compressor, cond, negated) === negated) { + self = make_node(AST_Conditional, self, { + condition: negated, + consequent: self.alternative, + alternative: self.consequent + }); + } + var condition = self.condition; + var consequent = self.consequent; + var alternative = self.alternative; + // x?x:y --> x||y + if (condition instanceof AST_SymbolRef + && consequent instanceof AST_SymbolRef + && condition.definition() === consequent.definition()) { + return make_node(AST_Binary, self, { + operator: "||", + left: condition, + right: alternative + }); + } + // if (foo) exp = something; else exp = something_else; + // | + // v + // exp = foo ? something : something_else; + if ( + consequent instanceof AST_Assign + && alternative instanceof AST_Assign + && consequent.operator === alternative.operator + && consequent.logical === alternative.logical + && consequent.left.equivalent_to(alternative.left) + && (!self.condition.has_side_effects(compressor) + || consequent.operator == "=" + && !consequent.left.has_side_effects(compressor)) + ) { + return make_node(AST_Assign, self, { + operator: consequent.operator, + left: consequent.left, + logical: consequent.logical, + right: make_node(AST_Conditional, self, { + condition: self.condition, + consequent: consequent.right, + alternative: alternative.right + }) + }); + } + // x ? y(a) : y(b) --> y(x ? a : b) + var arg_index; + if (consequent instanceof AST_Call + && alternative.TYPE === consequent.TYPE + && consequent.args.length > 0 + && consequent.args.length == alternative.args.length + && consequent.expression.equivalent_to(alternative.expression) + && !self.condition.has_side_effects(compressor) + && !consequent.expression.has_side_effects(compressor) + && typeof (arg_index = single_arg_diff()) == "number") { + var node = consequent.clone(); + node.args[arg_index] = make_node(AST_Conditional, self, { + condition: self.condition, + consequent: consequent.args[arg_index], + alternative: alternative.args[arg_index] + }); + return node; + } + // a ? b : c ? b : d --> (a || c) ? b : d + if (alternative instanceof AST_Conditional + && consequent.equivalent_to(alternative.consequent)) { + return make_node(AST_Conditional, self, { + condition: make_node(AST_Binary, self, { + operator: "||", + left: condition, + right: alternative.condition + }), + consequent: consequent, + alternative: alternative.alternative + }).optimize(compressor); + } + + // a == null ? b : a -> a ?? b + if ( + compressor.option("ecma") >= 2020 && + is_nullish_check(condition, alternative, compressor) + ) { + return make_node(AST_Binary, self, { + operator: "??", + left: alternative, + right: consequent + }).optimize(compressor); + } + + // a ? b : (c, b) --> (a || c), b + if (alternative instanceof AST_Sequence + && consequent.equivalent_to(alternative.expressions[alternative.expressions.length - 1])) { + return make_sequence(self, [ + make_node(AST_Binary, self, { + operator: "||", + left: condition, + right: make_sequence(self, alternative.expressions.slice(0, -1)) + }), + consequent + ]).optimize(compressor); + } + // a ? b : (c && b) --> (a || c) && b + if (alternative instanceof AST_Binary + && alternative.operator == "&&" + && consequent.equivalent_to(alternative.right)) { + return make_node(AST_Binary, self, { + operator: "&&", + left: make_node(AST_Binary, self, { + operator: "||", + left: condition, + right: alternative.left + }), + right: consequent + }).optimize(compressor); + } + // x?y?z:a:a --> x&&y?z:a + if (consequent instanceof AST_Conditional + && consequent.alternative.equivalent_to(alternative)) { + return make_node(AST_Conditional, self, { + condition: make_node(AST_Binary, self, { + left: self.condition, + operator: "&&", + right: consequent.condition + }), + consequent: consequent.consequent, + alternative: alternative + }); + } + // x ? y : y --> x, y + if (consequent.equivalent_to(alternative)) { + return make_sequence(self, [ + self.condition, + consequent + ]).optimize(compressor); + } + // x ? y || z : z --> x && y || z + if (consequent instanceof AST_Binary + && consequent.operator == "||" + && consequent.right.equivalent_to(alternative)) { + return make_node(AST_Binary, self, { + operator: "||", + left: make_node(AST_Binary, self, { + operator: "&&", + left: self.condition, + right: consequent.left + }), + right: alternative + }).optimize(compressor); + } + + const in_bool = compressor.in_boolean_context(); + if (is_true(self.consequent)) { + if (is_false(self.alternative)) { + // c ? true : false ---> !!c + return booleanize(self.condition); + } + // c ? true : x ---> !!c || x + return make_node(AST_Binary, self, { + operator: "||", + left: booleanize(self.condition), + right: self.alternative + }); + } + if (is_false(self.consequent)) { + if (is_true(self.alternative)) { + // c ? false : true ---> !c + return booleanize(self.condition.negate(compressor)); + } + // c ? false : x ---> !c && x + return make_node(AST_Binary, self, { + operator: "&&", + left: booleanize(self.condition.negate(compressor)), + right: self.alternative + }); + } + if (is_true(self.alternative)) { + // c ? x : true ---> !c || x + return make_node(AST_Binary, self, { + operator: "||", + left: booleanize(self.condition.negate(compressor)), + right: self.consequent + }); + } + if (is_false(self.alternative)) { + // c ? x : false ---> !!c && x + return make_node(AST_Binary, self, { + operator: "&&", + left: booleanize(self.condition), + right: self.consequent + }); + } + + return self; + + function booleanize(node) { + if (node.is_boolean()) return node; + // !!expression + return make_node(AST_UnaryPrefix, node, { + operator: "!", + expression: node.negate(compressor) + }); + } + + // AST_True or !0 + function is_true(node) { + return node instanceof AST_True + || in_bool + && node instanceof AST_Constant + && node.getValue() + || (node instanceof AST_UnaryPrefix + && node.operator == "!" + && node.expression instanceof AST_Constant + && !node.expression.getValue()); + } + // AST_False or !1 + function is_false(node) { + return node instanceof AST_False + || in_bool + && node instanceof AST_Constant + && !node.getValue() + || (node instanceof AST_UnaryPrefix + && node.operator == "!" + && node.expression instanceof AST_Constant + && node.expression.getValue()); + } + + function single_arg_diff() { + var a = consequent.args; + var b = alternative.args; + for (var i = 0, len = a.length; i < len; i++) { + if (a[i] instanceof AST_Expansion) return; + if (!a[i].equivalent_to(b[i])) { + if (b[i] instanceof AST_Expansion) return; + for (var j = i + 1; j < len; j++) { + if (a[j] instanceof AST_Expansion) return; + if (!a[j].equivalent_to(b[j])) return; + } + return i; + } + } + } +}); + +def_optimize(AST_Boolean, function(self, compressor) { + if (compressor.in_boolean_context()) return make_node(AST_Number, self, { + value: +self.value + }); + var p = compressor.parent(); + if (compressor.option("booleans_as_integers")) { + if (p instanceof AST_Binary && (p.operator == "===" || p.operator == "!==")) { + p.operator = p.operator.replace(/=$/, ""); + } + return make_node(AST_Number, self, { + value: +self.value + }); + } + if (compressor.option("booleans")) { + if (p instanceof AST_Binary && (p.operator == "==" + || p.operator == "!=")) { + return make_node(AST_Number, self, { + value: +self.value + }); + } + return make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: make_node(AST_Number, self, { + value: 1 - self.value + }) + }); + } + return self; +}); + +function safe_to_flatten(value, compressor) { + if (value instanceof AST_SymbolRef) { + value = value.fixed_value(); + } + if (!value) return false; + if (!(value instanceof AST_Lambda || value instanceof AST_Class)) return true; + if (!(value instanceof AST_Lambda && value.contains_this())) return true; + return compressor.parent() instanceof AST_New; +} + +AST_PropAccess.DEFMETHOD("flatten_object", function(key, compressor) { + if (!compressor.option("properties")) return; + if (key === "__proto__") return; + + var arrows = compressor.option("unsafe_arrows") && compressor.option("ecma") >= 2015; + var expr = this.expression; + if (expr instanceof AST_Object) { + var props = expr.properties; + + for (var i = props.length; --i >= 0;) { + var prop = props[i]; + + if ("" + (prop instanceof AST_ConciseMethod ? prop.key.name : prop.key) == key) { + const all_props_flattenable = props.every((p) => + (p instanceof AST_ObjectKeyVal + || arrows && p instanceof AST_ConciseMethod && !p.is_generator + ) + && !p.computed_key() + ); + + if (!all_props_flattenable) return; + if (!safe_to_flatten(prop.value, compressor)) return; + + return make_node(AST_Sub, this, { + expression: make_node(AST_Array, expr, { + elements: props.map(function(prop) { + var v = prop.value; + if (v instanceof AST_Accessor) { + v = make_node(AST_Function, v, v); + } + + var k = prop.key; + if (k instanceof AST_Node && !(k instanceof AST_SymbolMethod)) { + return make_sequence(prop, [ k, v ]); + } + + return v; + }) + }), + property: make_node(AST_Number, this, { + value: i + }) + }); + } + } + } +}); + +def_optimize(AST_Sub, function(self, compressor) { + var expr = self.expression; + var prop = self.property; + if (compressor.option("properties")) { + var key = prop.evaluate(compressor); + if (key !== prop) { + if (typeof key == "string") { + if (key == "undefined") { + key = undefined; + } else { + var value = parseFloat(key); + if (value.toString() == key) { + key = value; + } + } + } + prop = self.property = best_of_expression( + prop, + make_node_from_constant(key, prop).transform(compressor) + ); + var property = "" + key; + if (is_basic_identifier_string(property) + && property.length <= prop.size() + 1) { + return make_node(AST_Dot, self, { + expression: expr, + optional: self.optional, + property: property, + quote: prop.quote, + }).optimize(compressor); + } + } + } + var fn; + OPT_ARGUMENTS: if (compressor.option("arguments") + && expr instanceof AST_SymbolRef + && expr.name == "arguments" + && expr.definition().orig.length == 1 + && (fn = expr.scope) instanceof AST_Lambda + && fn.uses_arguments + && !(fn instanceof AST_Arrow) + && prop instanceof AST_Number) { + var index = prop.getValue(); + var params = new Set(); + var argnames = fn.argnames; + for (var n = 0; n < argnames.length; n++) { + if (!(argnames[n] instanceof AST_SymbolFunarg)) { + break OPT_ARGUMENTS; // destructuring parameter - bail + } + var param = argnames[n].name; + if (params.has(param)) { + break OPT_ARGUMENTS; // duplicate parameter - bail + } + params.add(param); + } + var argname = fn.argnames[index]; + if (argname && compressor.has_directive("use strict")) { + var def = argname.definition(); + if (!compressor.option("reduce_vars") || def.assignments || def.orig.length > 1) { + argname = null; + } + } else if (!argname && !compressor.option("keep_fargs") && index < fn.argnames.length + 5) { + while (index >= fn.argnames.length) { + argname = fn.create_symbol(AST_SymbolFunarg, { + source: fn, + scope: fn, + tentative_name: "argument_" + fn.argnames.length, + }); + fn.argnames.push(argname); + } + } + if (argname) { + var sym = make_node(AST_SymbolRef, self, argname); + sym.reference({}); + clear_flag(argname, UNUSED); + return sym; + } + } + if (compressor.is_lhs()) return self; + if (key !== prop) { + var sub = self.flatten_object(property, compressor); + if (sub) { + expr = self.expression = sub.expression; + prop = self.property = sub.property; + } + } + if (compressor.option("properties") && compressor.option("side_effects") + && prop instanceof AST_Number && expr instanceof AST_Array) { + var index = prop.getValue(); + var elements = expr.elements; + var retValue = elements[index]; + FLATTEN: if (safe_to_flatten(retValue, compressor)) { + var flatten = true; + var values = []; + for (var i = elements.length; --i > index;) { + var value = elements[i].drop_side_effect_free(compressor); + if (value) { + values.unshift(value); + if (flatten && value.has_side_effects(compressor)) flatten = false; + } + } + if (retValue instanceof AST_Expansion) break FLATTEN; + retValue = retValue instanceof AST_Hole ? make_node(AST_Undefined, retValue) : retValue; + if (!flatten) values.unshift(retValue); + while (--i >= 0) { + var value = elements[i]; + if (value instanceof AST_Expansion) break FLATTEN; + value = value.drop_side_effect_free(compressor); + if (value) values.unshift(value); + else index--; + } + if (flatten) { + values.push(retValue); + return make_sequence(self, values).optimize(compressor); + } else return make_node(AST_Sub, self, { + expression: make_node(AST_Array, expr, { + elements: values + }), + property: make_node(AST_Number, prop, { + value: index + }) + }); + } + } + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + return self; +}); + +def_optimize(AST_Chain, function (self, compressor) { + if (is_nullish(self.expression, compressor)) { + let parent = compressor.parent(); + // It's valid to delete a nullish optional chain, but if we optimized + // this to `delete undefined` then it would appear to be a syntax error + // when we try to optimize the delete. Thankfully, `delete 0` is fine. + if (parent instanceof AST_UnaryPrefix && parent.operator === "delete") { + return make_node_from_constant(0, self); + } + return make_node(AST_Undefined, self); + } + return self; +}); + +def_optimize(AST_Dot, function(self, compressor) { + const parent = compressor.parent(); + if (compressor.is_lhs()) return self; + if (compressor.option("unsafe_proto") + && self.expression instanceof AST_Dot + && self.expression.property == "prototype") { + var exp = self.expression.expression; + if (is_undeclared_ref(exp)) switch (exp.name) { + case "Array": + self.expression = make_node(AST_Array, self.expression, { + elements: [] + }); + break; + case "Function": + self.expression = make_node(AST_Function, self.expression, { + argnames: [], + body: [] + }); + break; + case "Number": + self.expression = make_node(AST_Number, self.expression, { + value: 0 + }); + break; + case "Object": + self.expression = make_node(AST_Object, self.expression, { + properties: [] + }); + break; + case "RegExp": + self.expression = make_node(AST_RegExp, self.expression, { + value: { source: "t", flags: "" } + }); + break; + case "String": + self.expression = make_node(AST_String, self.expression, { + value: "" + }); + break; + } + } + if (!(parent instanceof AST_Call) || !has_annotation(parent, _NOINLINE)) { + const sub = self.flatten_object(self.property, compressor); + if (sub) return sub.optimize(compressor); + } + + if (self.expression instanceof AST_PropAccess + && parent instanceof AST_PropAccess) { + return self; + } + + let ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + return self; +}); + +function literals_in_boolean_context(self, compressor) { + if (compressor.in_boolean_context()) { + return best_of(compressor, self, make_sequence(self, [ + self, + make_node(AST_True, self) + ]).optimize(compressor)); + } + return self; +} + +function inline_array_like_spread(elements) { + for (var i = 0; i < elements.length; i++) { + var el = elements[i]; + if (el instanceof AST_Expansion) { + var expr = el.expression; + if ( + expr instanceof AST_Array + && !expr.elements.some(elm => elm instanceof AST_Hole) + ) { + elements.splice(i, 1, ...expr.elements); + // Step back one, as the element at i is now new. + i--; + } + // In array-like spread, spreading a non-iterable value is TypeError. + // We therefore can’t optimize anything else, unlike with object spread. + } + } +} + +def_optimize(AST_Array, function(self, compressor) { + var optimized = literals_in_boolean_context(self, compressor); + if (optimized !== self) { + return optimized; + } + inline_array_like_spread(self.elements); + return self; +}); + +function inline_object_prop_spread(props) { + for (var i = 0; i < props.length; i++) { + var prop = props[i]; + if (prop instanceof AST_Expansion) { + const expr = prop.expression; + if ( + expr instanceof AST_Object + && expr.properties.every(prop => prop instanceof AST_ObjectKeyVal) + ) { + props.splice(i, 1, ...expr.properties); + // Step back one, as the property at i is now new. + i--; + } else if (( + // `expr.is_constant()` returns `false` for `AST_RegExp`, so need both. + expr instanceof AST_Constant + || expr.is_constant() + ) && !(expr instanceof AST_String)) { + // Unlike array-like spread, in object spread, spreading a + // non-iterable value silently does nothing; it is thus safe + // to remove. AST_String is the only iterable constant. + props.splice(i, 1); + i--; + } + } + } +} + +def_optimize(AST_Object, function(self, compressor) { + var optimized = literals_in_boolean_context(self, compressor); + if (optimized !== self) { + return optimized; + } + inline_object_prop_spread(self.properties); + return self; +}); + +def_optimize(AST_RegExp, literals_in_boolean_context); + +def_optimize(AST_Return, function(self, compressor) { + if (self.value && is_undefined(self.value, compressor)) { + self.value = null; + } + return self; +}); + +def_optimize(AST_Arrow, opt_AST_Lambda); + +def_optimize(AST_Function, function(self, compressor) { + self = opt_AST_Lambda(self, compressor); + if (compressor.option("unsafe_arrows") + && compressor.option("ecma") >= 2015 + && !self.name + && !self.is_generator + && !self.uses_arguments + && !self.pinned()) { + const uses_this = walk(self, node => { + if (node instanceof AST_This) return walk_abort; + }); + if (!uses_this) return make_node(AST_Arrow, self, self).optimize(compressor); + } + return self; +}); + +def_optimize(AST_Class, function(self) { + for (let i = 0; i < self.properties.length; i++) { + const prop = self.properties[i]; + if (prop instanceof AST_ClassStaticBlock && prop.body.length == 0) { + self.properties.splice(i, 1); + i--; + } + } + + return self; +}); + +def_optimize(AST_ClassStaticBlock, function(self, compressor) { + tighten_body(self.body, compressor); + return self; +}); + +def_optimize(AST_Yield, function(self, compressor) { + if (self.expression && !self.is_star && is_undefined(self.expression, compressor)) { + self.expression = null; + } + return self; +}); + +def_optimize(AST_TemplateString, function(self, compressor) { + if ( + !compressor.option("evaluate") + || compressor.parent() instanceof AST_PrefixedTemplateString + ) { + return self; + } + + var segments = []; + for (var i = 0; i < self.segments.length; i++) { + var segment = self.segments[i]; + if (segment instanceof AST_Node) { + var result = segment.evaluate(compressor); + // Evaluate to constant value + // Constant value shorter than ${segment} + if (result !== segment && (result + "").length <= segment.size() + "${}".length) { + // There should always be a previous and next segment if segment is a node + segments[segments.length - 1].value = segments[segments.length - 1].value + result + self.segments[++i].value; + continue; + } + // `before ${`innerBefore ${any} innerAfter`} after` => `before innerBefore ${any} innerAfter after` + // TODO: + // `before ${'test' + foo} after` => `before innerBefore ${any} innerAfter after` + // `before ${foo + 'test} after` => `before innerBefore ${any} innerAfter after` + if (segment instanceof AST_TemplateString) { + var inners = segment.segments; + segments[segments.length - 1].value += inners[0].value; + for (var j = 1; j < inners.length; j++) { + segment = inners[j]; + segments.push(segment); + } + continue; + } + } + segments.push(segment); + } + self.segments = segments; + + // `foo` => "foo" + if (segments.length == 1) { + return make_node(AST_String, self, segments[0]); + } + + if ( + segments.length === 3 + && segments[1] instanceof AST_Node + && ( + segments[1].is_string(compressor) + || segments[1].is_number(compressor) + || is_nullish(segments[1], compressor) + || compressor.option("unsafe") + ) + ) { + // `foo${bar}` => "foo" + bar + if (segments[2].value === "") { + return make_node(AST_Binary, self, { + operator: "+", + left: make_node(AST_String, self, { + value: segments[0].value, + }), + right: segments[1], + }); + } + // `${bar}baz` => bar + "baz" + if (segments[0].value === "") { + return make_node(AST_Binary, self, { + operator: "+", + left: segments[1], + right: make_node(AST_String, self, { + value: segments[2].value, + }), + }); + } + } + return self; +}); + +def_optimize(AST_PrefixedTemplateString, function(self) { + return self; +}); + +// ["p"]:1 ---> p:1 +// [42]:1 ---> 42:1 +function lift_key(self, compressor) { + if (!compressor.option("computed_props")) return self; + // save a comparison in the typical case + if (!(self.key instanceof AST_Constant)) return self; + // allow certain acceptable props as not all AST_Constants are true constants + if (self.key instanceof AST_String || self.key instanceof AST_Number) { + const key = self.key.value.toString(); + + if (key === "__proto__") return self; + if (key == "constructor" + && compressor.parent() instanceof AST_Class) return self; + if (self instanceof AST_ObjectKeyVal) { + self.quote = self.key.quote; + self.key = key; + } else if (self instanceof AST_ClassProperty) { + self.quote = self.key.quote; + self.key = make_node(AST_SymbolClassProperty, self.key, { + name: key, + }); + } else { + self.quote = self.key.quote; + self.key = make_node(AST_SymbolMethod, self.key, { + name: key, + }); + } + } + return self; +} + +def_optimize(AST_ObjectProperty, lift_key); + +def_optimize(AST_ConciseMethod, function(self, compressor) { + lift_key(self, compressor); + // p(){return x;} ---> p:()=>x + if (compressor.option("arrows") + && compressor.parent() instanceof AST_Object + && !self.is_generator + && !self.value.uses_arguments + && !self.value.pinned() + && self.value.body.length == 1 + && self.value.body[0] instanceof AST_Return + && self.value.body[0].value + && !self.value.contains_this()) { + var arrow = make_node(AST_Arrow, self.value, self.value); + arrow.async = self.async; + arrow.is_generator = self.is_generator; + return make_node(AST_ObjectKeyVal, self, { + key: self.key instanceof AST_SymbolMethod ? self.key.name : self.key, + value: arrow, + quote: self.quote, + }); + } + return self; +}); + +def_optimize(AST_ObjectKeyVal, function(self, compressor) { + lift_key(self, compressor); + // p:function(){} ---> p(){} + // p:function*(){} ---> *p(){} + // p:async function(){} ---> async p(){} + // p:()=>{} ---> p(){} + // p:async()=>{} ---> async p(){} + var unsafe_methods = compressor.option("unsafe_methods"); + if (unsafe_methods + && compressor.option("ecma") >= 2015 + && (!(unsafe_methods instanceof RegExp) || unsafe_methods.test(self.key + ""))) { + var key = self.key; + var value = self.value; + var is_arrow_with_block = value instanceof AST_Arrow + && Array.isArray(value.body) + && !value.contains_this(); + if ((is_arrow_with_block || value instanceof AST_Function) && !value.name) { + return make_node(AST_ConciseMethod, self, { + async: value.async, + is_generator: value.is_generator, + key: key instanceof AST_Node ? key : make_node(AST_SymbolMethod, self, { + name: key, + }), + value: make_node(AST_Accessor, value, value), + quote: self.quote, + }); + } + } + return self; +}); + +def_optimize(AST_Destructuring, function(self, compressor) { + if (compressor.option("pure_getters") == true + && compressor.option("unused") + && !self.is_array + && Array.isArray(self.names) + && !is_destructuring_export_decl(compressor) + && !(self.names[self.names.length - 1] instanceof AST_Expansion)) { + var keep = []; + for (var i = 0; i < self.names.length; i++) { + var elem = self.names[i]; + if (!(elem instanceof AST_ObjectKeyVal + && typeof elem.key == "string" + && elem.value instanceof AST_SymbolDeclaration + && !should_retain(compressor, elem.value.definition()))) { + keep.push(elem); + } + } + if (keep.length != self.names.length) { + self.names = keep; + } + } + return self; + + function is_destructuring_export_decl(compressor) { + var ancestors = [/^VarDef$/, /^(Const|Let|Var)$/, /^Export$/]; + for (var a = 0, p = 0, len = ancestors.length; a < len; p++) { + var parent = compressor.parent(p); + if (!parent) return false; + if (a === 0 && parent.TYPE == "Destructuring") continue; + if (!ancestors[a].test(parent.TYPE)) { + return false; + } + a++; + } + return true; + } + + function should_retain(compressor, def) { + if (def.references.length) return true; + if (!def.global) return false; + if (compressor.toplevel.vars) { + if (compressor.top_retain) { + return compressor.top_retain(def); + } + return false; + } + return true; + } +}); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +// a small wrapper around source-map and @jridgewell/source-map +function* SourceMap(options) { + options = defaults(options, { + file : null, + root : null, + orig : null, + files: {}, + }); + + var orig_map; + var generator = new sourceMap.SourceMapGenerator({ + file : options.file, + sourceRoot : options.root + }); + + let sourcesContent = {__proto__: null}; + let files = options.files; + for (var name in files) if (HOP(files, name)) { + sourcesContent[name] = files[name]; + } + if (options.orig) { + // We support both @jridgewell/source-map (which has a sync + // SourceMapConsumer) and source-map (which has an async + // SourceMapConsumer). + orig_map = yield new sourceMap.SourceMapConsumer(options.orig); + if (orig_map.sourcesContent) { + orig_map.sources.forEach(function(source, i) { + var content = orig_map.sourcesContent[i]; + if (content) { + sourcesContent[source] = content; + } + }); + } + } + + function add(source, gen_line, gen_col, orig_line, orig_col, name) { + let generatedPos = { line: gen_line, column: gen_col }; + + if (orig_map) { + var info = orig_map.originalPositionFor({ + line: orig_line, + column: orig_col + }); + if (info.source === null) { + generator.addMapping({ + generated: generatedPos, + original: null, + source: null, + name: null + }); + return; + } + source = info.source; + orig_line = info.line; + orig_col = info.column; + name = info.name || name; + } + generator.addMapping({ + generated : generatedPos, + original : { line: orig_line, column: orig_col }, + source : source, + name : name + }); + generator.setSourceContent(source, sourcesContent[source]); + } + + function clean(map) { + const allNull = map.sourcesContent && map.sourcesContent.every(c => c == null); + if (allNull) delete map.sourcesContent; + if (map.file === undefined) delete map.file; + if (map.sourceRoot === undefined) delete map.sourceRoot; + return map; + } + + function getDecoded() { + if (!generator.toDecodedMap) return null; + return clean(generator.toDecodedMap()); + } + + function getEncoded() { + return clean(generator.toJSON()); + } + + function destroy() { + // @jridgewell/source-map's SourceMapConsumer does not need to be + // manually freed. + if (orig_map && orig_map.destroy) orig_map.destroy(); + } + + return { + add, + getDecoded, + getEncoded, + destroy, + }; +} + +var domprops = [ + "$&", + "$'", + "$*", + "$+", + "$1", + "$2", + "$3", + "$4", + "$5", + "$6", + "$7", + "$8", + "$9", + "$_", + "$`", + "$input", + "-moz-animation", + "-moz-animation-delay", + "-moz-animation-direction", + "-moz-animation-duration", + "-moz-animation-fill-mode", + "-moz-animation-iteration-count", + "-moz-animation-name", + "-moz-animation-play-state", + "-moz-animation-timing-function", + "-moz-appearance", + "-moz-backface-visibility", + "-moz-border-end", + "-moz-border-end-color", + "-moz-border-end-style", + "-moz-border-end-width", + "-moz-border-image", + "-moz-border-start", + "-moz-border-start-color", + "-moz-border-start-style", + "-moz-border-start-width", + "-moz-box-align", + "-moz-box-direction", + "-moz-box-flex", + "-moz-box-ordinal-group", + "-moz-box-orient", + "-moz-box-pack", + "-moz-box-sizing", + "-moz-float-edge", + "-moz-font-feature-settings", + "-moz-font-language-override", + "-moz-force-broken-image-icon", + "-moz-hyphens", + "-moz-image-region", + "-moz-margin-end", + "-moz-margin-start", + "-moz-orient", + "-moz-osx-font-smoothing", + "-moz-outline-radius", + "-moz-outline-radius-bottomleft", + "-moz-outline-radius-bottomright", + "-moz-outline-radius-topleft", + "-moz-outline-radius-topright", + "-moz-padding-end", + "-moz-padding-start", + "-moz-perspective", + "-moz-perspective-origin", + "-moz-tab-size", + "-moz-text-size-adjust", + "-moz-transform", + "-moz-transform-origin", + "-moz-transform-style", + "-moz-transition", + "-moz-transition-delay", + "-moz-transition-duration", + "-moz-transition-property", + "-moz-transition-timing-function", + "-moz-user-focus", + "-moz-user-input", + "-moz-user-modify", + "-moz-user-select", + "-moz-window-dragging", + "-webkit-align-content", + "-webkit-align-items", + "-webkit-align-self", + "-webkit-animation", + "-webkit-animation-delay", + "-webkit-animation-direction", + "-webkit-animation-duration", + "-webkit-animation-fill-mode", + "-webkit-animation-iteration-count", + "-webkit-animation-name", + "-webkit-animation-play-state", + "-webkit-animation-timing-function", + "-webkit-appearance", + "-webkit-backface-visibility", + "-webkit-background-clip", + "-webkit-background-origin", + "-webkit-background-size", + "-webkit-border-bottom-left-radius", + "-webkit-border-bottom-right-radius", + "-webkit-border-image", + "-webkit-border-radius", + "-webkit-border-top-left-radius", + "-webkit-border-top-right-radius", + "-webkit-box-align", + "-webkit-box-direction", + "-webkit-box-flex", + "-webkit-box-ordinal-group", + "-webkit-box-orient", + "-webkit-box-pack", + "-webkit-box-shadow", + "-webkit-box-sizing", + "-webkit-clip-path", + "-webkit-filter", + "-webkit-flex", + "-webkit-flex-basis", + "-webkit-flex-direction", + "-webkit-flex-flow", + "-webkit-flex-grow", + "-webkit-flex-shrink", + "-webkit-flex-wrap", + "-webkit-justify-content", + "-webkit-line-clamp", + "-webkit-mask", + "-webkit-mask-clip", + "-webkit-mask-composite", + "-webkit-mask-image", + "-webkit-mask-origin", + "-webkit-mask-position", + "-webkit-mask-position-x", + "-webkit-mask-position-y", + "-webkit-mask-repeat", + "-webkit-mask-size", + "-webkit-order", + "-webkit-perspective", + "-webkit-perspective-origin", + "-webkit-text-fill-color", + "-webkit-text-security", + "-webkit-text-size-adjust", + "-webkit-text-stroke", + "-webkit-text-stroke-color", + "-webkit-text-stroke-width", + "-webkit-transform", + "-webkit-transform-origin", + "-webkit-transform-style", + "-webkit-transition", + "-webkit-transition-delay", + "-webkit-transition-duration", + "-webkit-transition-property", + "-webkit-transition-timing-function", + "-webkit-user-select", + "0", + "1", + "10", + "11", + "12", + "13", + "14", + "15", + "16", + "17", + "18", + "19", + "2", + "20", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "@@iterator", + "ABORT_ERR", + "ACTIVE", + "ACTIVE_ATTRIBUTES", + "ACTIVE_TEXTURE", + "ACTIVE_UNIFORMS", + "ACTIVE_UNIFORM_BLOCKS", + "ADDITION", + "ALIASED_LINE_WIDTH_RANGE", + "ALIASED_POINT_SIZE_RANGE", + "ALL", + "ALLOW_KEYBOARD_INPUT", + "ALLPASS", + "ALPHA", + "ALPHA_BITS", + "ALREADY_SIGNALED", + "ALT_MASK", + "ALWAYS", + "ANY_SAMPLES_PASSED", + "ANY_SAMPLES_PASSED_CONSERVATIVE", + "ANY_TYPE", + "ANY_UNORDERED_NODE_TYPE", + "ARRAY_BUFFER", + "ARRAY_BUFFER_BINDING", + "ATTACHED_SHADERS", + "ATTRIBUTE_NODE", + "AT_TARGET", + "AbortController", + "AbortSignal", + "AbsoluteOrientationSensor", + "AbstractRange", + "Accelerometer", + "AddSearchProvider", + "AggregateError", + "AnalyserNode", + "Animation", + "AnimationEffect", + "AnimationEvent", + "AnimationPlaybackEvent", + "AnimationTimeline", + "AnonXMLHttpRequest", + "Any", + "ApplicationCache", + "ApplicationCacheErrorEvent", + "Array", + "ArrayBuffer", + "ArrayType", + "Atomics", + "Attr", + "Audio", + "AudioBuffer", + "AudioBufferSourceNode", + "AudioContext", + "AudioData", + "AudioDecoder", + "AudioDestinationNode", + "AudioEncoder", + "AudioListener", + "AudioNode", + "AudioParam", + "AudioParamMap", + "AudioProcessingEvent", + "AudioScheduledSourceNode", + "AudioSinkInfo", + "AudioStreamTrack", + "AudioWorklet", + "AudioWorkletNode", + "AuthenticatorAssertionResponse", + "AuthenticatorAttestationResponse", + "AuthenticatorResponse", + "AutocompleteErrorEvent", + "BACK", + "BAD_BOUNDARYPOINTS_ERR", + "BAD_REQUEST", + "BANDPASS", + "BLEND", + "BLEND_COLOR", + "BLEND_DST_ALPHA", + "BLEND_DST_RGB", + "BLEND_EQUATION", + "BLEND_EQUATION_ALPHA", + "BLEND_EQUATION_RGB", + "BLEND_SRC_ALPHA", + "BLEND_SRC_RGB", + "BLUE", + "BLUE_BITS", + "BLUR", + "BOOL", + "BOOLEAN_TYPE", + "BOOL_VEC2", + "BOOL_VEC3", + "BOOL_VEC4", + "BOTH", + "BROWSER_DEFAULT_WEBGL", + "BUBBLING_PHASE", + "BUFFER_SIZE", + "BUFFER_USAGE", + "BYTE", + "BYTES_PER_ELEMENT", + "BackgroundFetchManager", + "BackgroundFetchRecord", + "BackgroundFetchRegistration", + "BarProp", + "BarcodeDetector", + "BaseAudioContext", + "BaseHref", + "BatteryManager", + "BeforeInstallPromptEvent", + "BeforeLoadEvent", + "BeforeUnloadEvent", + "BigInt", + "BigInt64Array", + "BigUint64Array", + "BiquadFilterNode", + "Blob", + "BlobEvent", + "Bluetooth", + "BluetoothCharacteristicProperties", + "BluetoothDevice", + "BluetoothRemoteGATTCharacteristic", + "BluetoothRemoteGATTDescriptor", + "BluetoothRemoteGATTServer", + "BluetoothRemoteGATTService", + "BluetoothUUID", + "Boolean", + "BroadcastChannel", + "BrowserCaptureMediaStreamTrack", + "ByteLengthQueuingStrategy", + "CAPTURING_PHASE", + "CCW", + "CDATASection", + "CDATA_SECTION_NODE", + "CHANGE", + "CHARSET_RULE", + "CHECKING", + "CLAMP_TO_EDGE", + "CLICK", + "CLOSED", + "CLOSING", + "COLOR", + "COLOR_ATTACHMENT0", + "COLOR_ATTACHMENT1", + "COLOR_ATTACHMENT10", + "COLOR_ATTACHMENT11", + "COLOR_ATTACHMENT12", + "COLOR_ATTACHMENT13", + "COLOR_ATTACHMENT14", + "COLOR_ATTACHMENT15", + "COLOR_ATTACHMENT2", + "COLOR_ATTACHMENT3", + "COLOR_ATTACHMENT4", + "COLOR_ATTACHMENT5", + "COLOR_ATTACHMENT6", + "COLOR_ATTACHMENT7", + "COLOR_ATTACHMENT8", + "COLOR_ATTACHMENT9", + "COLOR_BUFFER_BIT", + "COLOR_CLEAR_VALUE", + "COLOR_WRITEMASK", + "COMMENT_NODE", + "COMPARE_REF_TO_TEXTURE", + "COMPILE_STATUS", + "COMPLETION_STATUS_KHR", + "COMPRESSED_RGBA_S3TC_DXT1_EXT", + "COMPRESSED_RGBA_S3TC_DXT3_EXT", + "COMPRESSED_RGBA_S3TC_DXT5_EXT", + "COMPRESSED_RGB_S3TC_DXT1_EXT", + "COMPRESSED_TEXTURE_FORMATS", + "COMPUTE", + "CONDITION_SATISFIED", + "CONFIGURATION_UNSUPPORTED", + "CONNECTING", + "CONSTANT_ALPHA", + "CONSTANT_COLOR", + "CONSTRAINT_ERR", + "CONTEXT_LOST_WEBGL", + "CONTROL_MASK", + "COPY_DST", + "COPY_READ_BUFFER", + "COPY_READ_BUFFER_BINDING", + "COPY_SRC", + "COPY_WRITE_BUFFER", + "COPY_WRITE_BUFFER_BINDING", + "COUNTER_STYLE_RULE", + "CSS", + "CSS2Properties", + "CSSAnimation", + "CSSCharsetRule", + "CSSConditionRule", + "CSSContainerRule", + "CSSCounterStyleRule", + "CSSFontFaceRule", + "CSSFontFeatureValuesRule", + "CSSFontPaletteValuesRule", + "CSSGroupingRule", + "CSSImageValue", + "CSSImportRule", + "CSSKeyframeRule", + "CSSKeyframesRule", + "CSSKeywordValue", + "CSSLayerBlockRule", + "CSSLayerStatementRule", + "CSSMathClamp", + "CSSMathInvert", + "CSSMathMax", + "CSSMathMin", + "CSSMathNegate", + "CSSMathProduct", + "CSSMathSum", + "CSSMathValue", + "CSSMatrixComponent", + "CSSMediaRule", + "CSSMozDocumentRule", + "CSSNameSpaceRule", + "CSSNamespaceRule", + "CSSNumericArray", + "CSSNumericValue", + "CSSPageRule", + "CSSPerspective", + "CSSPositionValue", + "CSSPrimitiveValue", + "CSSPropertyRule", + "CSSRotate", + "CSSRule", + "CSSRuleList", + "CSSScale", + "CSSScopeRule", + "CSSSkew", + "CSSSkewX", + "CSSSkewY", + "CSSStartingStyleRule", + "CSSStyleDeclaration", + "CSSStyleRule", + "CSSStyleSheet", + "CSSStyleValue", + "CSSSupportsRule", + "CSSTransformComponent", + "CSSTransformValue", + "CSSTransition", + "CSSTranslate", + "CSSUnitValue", + "CSSUnknownRule", + "CSSUnparsedValue", + "CSSValue", + "CSSValueList", + "CSSVariableReferenceValue", + "CSSVariablesDeclaration", + "CSSVariablesRule", + "CSSViewportRule", + "CSS_ATTR", + "CSS_CM", + "CSS_COUNTER", + "CSS_CUSTOM", + "CSS_DEG", + "CSS_DIMENSION", + "CSS_EMS", + "CSS_EXS", + "CSS_FILTER_BLUR", + "CSS_FILTER_BRIGHTNESS", + "CSS_FILTER_CONTRAST", + "CSS_FILTER_CUSTOM", + "CSS_FILTER_DROP_SHADOW", + "CSS_FILTER_GRAYSCALE", + "CSS_FILTER_HUE_ROTATE", + "CSS_FILTER_INVERT", + "CSS_FILTER_OPACITY", + "CSS_FILTER_REFERENCE", + "CSS_FILTER_SATURATE", + "CSS_FILTER_SEPIA", + "CSS_GRAD", + "CSS_HZ", + "CSS_IDENT", + "CSS_IN", + "CSS_INHERIT", + "CSS_KHZ", + "CSS_MATRIX", + "CSS_MATRIX3D", + "CSS_MM", + "CSS_MS", + "CSS_NUMBER", + "CSS_PC", + "CSS_PERCENTAGE", + "CSS_PERSPECTIVE", + "CSS_PRIMITIVE_VALUE", + "CSS_PT", + "CSS_PX", + "CSS_RAD", + "CSS_RECT", + "CSS_RGBCOLOR", + "CSS_ROTATE", + "CSS_ROTATE3D", + "CSS_ROTATEX", + "CSS_ROTATEY", + "CSS_ROTATEZ", + "CSS_S", + "CSS_SCALE", + "CSS_SCALE3D", + "CSS_SCALEX", + "CSS_SCALEY", + "CSS_SCALEZ", + "CSS_SKEW", + "CSS_SKEWX", + "CSS_SKEWY", + "CSS_STRING", + "CSS_TRANSLATE", + "CSS_TRANSLATE3D", + "CSS_TRANSLATEX", + "CSS_TRANSLATEY", + "CSS_TRANSLATEZ", + "CSS_UNKNOWN", + "CSS_URI", + "CSS_VALUE_LIST", + "CSS_VH", + "CSS_VMAX", + "CSS_VMIN", + "CSS_VW", + "CULL_FACE", + "CULL_FACE_MODE", + "CURRENT_PROGRAM", + "CURRENT_QUERY", + "CURRENT_VERTEX_ATTRIB", + "CUSTOM", + "CW", + "Cache", + "CacheStorage", + "CanvasCaptureMediaStream", + "CanvasCaptureMediaStreamTrack", + "CanvasGradient", + "CanvasPattern", + "CanvasRenderingContext2D", + "CaptureController", + "CaretPosition", + "ChannelMergerNode", + "ChannelSplitterNode", + "CharacterBoundsUpdateEvent", + "CharacterData", + "ClientRect", + "ClientRectList", + "Clipboard", + "ClipboardEvent", + "ClipboardItem", + "CloseEvent", + "Collator", + "CommandEvent", + "Comment", + "CompileError", + "CompositionEvent", + "CompressionStream", + "Console", + "ConstantSourceNode", + "ContentVisibilityAutoStateChangeEvent", + "Controllers", + "ConvolverNode", + "CookieChangeEvent", + "CookieStore", + "CookieStoreManager", + "CountQueuingStrategy", + "Counter", + "Credential", + "CredentialsContainer", + "CropTarget", + "Crypto", + "CryptoKey", + "CustomElementRegistry", + "CustomEvent", + "CustomStateSet", + "DATABASE_ERR", + "DATA_CLONE_ERR", + "DATA_ERR", + "DBLCLICK", + "DECR", + "DECR_WRAP", + "DELETE_STATUS", + "DEPTH", + "DEPTH24_STENCIL8", + "DEPTH32F_STENCIL8", + "DEPTH_ATTACHMENT", + "DEPTH_BITS", + "DEPTH_BUFFER_BIT", + "DEPTH_CLEAR_VALUE", + "DEPTH_COMPONENT", + "DEPTH_COMPONENT16", + "DEPTH_COMPONENT24", + "DEPTH_COMPONENT32F", + "DEPTH_FUNC", + "DEPTH_RANGE", + "DEPTH_STENCIL", + "DEPTH_STENCIL_ATTACHMENT", + "DEPTH_TEST", + "DEPTH_WRITEMASK", + "DEVICE_INELIGIBLE", + "DIRECTION_DOWN", + "DIRECTION_LEFT", + "DIRECTION_RIGHT", + "DIRECTION_UP", + "DISABLED", + "DISPATCH_REQUEST_ERR", + "DITHER", + "DOCUMENT_FRAGMENT_NODE", + "DOCUMENT_NODE", + "DOCUMENT_POSITION_CONTAINED_BY", + "DOCUMENT_POSITION_CONTAINS", + "DOCUMENT_POSITION_DISCONNECTED", + "DOCUMENT_POSITION_FOLLOWING", + "DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC", + "DOCUMENT_POSITION_PRECEDING", + "DOCUMENT_TYPE_NODE", + "DOMCursor", + "DOMError", + "DOMException", + "DOMImplementation", + "DOMImplementationLS", + "DOMMatrix", + "DOMMatrixReadOnly", + "DOMParser", + "DOMPoint", + "DOMPointReadOnly", + "DOMQuad", + "DOMRect", + "DOMRectList", + "DOMRectReadOnly", + "DOMRequest", + "DOMSTRING_SIZE_ERR", + "DOMSettableTokenList", + "DOMStringList", + "DOMStringMap", + "DOMTokenList", + "DOMTransactionEvent", + "DOM_DELTA_LINE", + "DOM_DELTA_PAGE", + "DOM_DELTA_PIXEL", + "DOM_INPUT_METHOD_DROP", + "DOM_INPUT_METHOD_HANDWRITING", + "DOM_INPUT_METHOD_IME", + "DOM_INPUT_METHOD_KEYBOARD", + "DOM_INPUT_METHOD_MULTIMODAL", + "DOM_INPUT_METHOD_OPTION", + "DOM_INPUT_METHOD_PASTE", + "DOM_INPUT_METHOD_SCRIPT", + "DOM_INPUT_METHOD_UNKNOWN", + "DOM_INPUT_METHOD_VOICE", + "DOM_KEY_LOCATION_JOYSTICK", + "DOM_KEY_LOCATION_LEFT", + "DOM_KEY_LOCATION_MOBILE", + "DOM_KEY_LOCATION_NUMPAD", + "DOM_KEY_LOCATION_RIGHT", + "DOM_KEY_LOCATION_STANDARD", + "DOM_VK_0", + "DOM_VK_1", + "DOM_VK_2", + "DOM_VK_3", + "DOM_VK_4", + "DOM_VK_5", + "DOM_VK_6", + "DOM_VK_7", + "DOM_VK_8", + "DOM_VK_9", + "DOM_VK_A", + "DOM_VK_ACCEPT", + "DOM_VK_ADD", + "DOM_VK_ALT", + "DOM_VK_ALTGR", + "DOM_VK_AMPERSAND", + "DOM_VK_ASTERISK", + "DOM_VK_AT", + "DOM_VK_ATTN", + "DOM_VK_B", + "DOM_VK_BACKSPACE", + "DOM_VK_BACK_QUOTE", + "DOM_VK_BACK_SLASH", + "DOM_VK_BACK_SPACE", + "DOM_VK_C", + "DOM_VK_CANCEL", + "DOM_VK_CAPS_LOCK", + "DOM_VK_CIRCUMFLEX", + "DOM_VK_CLEAR", + "DOM_VK_CLOSE_BRACKET", + "DOM_VK_CLOSE_CURLY_BRACKET", + "DOM_VK_CLOSE_PAREN", + "DOM_VK_COLON", + "DOM_VK_COMMA", + "DOM_VK_CONTEXT_MENU", + "DOM_VK_CONTROL", + "DOM_VK_CONVERT", + "DOM_VK_CRSEL", + "DOM_VK_CTRL", + "DOM_VK_D", + "DOM_VK_DECIMAL", + "DOM_VK_DELETE", + "DOM_VK_DIVIDE", + "DOM_VK_DOLLAR", + "DOM_VK_DOUBLE_QUOTE", + "DOM_VK_DOWN", + "DOM_VK_E", + "DOM_VK_EISU", + "DOM_VK_END", + "DOM_VK_ENTER", + "DOM_VK_EQUALS", + "DOM_VK_EREOF", + "DOM_VK_ESCAPE", + "DOM_VK_EXCLAMATION", + "DOM_VK_EXECUTE", + "DOM_VK_EXSEL", + "DOM_VK_F", + "DOM_VK_F1", + "DOM_VK_F10", + "DOM_VK_F11", + "DOM_VK_F12", + "DOM_VK_F13", + "DOM_VK_F14", + "DOM_VK_F15", + "DOM_VK_F16", + "DOM_VK_F17", + "DOM_VK_F18", + "DOM_VK_F19", + "DOM_VK_F2", + "DOM_VK_F20", + "DOM_VK_F21", + "DOM_VK_F22", + "DOM_VK_F23", + "DOM_VK_F24", + "DOM_VK_F25", + "DOM_VK_F26", + "DOM_VK_F27", + "DOM_VK_F28", + "DOM_VK_F29", + "DOM_VK_F3", + "DOM_VK_F30", + "DOM_VK_F31", + "DOM_VK_F32", + "DOM_VK_F33", + "DOM_VK_F34", + "DOM_VK_F35", + "DOM_VK_F36", + "DOM_VK_F4", + "DOM_VK_F5", + "DOM_VK_F6", + "DOM_VK_F7", + "DOM_VK_F8", + "DOM_VK_F9", + "DOM_VK_FINAL", + "DOM_VK_FRONT", + "DOM_VK_G", + "DOM_VK_GREATER_THAN", + "DOM_VK_H", + "DOM_VK_HANGUL", + "DOM_VK_HANJA", + "DOM_VK_HASH", + "DOM_VK_HELP", + "DOM_VK_HK_TOGGLE", + "DOM_VK_HOME", + "DOM_VK_HYPHEN_MINUS", + "DOM_VK_I", + "DOM_VK_INSERT", + "DOM_VK_J", + "DOM_VK_JUNJA", + "DOM_VK_K", + "DOM_VK_KANA", + "DOM_VK_KANJI", + "DOM_VK_L", + "DOM_VK_LEFT", + "DOM_VK_LEFT_TAB", + "DOM_VK_LESS_THAN", + "DOM_VK_M", + "DOM_VK_META", + "DOM_VK_MODECHANGE", + "DOM_VK_MULTIPLY", + "DOM_VK_N", + "DOM_VK_NONCONVERT", + "DOM_VK_NUMPAD0", + "DOM_VK_NUMPAD1", + "DOM_VK_NUMPAD2", + "DOM_VK_NUMPAD3", + "DOM_VK_NUMPAD4", + "DOM_VK_NUMPAD5", + "DOM_VK_NUMPAD6", + "DOM_VK_NUMPAD7", + "DOM_VK_NUMPAD8", + "DOM_VK_NUMPAD9", + "DOM_VK_NUM_LOCK", + "DOM_VK_O", + "DOM_VK_OEM_1", + "DOM_VK_OEM_102", + "DOM_VK_OEM_2", + "DOM_VK_OEM_3", + "DOM_VK_OEM_4", + "DOM_VK_OEM_5", + "DOM_VK_OEM_6", + "DOM_VK_OEM_7", + "DOM_VK_OEM_8", + "DOM_VK_OEM_COMMA", + "DOM_VK_OEM_MINUS", + "DOM_VK_OEM_PERIOD", + "DOM_VK_OEM_PLUS", + "DOM_VK_OPEN_BRACKET", + "DOM_VK_OPEN_CURLY_BRACKET", + "DOM_VK_OPEN_PAREN", + "DOM_VK_P", + "DOM_VK_PA1", + "DOM_VK_PAGEDOWN", + "DOM_VK_PAGEUP", + "DOM_VK_PAGE_DOWN", + "DOM_VK_PAGE_UP", + "DOM_VK_PAUSE", + "DOM_VK_PERCENT", + "DOM_VK_PERIOD", + "DOM_VK_PIPE", + "DOM_VK_PLAY", + "DOM_VK_PLUS", + "DOM_VK_PRINT", + "DOM_VK_PRINTSCREEN", + "DOM_VK_PROCESSKEY", + "DOM_VK_PROPERITES", + "DOM_VK_Q", + "DOM_VK_QUESTION_MARK", + "DOM_VK_QUOTE", + "DOM_VK_R", + "DOM_VK_REDO", + "DOM_VK_RETURN", + "DOM_VK_RIGHT", + "DOM_VK_S", + "DOM_VK_SCROLL_LOCK", + "DOM_VK_SELECT", + "DOM_VK_SEMICOLON", + "DOM_VK_SEPARATOR", + "DOM_VK_SHIFT", + "DOM_VK_SLASH", + "DOM_VK_SLEEP", + "DOM_VK_SPACE", + "DOM_VK_SUBTRACT", + "DOM_VK_T", + "DOM_VK_TAB", + "DOM_VK_TILDE", + "DOM_VK_U", + "DOM_VK_UNDERSCORE", + "DOM_VK_UNDO", + "DOM_VK_UNICODE", + "DOM_VK_UP", + "DOM_VK_V", + "DOM_VK_VOLUME_DOWN", + "DOM_VK_VOLUME_MUTE", + "DOM_VK_VOLUME_UP", + "DOM_VK_W", + "DOM_VK_WIN", + "DOM_VK_WINDOW", + "DOM_VK_WIN_ICO_00", + "DOM_VK_WIN_ICO_CLEAR", + "DOM_VK_WIN_ICO_HELP", + "DOM_VK_WIN_OEM_ATTN", + "DOM_VK_WIN_OEM_AUTO", + "DOM_VK_WIN_OEM_BACKTAB", + "DOM_VK_WIN_OEM_CLEAR", + "DOM_VK_WIN_OEM_COPY", + "DOM_VK_WIN_OEM_CUSEL", + "DOM_VK_WIN_OEM_ENLW", + "DOM_VK_WIN_OEM_FINISH", + "DOM_VK_WIN_OEM_FJ_JISHO", + "DOM_VK_WIN_OEM_FJ_LOYA", + "DOM_VK_WIN_OEM_FJ_MASSHOU", + "DOM_VK_WIN_OEM_FJ_ROYA", + "DOM_VK_WIN_OEM_FJ_TOUROKU", + "DOM_VK_WIN_OEM_JUMP", + "DOM_VK_WIN_OEM_PA1", + "DOM_VK_WIN_OEM_PA2", + "DOM_VK_WIN_OEM_PA3", + "DOM_VK_WIN_OEM_RESET", + "DOM_VK_WIN_OEM_WSCTRL", + "DOM_VK_X", + "DOM_VK_XF86XK_ADD_FAVORITE", + "DOM_VK_XF86XK_APPLICATION_LEFT", + "DOM_VK_XF86XK_APPLICATION_RIGHT", + "DOM_VK_XF86XK_AUDIO_CYCLE_TRACK", + "DOM_VK_XF86XK_AUDIO_FORWARD", + "DOM_VK_XF86XK_AUDIO_LOWER_VOLUME", + "DOM_VK_XF86XK_AUDIO_MEDIA", + "DOM_VK_XF86XK_AUDIO_MUTE", + "DOM_VK_XF86XK_AUDIO_NEXT", + "DOM_VK_XF86XK_AUDIO_PAUSE", + "DOM_VK_XF86XK_AUDIO_PLAY", + "DOM_VK_XF86XK_AUDIO_PREV", + "DOM_VK_XF86XK_AUDIO_RAISE_VOLUME", + "DOM_VK_XF86XK_AUDIO_RANDOM_PLAY", + "DOM_VK_XF86XK_AUDIO_RECORD", + "DOM_VK_XF86XK_AUDIO_REPEAT", + "DOM_VK_XF86XK_AUDIO_REWIND", + "DOM_VK_XF86XK_AUDIO_STOP", + "DOM_VK_XF86XK_AWAY", + "DOM_VK_XF86XK_BACK", + "DOM_VK_XF86XK_BACK_FORWARD", + "DOM_VK_XF86XK_BATTERY", + "DOM_VK_XF86XK_BLUE", + "DOM_VK_XF86XK_BLUETOOTH", + "DOM_VK_XF86XK_BOOK", + "DOM_VK_XF86XK_BRIGHTNESS_ADJUST", + "DOM_VK_XF86XK_CALCULATOR", + "DOM_VK_XF86XK_CALENDAR", + "DOM_VK_XF86XK_CD", + "DOM_VK_XF86XK_CLOSE", + "DOM_VK_XF86XK_COMMUNITY", + "DOM_VK_XF86XK_CONTRAST_ADJUST", + "DOM_VK_XF86XK_COPY", + "DOM_VK_XF86XK_CUT", + "DOM_VK_XF86XK_CYCLE_ANGLE", + "DOM_VK_XF86XK_DISPLAY", + "DOM_VK_XF86XK_DOCUMENTS", + "DOM_VK_XF86XK_DOS", + "DOM_VK_XF86XK_EJECT", + "DOM_VK_XF86XK_EXCEL", + "DOM_VK_XF86XK_EXPLORER", + "DOM_VK_XF86XK_FAVORITES", + "DOM_VK_XF86XK_FINANCE", + "DOM_VK_XF86XK_FORWARD", + "DOM_VK_XF86XK_FRAME_BACK", + "DOM_VK_XF86XK_FRAME_FORWARD", + "DOM_VK_XF86XK_GAME", + "DOM_VK_XF86XK_GO", + "DOM_VK_XF86XK_GREEN", + "DOM_VK_XF86XK_HIBERNATE", + "DOM_VK_XF86XK_HISTORY", + "DOM_VK_XF86XK_HOME_PAGE", + "DOM_VK_XF86XK_HOT_LINKS", + "DOM_VK_XF86XK_I_TOUCH", + "DOM_VK_XF86XK_KBD_BRIGHTNESS_DOWN", + "DOM_VK_XF86XK_KBD_BRIGHTNESS_UP", + "DOM_VK_XF86XK_KBD_LIGHT_ON_OFF", + "DOM_VK_XF86XK_LAUNCH0", + "DOM_VK_XF86XK_LAUNCH1", + "DOM_VK_XF86XK_LAUNCH2", + "DOM_VK_XF86XK_LAUNCH3", + "DOM_VK_XF86XK_LAUNCH4", + "DOM_VK_XF86XK_LAUNCH5", + "DOM_VK_XF86XK_LAUNCH6", + "DOM_VK_XF86XK_LAUNCH7", + "DOM_VK_XF86XK_LAUNCH8", + "DOM_VK_XF86XK_LAUNCH9", + "DOM_VK_XF86XK_LAUNCH_A", + "DOM_VK_XF86XK_LAUNCH_B", + "DOM_VK_XF86XK_LAUNCH_C", + "DOM_VK_XF86XK_LAUNCH_D", + "DOM_VK_XF86XK_LAUNCH_E", + "DOM_VK_XF86XK_LAUNCH_F", + "DOM_VK_XF86XK_LIGHT_BULB", + "DOM_VK_XF86XK_LOG_OFF", + "DOM_VK_XF86XK_MAIL", + "DOM_VK_XF86XK_MAIL_FORWARD", + "DOM_VK_XF86XK_MARKET", + "DOM_VK_XF86XK_MEETING", + "DOM_VK_XF86XK_MEMO", + "DOM_VK_XF86XK_MENU_KB", + "DOM_VK_XF86XK_MENU_PB", + "DOM_VK_XF86XK_MESSENGER", + "DOM_VK_XF86XK_MON_BRIGHTNESS_DOWN", + "DOM_VK_XF86XK_MON_BRIGHTNESS_UP", + "DOM_VK_XF86XK_MUSIC", + "DOM_VK_XF86XK_MY_COMPUTER", + "DOM_VK_XF86XK_MY_SITES", + "DOM_VK_XF86XK_NEW", + "DOM_VK_XF86XK_NEWS", + "DOM_VK_XF86XK_OFFICE_HOME", + "DOM_VK_XF86XK_OPEN", + "DOM_VK_XF86XK_OPEN_URL", + "DOM_VK_XF86XK_OPTION", + "DOM_VK_XF86XK_PASTE", + "DOM_VK_XF86XK_PHONE", + "DOM_VK_XF86XK_PICTURES", + "DOM_VK_XF86XK_POWER_DOWN", + "DOM_VK_XF86XK_POWER_OFF", + "DOM_VK_XF86XK_RED", + "DOM_VK_XF86XK_REFRESH", + "DOM_VK_XF86XK_RELOAD", + "DOM_VK_XF86XK_REPLY", + "DOM_VK_XF86XK_ROCKER_DOWN", + "DOM_VK_XF86XK_ROCKER_ENTER", + "DOM_VK_XF86XK_ROCKER_UP", + "DOM_VK_XF86XK_ROTATE_WINDOWS", + "DOM_VK_XF86XK_ROTATION_KB", + "DOM_VK_XF86XK_ROTATION_PB", + "DOM_VK_XF86XK_SAVE", + "DOM_VK_XF86XK_SCREEN_SAVER", + "DOM_VK_XF86XK_SCROLL_CLICK", + "DOM_VK_XF86XK_SCROLL_DOWN", + "DOM_VK_XF86XK_SCROLL_UP", + "DOM_VK_XF86XK_SEARCH", + "DOM_VK_XF86XK_SEND", + "DOM_VK_XF86XK_SHOP", + "DOM_VK_XF86XK_SPELL", + "DOM_VK_XF86XK_SPLIT_SCREEN", + "DOM_VK_XF86XK_STANDBY", + "DOM_VK_XF86XK_START", + "DOM_VK_XF86XK_STOP", + "DOM_VK_XF86XK_SUBTITLE", + "DOM_VK_XF86XK_SUPPORT", + "DOM_VK_XF86XK_SUSPEND", + "DOM_VK_XF86XK_TASK_PANE", + "DOM_VK_XF86XK_TERMINAL", + "DOM_VK_XF86XK_TIME", + "DOM_VK_XF86XK_TOOLS", + "DOM_VK_XF86XK_TOP_MENU", + "DOM_VK_XF86XK_TO_DO_LIST", + "DOM_VK_XF86XK_TRAVEL", + "DOM_VK_XF86XK_USER1KB", + "DOM_VK_XF86XK_USER2KB", + "DOM_VK_XF86XK_USER_PB", + "DOM_VK_XF86XK_UWB", + "DOM_VK_XF86XK_VENDOR_HOME", + "DOM_VK_XF86XK_VIDEO", + "DOM_VK_XF86XK_VIEW", + "DOM_VK_XF86XK_WAKE_UP", + "DOM_VK_XF86XK_WEB_CAM", + "DOM_VK_XF86XK_WHEEL_BUTTON", + "DOM_VK_XF86XK_WLAN", + "DOM_VK_XF86XK_WORD", + "DOM_VK_XF86XK_WWW", + "DOM_VK_XF86XK_XFER", + "DOM_VK_XF86XK_YELLOW", + "DOM_VK_XF86XK_ZOOM_IN", + "DOM_VK_XF86XK_ZOOM_OUT", + "DOM_VK_Y", + "DOM_VK_Z", + "DOM_VK_ZOOM", + "DONE", + "DONT_CARE", + "DOWNLOADING", + "DRAGDROP", + "DRAW_BUFFER0", + "DRAW_BUFFER1", + "DRAW_BUFFER10", + "DRAW_BUFFER11", + "DRAW_BUFFER12", + "DRAW_BUFFER13", + "DRAW_BUFFER14", + "DRAW_BUFFER15", + "DRAW_BUFFER2", + "DRAW_BUFFER3", + "DRAW_BUFFER4", + "DRAW_BUFFER5", + "DRAW_BUFFER6", + "DRAW_BUFFER7", + "DRAW_BUFFER8", + "DRAW_BUFFER9", + "DRAW_FRAMEBUFFER", + "DRAW_FRAMEBUFFER_BINDING", + "DST_ALPHA", + "DST_COLOR", + "DYNAMIC_COPY", + "DYNAMIC_DRAW", + "DYNAMIC_READ", + "DataChannel", + "DataTransfer", + "DataTransferItem", + "DataTransferItemList", + "DataView", + "Date", + "DateTimeFormat", + "DecompressionStream", + "DelayNode", + "DelegatedInkTrailPresenter", + "DeprecationReportBody", + "DesktopNotification", + "DesktopNotificationCenter", + "DeviceLightEvent", + "DeviceMotionEvent", + "DeviceMotionEventAcceleration", + "DeviceMotionEventRotationRate", + "DeviceOrientationEvent", + "DeviceProximityEvent", + "DeviceStorage", + "DeviceStorageChangeEvent", + "Directory", + "DisplayNames", + "Document", + "DocumentFragment", + "DocumentPictureInPicture", + "DocumentPictureInPictureEvent", + "DocumentTimeline", + "DocumentType", + "DragEvent", + "DynamicsCompressorNode", + "E", + "ELEMENT_ARRAY_BUFFER", + "ELEMENT_ARRAY_BUFFER_BINDING", + "ELEMENT_NODE", + "EMPTY", + "ENCODING_ERR", + "ENDED", + "END_TO_END", + "END_TO_START", + "ENTITY_NODE", + "ENTITY_REFERENCE_NODE", + "EPSILON", + "EQUAL", + "EQUALPOWER", + "ERROR", + "EXPONENTIAL_DISTANCE", + "EditContext", + "Element", + "ElementInternals", + "ElementQuery", + "EncodedAudioChunk", + "EncodedVideoChunk", + "EnterPictureInPictureEvent", + "Entity", + "EntityReference", + "Error", + "ErrorEvent", + "EvalError", + "Event", + "EventCounts", + "EventException", + "EventSource", + "EventTarget", + "Exception", + "External", + "EyeDropper", + "FASTEST", + "FIDOSDK", + "FILTER_ACCEPT", + "FILTER_INTERRUPT", + "FILTER_REJECT", + "FILTER_SKIP", + "FINISHED_STATE", + "FIRST_ORDERED_NODE_TYPE", + "FLOAT", + "FLOAT_32_UNSIGNED_INT_24_8_REV", + "FLOAT_MAT2", + "FLOAT_MAT2x3", + "FLOAT_MAT2x4", + "FLOAT_MAT3", + "FLOAT_MAT3x2", + "FLOAT_MAT3x4", + "FLOAT_MAT4", + "FLOAT_MAT4x2", + "FLOAT_MAT4x3", + "FLOAT_VEC2", + "FLOAT_VEC3", + "FLOAT_VEC4", + "FOCUS", + "FONT_FACE_RULE", + "FONT_FEATURE_VALUES_RULE", + "FRAGMENT", + "FRAGMENT_SHADER", + "FRAGMENT_SHADER_DERIVATIVE_HINT", + "FRAGMENT_SHADER_DERIVATIVE_HINT_OES", + "FRAMEBUFFER", + "FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE", + "FRAMEBUFFER_ATTACHMENT_BLUE_SIZE", + "FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING", + "FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE", + "FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE", + "FRAMEBUFFER_ATTACHMENT_GREEN_SIZE", + "FRAMEBUFFER_ATTACHMENT_OBJECT_NAME", + "FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE", + "FRAMEBUFFER_ATTACHMENT_RED_SIZE", + "FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE", + "FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE", + "FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER", + "FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL", + "FRAMEBUFFER_BINDING", + "FRAMEBUFFER_COMPLETE", + "FRAMEBUFFER_DEFAULT", + "FRAMEBUFFER_INCOMPLETE_ATTACHMENT", + "FRAMEBUFFER_INCOMPLETE_DIMENSIONS", + "FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT", + "FRAMEBUFFER_INCOMPLETE_MULTISAMPLE", + "FRAMEBUFFER_UNSUPPORTED", + "FRONT", + "FRONT_AND_BACK", + "FRONT_FACE", + "FUNC_ADD", + "FUNC_REVERSE_SUBTRACT", + "FUNC_SUBTRACT", + "FeaturePolicy", + "FeaturePolicyViolationReportBody", + "FederatedCredential", + "Feed", + "FeedEntry", + "Fence", + "FencedFrameConfig", + "File", + "FileError", + "FileList", + "FileReader", + "FileSystem", + "FileSystemDirectoryEntry", + "FileSystemDirectoryHandle", + "FileSystemDirectoryReader", + "FileSystemEntry", + "FileSystemFileEntry", + "FileSystemFileHandle", + "FileSystemHandle", + "FileSystemWritableFileStream", + "FinalizationRegistry", + "FindInPage", + "Float32Array", + "Float64Array", + "FocusEvent", + "FontData", + "FontFace", + "FontFaceSet", + "FontFaceSetLoadEvent", + "FormData", + "FormDataEvent", + "FragmentDirective", + "Function", + "GENERATE_MIPMAP_HINT", + "GEQUAL", + "GPU", + "GPUAdapter", + "GPUAdapterInfo", + "GPUBindGroup", + "GPUBindGroupLayout", + "GPUBuffer", + "GPUBufferUsage", + "GPUCanvasContext", + "GPUColorWrite", + "GPUCommandBuffer", + "GPUCommandEncoder", + "GPUCompilationInfo", + "GPUCompilationMessage", + "GPUComputePassEncoder", + "GPUComputePipeline", + "GPUDevice", + "GPUDeviceLostInfo", + "GPUError", + "GPUExternalTexture", + "GPUInternalError", + "GPUMapMode", + "GPUOutOfMemoryError", + "GPUPipelineError", + "GPUPipelineLayout", + "GPUQuerySet", + "GPUQueue", + "GPURenderBundle", + "GPURenderBundleEncoder", + "GPURenderPassEncoder", + "GPURenderPipeline", + "GPUSampler", + "GPUShaderModule", + "GPUShaderStage", + "GPUSupportedFeatures", + "GPUSupportedLimits", + "GPUTexture", + "GPUTextureUsage", + "GPUTextureView", + "GPUUncapturedErrorEvent", + "GPUValidationError", + "GREATER", + "GREEN", + "GREEN_BITS", + "GainNode", + "Gamepad", + "GamepadAxisMoveEvent", + "GamepadButton", + "GamepadButtonEvent", + "GamepadEvent", + "GamepadHapticActuator", + "GamepadPose", + "Geolocation", + "GeolocationCoordinates", + "GeolocationPosition", + "GeolocationPositionError", + "GestureEvent", + "Global", + "GravitySensor", + "Gyroscope", + "HALF_FLOAT", + "HAVE_CURRENT_DATA", + "HAVE_ENOUGH_DATA", + "HAVE_FUTURE_DATA", + "HAVE_METADATA", + "HAVE_NOTHING", + "HEADERS_RECEIVED", + "HID", + "HIDConnectionEvent", + "HIDDEN", + "HIDDevice", + "HIDInputReportEvent", + "HIERARCHY_REQUEST_ERR", + "HIGHPASS", + "HIGHSHELF", + "HIGH_FLOAT", + "HIGH_INT", + "HORIZONTAL", + "HORIZONTAL_AXIS", + "HRTF", + "HTMLAllCollection", + "HTMLAnchorElement", + "HTMLAppletElement", + "HTMLAreaElement", + "HTMLAudioElement", + "HTMLBRElement", + "HTMLBaseElement", + "HTMLBaseFontElement", + "HTMLBlockquoteElement", + "HTMLBodyElement", + "HTMLButtonElement", + "HTMLCanvasElement", + "HTMLCollection", + "HTMLCommandElement", + "HTMLContentElement", + "HTMLDListElement", + "HTMLDataElement", + "HTMLDataListElement", + "HTMLDetailsElement", + "HTMLDialogElement", + "HTMLDirectoryElement", + "HTMLDivElement", + "HTMLDocument", + "HTMLElement", + "HTMLEmbedElement", + "HTMLFencedFrameElement", + "HTMLFieldSetElement", + "HTMLFontElement", + "HTMLFormControlsCollection", + "HTMLFormElement", + "HTMLFrameElement", + "HTMLFrameSetElement", + "HTMLHRElement", + "HTMLHeadElement", + "HTMLHeadingElement", + "HTMLHtmlElement", + "HTMLIFrameElement", + "HTMLImageElement", + "HTMLInputElement", + "HTMLIsIndexElement", + "HTMLKeygenElement", + "HTMLLIElement", + "HTMLLabelElement", + "HTMLLegendElement", + "HTMLLinkElement", + "HTMLMapElement", + "HTMLMarqueeElement", + "HTMLMediaElement", + "HTMLMenuElement", + "HTMLMenuItemElement", + "HTMLMetaElement", + "HTMLMeterElement", + "HTMLModElement", + "HTMLOListElement", + "HTMLObjectElement", + "HTMLOptGroupElement", + "HTMLOptionElement", + "HTMLOptionsCollection", + "HTMLOutputElement", + "HTMLParagraphElement", + "HTMLParamElement", + "HTMLPictureElement", + "HTMLPreElement", + "HTMLProgressElement", + "HTMLPropertiesCollection", + "HTMLQuoteElement", + "HTMLScriptElement", + "HTMLSelectElement", + "HTMLShadowElement", + "HTMLSlotElement", + "HTMLSourceElement", + "HTMLSpanElement", + "HTMLStyleElement", + "HTMLTableCaptionElement", + "HTMLTableCellElement", + "HTMLTableColElement", + "HTMLTableElement", + "HTMLTableRowElement", + "HTMLTableSectionElement", + "HTMLTemplateElement", + "HTMLTextAreaElement", + "HTMLTimeElement", + "HTMLTitleElement", + "HTMLTrackElement", + "HTMLUListElement", + "HTMLUnknownElement", + "HTMLVideoElement", + "HashChangeEvent", + "Headers", + "Highlight", + "HighlightRegistry", + "History", + "Hz", + "ICE_CHECKING", + "ICE_CLOSED", + "ICE_COMPLETED", + "ICE_CONNECTED", + "ICE_FAILED", + "ICE_GATHERING", + "ICE_WAITING", + "IDBCursor", + "IDBCursorWithValue", + "IDBDatabase", + "IDBDatabaseException", + "IDBFactory", + "IDBFileHandle", + "IDBFileRequest", + "IDBIndex", + "IDBKeyRange", + "IDBMutableFile", + "IDBObjectStore", + "IDBOpenDBRequest", + "IDBRequest", + "IDBTransaction", + "IDBVersionChangeEvent", + "IDLE", + "IIRFilterNode", + "IMPLEMENTATION_COLOR_READ_FORMAT", + "IMPLEMENTATION_COLOR_READ_TYPE", + "IMPORT_RULE", + "INCR", + "INCR_WRAP", + "INDEX", + "INDEX_SIZE_ERR", + "INDIRECT", + "INT", + "INTERLEAVED_ATTRIBS", + "INT_2_10_10_10_REV", + "INT_SAMPLER_2D", + "INT_SAMPLER_2D_ARRAY", + "INT_SAMPLER_3D", + "INT_SAMPLER_CUBE", + "INT_VEC2", + "INT_VEC3", + "INT_VEC4", + "INUSE_ATTRIBUTE_ERR", + "INVALID_ACCESS_ERR", + "INVALID_CHARACTER_ERR", + "INVALID_ENUM", + "INVALID_EXPRESSION_ERR", + "INVALID_FRAMEBUFFER_OPERATION", + "INVALID_INDEX", + "INVALID_MODIFICATION_ERR", + "INVALID_NODE_TYPE_ERR", + "INVALID_OPERATION", + "INVALID_STATE_ERR", + "INVALID_VALUE", + "INVERSE_DISTANCE", + "INVERT", + "IceCandidate", + "IdentityCredential", + "IdentityCredentialError", + "IdentityProvider", + "IdleDeadline", + "IdleDetector", + "Image", + "ImageBitmap", + "ImageBitmapRenderingContext", + "ImageCapture", + "ImageData", + "ImageDecoder", + "ImageTrack", + "ImageTrackList", + "Infinity", + "Ink", + "InputDeviceCapabilities", + "InputDeviceInfo", + "InputEvent", + "InputMethodContext", + "InstallTrigger", + "InstallTriggerImpl", + "Instance", + "Int16Array", + "Int32Array", + "Int8Array", + "Intent", + "InternalError", + "IntersectionObserver", + "IntersectionObserverEntry", + "Intl", + "IsSearchProviderInstalled", + "Iterator", + "JSON", + "JSTag", + "KEEP", + "KEYDOWN", + "KEYFRAMES_RULE", + "KEYFRAME_RULE", + "KEYPRESS", + "KEYUP", + "KeyEvent", + "Keyboard", + "KeyboardEvent", + "KeyboardLayoutMap", + "KeyframeEffect", + "LENGTHADJUST_SPACING", + "LENGTHADJUST_SPACINGANDGLYPHS", + "LENGTHADJUST_UNKNOWN", + "LEQUAL", + "LESS", + "LINEAR", + "LINEAR_DISTANCE", + "LINEAR_MIPMAP_LINEAR", + "LINEAR_MIPMAP_NEAREST", + "LINES", + "LINE_LOOP", + "LINE_STRIP", + "LINE_WIDTH", + "LINK_STATUS", + "LIVE", + "LN10", + "LN2", + "LOADED", + "LOADING", + "LOG10E", + "LOG2E", + "LOWPASS", + "LOWSHELF", + "LOW_FLOAT", + "LOW_INT", + "LSException", + "LSParserFilter", + "LUMINANCE", + "LUMINANCE_ALPHA", + "LargestContentfulPaint", + "LaunchParams", + "LaunchQueue", + "LayoutShift", + "LayoutShiftAttribution", + "LinearAccelerationSensor", + "LinkError", + "ListFormat", + "LocalMediaStream", + "Locale", + "Location", + "Lock", + "LockManager", + "MAP_READ", + "MAP_WRITE", + "MAX", + "MAX_3D_TEXTURE_SIZE", + "MAX_ARRAY_TEXTURE_LAYERS", + "MAX_CLIENT_WAIT_TIMEOUT_WEBGL", + "MAX_COLOR_ATTACHMENTS", + "MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS", + "MAX_COMBINED_TEXTURE_IMAGE_UNITS", + "MAX_COMBINED_UNIFORM_BLOCKS", + "MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS", + "MAX_CUBE_MAP_TEXTURE_SIZE", + "MAX_DRAW_BUFFERS", + "MAX_ELEMENTS_INDICES", + "MAX_ELEMENTS_VERTICES", + "MAX_ELEMENT_INDEX", + "MAX_FRAGMENT_INPUT_COMPONENTS", + "MAX_FRAGMENT_UNIFORM_BLOCKS", + "MAX_FRAGMENT_UNIFORM_COMPONENTS", + "MAX_FRAGMENT_UNIFORM_VECTORS", + "MAX_PROGRAM_TEXEL_OFFSET", + "MAX_RENDERBUFFER_SIZE", + "MAX_SAFE_INTEGER", + "MAX_SAMPLES", + "MAX_SERVER_WAIT_TIMEOUT", + "MAX_TEXTURE_IMAGE_UNITS", + "MAX_TEXTURE_LOD_BIAS", + "MAX_TEXTURE_MAX_ANISOTROPY_EXT", + "MAX_TEXTURE_SIZE", + "MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS", + "MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS", + "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS", + "MAX_UNIFORM_BLOCK_SIZE", + "MAX_UNIFORM_BUFFER_BINDINGS", + "MAX_VALUE", + "MAX_VARYING_COMPONENTS", + "MAX_VARYING_VECTORS", + "MAX_VERTEX_ATTRIBS", + "MAX_VERTEX_OUTPUT_COMPONENTS", + "MAX_VERTEX_TEXTURE_IMAGE_UNITS", + "MAX_VERTEX_UNIFORM_BLOCKS", + "MAX_VERTEX_UNIFORM_COMPONENTS", + "MAX_VERTEX_UNIFORM_VECTORS", + "MAX_VIEWPORT_DIMS", + "MEDIA_ERR_ABORTED", + "MEDIA_ERR_DECODE", + "MEDIA_ERR_ENCRYPTED", + "MEDIA_ERR_NETWORK", + "MEDIA_ERR_SRC_NOT_SUPPORTED", + "MEDIA_KEYERR_CLIENT", + "MEDIA_KEYERR_DOMAIN", + "MEDIA_KEYERR_HARDWARECHANGE", + "MEDIA_KEYERR_OUTPUT", + "MEDIA_KEYERR_SERVICE", + "MEDIA_KEYERR_UNKNOWN", + "MEDIA_RULE", + "MEDIUM_FLOAT", + "MEDIUM_INT", + "META_MASK", + "MIDIAccess", + "MIDIConnectionEvent", + "MIDIInput", + "MIDIInputMap", + "MIDIMessageEvent", + "MIDIOutput", + "MIDIOutputMap", + "MIDIPort", + "MIN", + "MIN_PROGRAM_TEXEL_OFFSET", + "MIN_SAFE_INTEGER", + "MIN_VALUE", + "MIRRORED_REPEAT", + "MODE_ASYNCHRONOUS", + "MODE_SYNCHRONOUS", + "MODIFICATION", + "MOUSEDOWN", + "MOUSEDRAG", + "MOUSEMOVE", + "MOUSEOUT", + "MOUSEOVER", + "MOUSEUP", + "MOZ_KEYFRAMES_RULE", + "MOZ_KEYFRAME_RULE", + "MOZ_SOURCE_CURSOR", + "MOZ_SOURCE_ERASER", + "MOZ_SOURCE_KEYBOARD", + "MOZ_SOURCE_MOUSE", + "MOZ_SOURCE_PEN", + "MOZ_SOURCE_TOUCH", + "MOZ_SOURCE_UNKNOWN", + "MSGESTURE_FLAG_BEGIN", + "MSGESTURE_FLAG_CANCEL", + "MSGESTURE_FLAG_END", + "MSGESTURE_FLAG_INERTIA", + "MSGESTURE_FLAG_NONE", + "MSPOINTER_TYPE_MOUSE", + "MSPOINTER_TYPE_PEN", + "MSPOINTER_TYPE_TOUCH", + "MS_ASYNC_CALLBACK_STATUS_ASSIGN_DELEGATE", + "MS_ASYNC_CALLBACK_STATUS_CANCEL", + "MS_ASYNC_CALLBACK_STATUS_CHOOSEANY", + "MS_ASYNC_CALLBACK_STATUS_ERROR", + "MS_ASYNC_CALLBACK_STATUS_JOIN", + "MS_ASYNC_OP_STATUS_CANCELED", + "MS_ASYNC_OP_STATUS_ERROR", + "MS_ASYNC_OP_STATUS_SUCCESS", + "MS_MANIPULATION_STATE_ACTIVE", + "MS_MANIPULATION_STATE_CANCELLED", + "MS_MANIPULATION_STATE_COMMITTED", + "MS_MANIPULATION_STATE_DRAGGING", + "MS_MANIPULATION_STATE_INERTIA", + "MS_MANIPULATION_STATE_PRESELECT", + "MS_MANIPULATION_STATE_SELECTING", + "MS_MANIPULATION_STATE_STOPPED", + "MS_MEDIA_ERR_ENCRYPTED", + "MS_MEDIA_KEYERR_CLIENT", + "MS_MEDIA_KEYERR_DOMAIN", + "MS_MEDIA_KEYERR_HARDWARECHANGE", + "MS_MEDIA_KEYERR_OUTPUT", + "MS_MEDIA_KEYERR_SERVICE", + "MS_MEDIA_KEYERR_UNKNOWN", + "Map", + "Math", + "MathMLElement", + "MediaCapabilities", + "MediaCapabilitiesInfo", + "MediaController", + "MediaDeviceInfo", + "MediaDevices", + "MediaElementAudioSourceNode", + "MediaEncryptedEvent", + "MediaError", + "MediaKeyError", + "MediaKeyEvent", + "MediaKeyMessageEvent", + "MediaKeyNeededEvent", + "MediaKeySession", + "MediaKeyStatusMap", + "MediaKeySystemAccess", + "MediaKeys", + "MediaList", + "MediaMetadata", + "MediaQueryList", + "MediaQueryListEvent", + "MediaRecorder", + "MediaRecorderErrorEvent", + "MediaSession", + "MediaSettingsRange", + "MediaSource", + "MediaSourceHandle", + "MediaStream", + "MediaStreamAudioDestinationNode", + "MediaStreamAudioSourceNode", + "MediaStreamEvent", + "MediaStreamTrack", + "MediaStreamTrackAudioSourceNode", + "MediaStreamTrackEvent", + "MediaStreamTrackGenerator", + "MediaStreamTrackProcessor", + "MediaStreamTrackVideoStats", + "Memory", + "MessageChannel", + "MessageEvent", + "MessagePort", + "Methods", + "MimeType", + "MimeTypeArray", + "Module", + "MouseEvent", + "MouseScrollEvent", + "MozAnimation", + "MozAnimationDelay", + "MozAnimationDirection", + "MozAnimationDuration", + "MozAnimationFillMode", + "MozAnimationIterationCount", + "MozAnimationName", + "MozAnimationPlayState", + "MozAnimationTimingFunction", + "MozAppearance", + "MozBackfaceVisibility", + "MozBinding", + "MozBorderBottomColors", + "MozBorderEnd", + "MozBorderEndColor", + "MozBorderEndStyle", + "MozBorderEndWidth", + "MozBorderImage", + "MozBorderLeftColors", + "MozBorderRightColors", + "MozBorderStart", + "MozBorderStartColor", + "MozBorderStartStyle", + "MozBorderStartWidth", + "MozBorderTopColors", + "MozBoxAlign", + "MozBoxDirection", + "MozBoxFlex", + "MozBoxOrdinalGroup", + "MozBoxOrient", + "MozBoxPack", + "MozBoxSizing", + "MozCSSKeyframeRule", + "MozCSSKeyframesRule", + "MozColumnCount", + "MozColumnFill", + "MozColumnGap", + "MozColumnRule", + "MozColumnRuleColor", + "MozColumnRuleStyle", + "MozColumnRuleWidth", + "MozColumnWidth", + "MozColumns", + "MozContactChangeEvent", + "MozFloatEdge", + "MozFontFeatureSettings", + "MozFontLanguageOverride", + "MozForceBrokenImageIcon", + "MozHyphens", + "MozImageRegion", + "MozMarginEnd", + "MozMarginStart", + "MozMmsEvent", + "MozMmsMessage", + "MozMobileMessageThread", + "MozOSXFontSmoothing", + "MozOrient", + "MozOsxFontSmoothing", + "MozOutlineRadius", + "MozOutlineRadiusBottomleft", + "MozOutlineRadiusBottomright", + "MozOutlineRadiusTopleft", + "MozOutlineRadiusTopright", + "MozPaddingEnd", + "MozPaddingStart", + "MozPerspective", + "MozPerspectiveOrigin", + "MozPowerManager", + "MozSettingsEvent", + "MozSmsEvent", + "MozSmsMessage", + "MozStackSizing", + "MozTabSize", + "MozTextAlignLast", + "MozTextDecorationColor", + "MozTextDecorationLine", + "MozTextDecorationStyle", + "MozTextSizeAdjust", + "MozTransform", + "MozTransformOrigin", + "MozTransformStyle", + "MozTransition", + "MozTransitionDelay", + "MozTransitionDuration", + "MozTransitionProperty", + "MozTransitionTimingFunction", + "MozUserFocus", + "MozUserInput", + "MozUserModify", + "MozUserSelect", + "MozWindowDragging", + "MozWindowShadow", + "MutationEvent", + "MutationObserver", + "MutationRecord", + "NAMESPACE_ERR", + "NAMESPACE_RULE", + "NEAREST", + "NEAREST_MIPMAP_LINEAR", + "NEAREST_MIPMAP_NEAREST", + "NEGATIVE_INFINITY", + "NETWORK_EMPTY", + "NETWORK_ERR", + "NETWORK_IDLE", + "NETWORK_LOADED", + "NETWORK_LOADING", + "NETWORK_NO_SOURCE", + "NEVER", + "NEW", + "NEXT", + "NEXT_NO_DUPLICATE", + "NICEST", + "NODE_AFTER", + "NODE_BEFORE", + "NODE_BEFORE_AND_AFTER", + "NODE_INSIDE", + "NONE", + "NON_TRANSIENT_ERR", + "NOTATION_NODE", + "NOTCH", + "NOTEQUAL", + "NOT_ALLOWED_ERR", + "NOT_FOUND_ERR", + "NOT_READABLE_ERR", + "NOT_SUPPORTED_ERR", + "NO_DATA_ALLOWED_ERR", + "NO_ERR", + "NO_ERROR", + "NO_MODIFICATION_ALLOWED_ERR", + "NUMBER_TYPE", + "NUM_COMPRESSED_TEXTURE_FORMATS", + "NaN", + "NamedNodeMap", + "NavigateEvent", + "Navigation", + "NavigationActivation", + "NavigationCurrentEntryChangeEvent", + "NavigationDestination", + "NavigationHistoryEntry", + "NavigationPreloadManager", + "NavigationTransition", + "Navigator", + "NavigatorLogin", + "NavigatorManagedData", + "NavigatorUAData", + "NearbyLinks", + "NetworkInformation", + "Node", + "NodeFilter", + "NodeIterator", + "NodeList", + "NotRestoredReasonDetails", + "NotRestoredReasons", + "Notation", + "Notification", + "NotifyPaintEvent", + "Number", + "NumberFormat", + "OBJECT_TYPE", + "OBSOLETE", + "OK", + "ONE", + "ONE_MINUS_CONSTANT_ALPHA", + "ONE_MINUS_CONSTANT_COLOR", + "ONE_MINUS_DST_ALPHA", + "ONE_MINUS_DST_COLOR", + "ONE_MINUS_SRC_ALPHA", + "ONE_MINUS_SRC_COLOR", + "OPEN", + "OPENED", + "OPENING", + "ORDERED_NODE_ITERATOR_TYPE", + "ORDERED_NODE_SNAPSHOT_TYPE", + "OTHER_ERROR", + "OTPCredential", + "OUT_OF_MEMORY", + "Object", + "OfflineAudioCompletionEvent", + "OfflineAudioContext", + "OfflineResourceList", + "OffscreenCanvas", + "OffscreenCanvasRenderingContext2D", + "Option", + "OrientationSensor", + "OscillatorNode", + "OverconstrainedError", + "OverflowEvent", + "PACK_ALIGNMENT", + "PACK_ROW_LENGTH", + "PACK_SKIP_PIXELS", + "PACK_SKIP_ROWS", + "PAGE_RULE", + "PARSE_ERR", + "PATHSEG_ARC_ABS", + "PATHSEG_ARC_REL", + "PATHSEG_CLOSEPATH", + "PATHSEG_CURVETO_CUBIC_ABS", + "PATHSEG_CURVETO_CUBIC_REL", + "PATHSEG_CURVETO_CUBIC_SMOOTH_ABS", + "PATHSEG_CURVETO_CUBIC_SMOOTH_REL", + "PATHSEG_CURVETO_QUADRATIC_ABS", + "PATHSEG_CURVETO_QUADRATIC_REL", + "PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS", + "PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL", + "PATHSEG_LINETO_ABS", + "PATHSEG_LINETO_HORIZONTAL_ABS", + "PATHSEG_LINETO_HORIZONTAL_REL", + "PATHSEG_LINETO_REL", + "PATHSEG_LINETO_VERTICAL_ABS", + "PATHSEG_LINETO_VERTICAL_REL", + "PATHSEG_MOVETO_ABS", + "PATHSEG_MOVETO_REL", + "PATHSEG_UNKNOWN", + "PATH_EXISTS_ERR", + "PEAKING", + "PERMISSION_DENIED", + "PERSISTENT", + "PI", + "PIXEL_PACK_BUFFER", + "PIXEL_PACK_BUFFER_BINDING", + "PIXEL_UNPACK_BUFFER", + "PIXEL_UNPACK_BUFFER_BINDING", + "PLAYING_STATE", + "POINTS", + "POLYGON_OFFSET_FACTOR", + "POLYGON_OFFSET_FILL", + "POLYGON_OFFSET_UNITS", + "POSITION_UNAVAILABLE", + "POSITIVE_INFINITY", + "PREV", + "PREV_NO_DUPLICATE", + "PROCESSING_INSTRUCTION_NODE", + "PageChangeEvent", + "PageRevealEvent", + "PageSwapEvent", + "PageTransitionEvent", + "PaintRequest", + "PaintRequestList", + "PannerNode", + "PasswordCredential", + "Path2D", + "PaymentAddress", + "PaymentInstruments", + "PaymentManager", + "PaymentMethodChangeEvent", + "PaymentRequest", + "PaymentRequestUpdateEvent", + "PaymentResponse", + "Performance", + "PerformanceElementTiming", + "PerformanceEntry", + "PerformanceEventTiming", + "PerformanceLongAnimationFrameTiming", + "PerformanceLongTaskTiming", + "PerformanceMark", + "PerformanceMeasure", + "PerformanceNavigation", + "PerformanceNavigationTiming", + "PerformanceObserver", + "PerformanceObserverEntryList", + "PerformancePaintTiming", + "PerformanceResourceTiming", + "PerformanceScriptTiming", + "PerformanceServerTiming", + "PerformanceTiming", + "PeriodicSyncManager", + "PeriodicWave", + "PermissionStatus", + "Permissions", + "PhotoCapabilities", + "PictureInPictureEvent", + "PictureInPictureWindow", + "Plugin", + "PluginArray", + "PluralRules", + "PointerEvent", + "PopStateEvent", + "PopupBlockedEvent", + "Presentation", + "PresentationAvailability", + "PresentationConnection", + "PresentationConnectionAvailableEvent", + "PresentationConnectionCloseEvent", + "PresentationConnectionList", + "PresentationReceiver", + "PresentationRequest", + "ProcessingInstruction", + "Profiler", + "ProgressEvent", + "Promise", + "PromiseRejectionEvent", + "PropertyNodeList", + "Proxy", + "PublicKeyCredential", + "PushManager", + "PushSubscription", + "PushSubscriptionOptions", + "Q", + "QUERY_RESOLVE", + "QUERY_RESULT", + "QUERY_RESULT_AVAILABLE", + "QUOTA_ERR", + "QUOTA_EXCEEDED_ERR", + "QueryInterface", + "R11F_G11F_B10F", + "R16F", + "R16I", + "R16UI", + "R32F", + "R32I", + "R32UI", + "R8", + "R8I", + "R8UI", + "R8_SNORM", + "RASTERIZER_DISCARD", + "READ", + "READ_BUFFER", + "READ_FRAMEBUFFER", + "READ_FRAMEBUFFER_BINDING", + "READ_ONLY", + "READ_ONLY_ERR", + "READ_WRITE", + "RED", + "RED_BITS", + "RED_INTEGER", + "REMOVAL", + "RENDERBUFFER", + "RENDERBUFFER_ALPHA_SIZE", + "RENDERBUFFER_BINDING", + "RENDERBUFFER_BLUE_SIZE", + "RENDERBUFFER_DEPTH_SIZE", + "RENDERBUFFER_GREEN_SIZE", + "RENDERBUFFER_HEIGHT", + "RENDERBUFFER_INTERNAL_FORMAT", + "RENDERBUFFER_RED_SIZE", + "RENDERBUFFER_SAMPLES", + "RENDERBUFFER_STENCIL_SIZE", + "RENDERBUFFER_WIDTH", + "RENDERER", + "RENDERING_INTENT_ABSOLUTE_COLORIMETRIC", + "RENDERING_INTENT_AUTO", + "RENDERING_INTENT_PERCEPTUAL", + "RENDERING_INTENT_RELATIVE_COLORIMETRIC", + "RENDERING_INTENT_SATURATION", + "RENDERING_INTENT_UNKNOWN", + "RENDER_ATTACHMENT", + "REPEAT", + "REPLACE", + "RG", + "RG16F", + "RG16I", + "RG16UI", + "RG32F", + "RG32I", + "RG32UI", + "RG8", + "RG8I", + "RG8UI", + "RG8_SNORM", + "RGB", + "RGB10_A2", + "RGB10_A2UI", + "RGB16F", + "RGB16I", + "RGB16UI", + "RGB32F", + "RGB32I", + "RGB32UI", + "RGB565", + "RGB5_A1", + "RGB8", + "RGB8I", + "RGB8UI", + "RGB8_SNORM", + "RGB9_E5", + "RGBA", + "RGBA16F", + "RGBA16I", + "RGBA16UI", + "RGBA32F", + "RGBA32I", + "RGBA32UI", + "RGBA4", + "RGBA8", + "RGBA8I", + "RGBA8UI", + "RGBA8_SNORM", + "RGBA_INTEGER", + "RGBColor", + "RGB_INTEGER", + "RG_INTEGER", + "ROTATION_CLOCKWISE", + "ROTATION_COUNTERCLOCKWISE", + "RTCCertificate", + "RTCDTMFSender", + "RTCDTMFToneChangeEvent", + "RTCDataChannel", + "RTCDataChannelEvent", + "RTCDtlsTransport", + "RTCEncodedAudioFrame", + "RTCEncodedVideoFrame", + "RTCError", + "RTCErrorEvent", + "RTCIceCandidate", + "RTCIceTransport", + "RTCPeerConnection", + "RTCPeerConnectionIceErrorEvent", + "RTCPeerConnectionIceEvent", + "RTCRtpReceiver", + "RTCRtpScriptTransform", + "RTCRtpSender", + "RTCRtpTransceiver", + "RTCSctpTransport", + "RTCSessionDescription", + "RTCStatsReport", + "RTCTrackEvent", + "RadioNodeList", + "Range", + "RangeError", + "RangeException", + "ReadableByteStreamController", + "ReadableStream", + "ReadableStreamBYOBReader", + "ReadableStreamBYOBRequest", + "ReadableStreamDefaultController", + "ReadableStreamDefaultReader", + "RecordErrorEvent", + "Rect", + "ReferenceError", + "Reflect", + "RegExp", + "RelativeOrientationSensor", + "RelativeTimeFormat", + "RemotePlayback", + "Report", + "ReportBody", + "ReportingObserver", + "Request", + "ResizeObserver", + "ResizeObserverEntry", + "ResizeObserverSize", + "Response", + "RuntimeError", + "SAMPLER_2D", + "SAMPLER_2D_ARRAY", + "SAMPLER_2D_ARRAY_SHADOW", + "SAMPLER_2D_SHADOW", + "SAMPLER_3D", + "SAMPLER_BINDING", + "SAMPLER_CUBE", + "SAMPLER_CUBE_SHADOW", + "SAMPLES", + "SAMPLE_ALPHA_TO_COVERAGE", + "SAMPLE_BUFFERS", + "SAMPLE_COVERAGE", + "SAMPLE_COVERAGE_INVERT", + "SAMPLE_COVERAGE_VALUE", + "SAWTOOTH", + "SCHEDULED_STATE", + "SCISSOR_BOX", + "SCISSOR_TEST", + "SCROLL_PAGE_DOWN", + "SCROLL_PAGE_UP", + "SDP_ANSWER", + "SDP_OFFER", + "SDP_PRANSWER", + "SECURITY_ERR", + "SELECT", + "SEPARATE_ATTRIBS", + "SERIALIZE_ERR", + "SEVERITY_ERROR", + "SEVERITY_FATAL_ERROR", + "SEVERITY_WARNING", + "SHADER_COMPILER", + "SHADER_TYPE", + "SHADING_LANGUAGE_VERSION", + "SHIFT_MASK", + "SHORT", + "SHOWING", + "SHOW_ALL", + "SHOW_ATTRIBUTE", + "SHOW_CDATA_SECTION", + "SHOW_COMMENT", + "SHOW_DOCUMENT", + "SHOW_DOCUMENT_FRAGMENT", + "SHOW_DOCUMENT_TYPE", + "SHOW_ELEMENT", + "SHOW_ENTITY", + "SHOW_ENTITY_REFERENCE", + "SHOW_NOTATION", + "SHOW_PROCESSING_INSTRUCTION", + "SHOW_TEXT", + "SIGNALED", + "SIGNED_NORMALIZED", + "SINE", + "SOUNDFIELD", + "SQLException", + "SQRT1_2", + "SQRT2", + "SQUARE", + "SRC_ALPHA", + "SRC_ALPHA_SATURATE", + "SRC_COLOR", + "SRGB", + "SRGB8", + "SRGB8_ALPHA8", + "START_TO_END", + "START_TO_START", + "STATIC_COPY", + "STATIC_DRAW", + "STATIC_READ", + "STENCIL", + "STENCIL_ATTACHMENT", + "STENCIL_BACK_FAIL", + "STENCIL_BACK_FUNC", + "STENCIL_BACK_PASS_DEPTH_FAIL", + "STENCIL_BACK_PASS_DEPTH_PASS", + "STENCIL_BACK_REF", + "STENCIL_BACK_VALUE_MASK", + "STENCIL_BACK_WRITEMASK", + "STENCIL_BITS", + "STENCIL_BUFFER_BIT", + "STENCIL_CLEAR_VALUE", + "STENCIL_FAIL", + "STENCIL_FUNC", + "STENCIL_INDEX", + "STENCIL_INDEX8", + "STENCIL_PASS_DEPTH_FAIL", + "STENCIL_PASS_DEPTH_PASS", + "STENCIL_REF", + "STENCIL_TEST", + "STENCIL_VALUE_MASK", + "STENCIL_WRITEMASK", + "STORAGE", + "STORAGE_BINDING", + "STREAM_COPY", + "STREAM_DRAW", + "STREAM_READ", + "STRING_TYPE", + "STYLE_RULE", + "SUBPIXEL_BITS", + "SUPPORTS_RULE", + "SVGAElement", + "SVGAltGlyphDefElement", + "SVGAltGlyphElement", + "SVGAltGlyphItemElement", + "SVGAngle", + "SVGAnimateColorElement", + "SVGAnimateElement", + "SVGAnimateMotionElement", + "SVGAnimateTransformElement", + "SVGAnimatedAngle", + "SVGAnimatedBoolean", + "SVGAnimatedEnumeration", + "SVGAnimatedInteger", + "SVGAnimatedLength", + "SVGAnimatedLengthList", + "SVGAnimatedNumber", + "SVGAnimatedNumberList", + "SVGAnimatedPreserveAspectRatio", + "SVGAnimatedRect", + "SVGAnimatedString", + "SVGAnimatedTransformList", + "SVGAnimationElement", + "SVGCircleElement", + "SVGClipPathElement", + "SVGColor", + "SVGComponentTransferFunctionElement", + "SVGCursorElement", + "SVGDefsElement", + "SVGDescElement", + "SVGDiscardElement", + "SVGDocument", + "SVGElement", + "SVGElementInstance", + "SVGElementInstanceList", + "SVGEllipseElement", + "SVGException", + "SVGFEBlendElement", + "SVGFEColorMatrixElement", + "SVGFEComponentTransferElement", + "SVGFECompositeElement", + "SVGFEConvolveMatrixElement", + "SVGFEDiffuseLightingElement", + "SVGFEDisplacementMapElement", + "SVGFEDistantLightElement", + "SVGFEDropShadowElement", + "SVGFEFloodElement", + "SVGFEFuncAElement", + "SVGFEFuncBElement", + "SVGFEFuncGElement", + "SVGFEFuncRElement", + "SVGFEGaussianBlurElement", + "SVGFEImageElement", + "SVGFEMergeElement", + "SVGFEMergeNodeElement", + "SVGFEMorphologyElement", + "SVGFEOffsetElement", + "SVGFEPointLightElement", + "SVGFESpecularLightingElement", + "SVGFESpotLightElement", + "SVGFETileElement", + "SVGFETurbulenceElement", + "SVGFilterElement", + "SVGFontElement", + "SVGFontFaceElement", + "SVGFontFaceFormatElement", + "SVGFontFaceNameElement", + "SVGFontFaceSrcElement", + "SVGFontFaceUriElement", + "SVGForeignObjectElement", + "SVGGElement", + "SVGGeometryElement", + "SVGGlyphElement", + "SVGGlyphRefElement", + "SVGGradientElement", + "SVGGraphicsElement", + "SVGHKernElement", + "SVGImageElement", + "SVGLength", + "SVGLengthList", + "SVGLineElement", + "SVGLinearGradientElement", + "SVGMPathElement", + "SVGMarkerElement", + "SVGMaskElement", + "SVGMatrix", + "SVGMetadataElement", + "SVGMissingGlyphElement", + "SVGNumber", + "SVGNumberList", + "SVGPaint", + "SVGPathElement", + "SVGPathSeg", + "SVGPathSegArcAbs", + "SVGPathSegArcRel", + "SVGPathSegClosePath", + "SVGPathSegCurvetoCubicAbs", + "SVGPathSegCurvetoCubicRel", + "SVGPathSegCurvetoCubicSmoothAbs", + "SVGPathSegCurvetoCubicSmoothRel", + "SVGPathSegCurvetoQuadraticAbs", + "SVGPathSegCurvetoQuadraticRel", + "SVGPathSegCurvetoQuadraticSmoothAbs", + "SVGPathSegCurvetoQuadraticSmoothRel", + "SVGPathSegLinetoAbs", + "SVGPathSegLinetoHorizontalAbs", + "SVGPathSegLinetoHorizontalRel", + "SVGPathSegLinetoRel", + "SVGPathSegLinetoVerticalAbs", + "SVGPathSegLinetoVerticalRel", + "SVGPathSegList", + "SVGPathSegMovetoAbs", + "SVGPathSegMovetoRel", + "SVGPatternElement", + "SVGPoint", + "SVGPointList", + "SVGPolygonElement", + "SVGPolylineElement", + "SVGPreserveAspectRatio", + "SVGRadialGradientElement", + "SVGRect", + "SVGRectElement", + "SVGRenderingIntent", + "SVGSVGElement", + "SVGScriptElement", + "SVGSetElement", + "SVGStopElement", + "SVGStringList", + "SVGStyleElement", + "SVGSwitchElement", + "SVGSymbolElement", + "SVGTRefElement", + "SVGTSpanElement", + "SVGTextContentElement", + "SVGTextElement", + "SVGTextPathElement", + "SVGTextPositioningElement", + "SVGTitleElement", + "SVGTransform", + "SVGTransformList", + "SVGUnitTypes", + "SVGUseElement", + "SVGVKernElement", + "SVGViewElement", + "SVGViewSpec", + "SVGZoomAndPan", + "SVGZoomEvent", + "SVG_ANGLETYPE_DEG", + "SVG_ANGLETYPE_GRAD", + "SVG_ANGLETYPE_RAD", + "SVG_ANGLETYPE_UNKNOWN", + "SVG_ANGLETYPE_UNSPECIFIED", + "SVG_CHANNEL_A", + "SVG_CHANNEL_B", + "SVG_CHANNEL_G", + "SVG_CHANNEL_R", + "SVG_CHANNEL_UNKNOWN", + "SVG_COLORTYPE_CURRENTCOLOR", + "SVG_COLORTYPE_RGBCOLOR", + "SVG_COLORTYPE_RGBCOLOR_ICCCOLOR", + "SVG_COLORTYPE_UNKNOWN", + "SVG_EDGEMODE_DUPLICATE", + "SVG_EDGEMODE_NONE", + "SVG_EDGEMODE_UNKNOWN", + "SVG_EDGEMODE_WRAP", + "SVG_FEBLEND_MODE_COLOR", + "SVG_FEBLEND_MODE_COLOR_BURN", + "SVG_FEBLEND_MODE_COLOR_DODGE", + "SVG_FEBLEND_MODE_DARKEN", + "SVG_FEBLEND_MODE_DIFFERENCE", + "SVG_FEBLEND_MODE_EXCLUSION", + "SVG_FEBLEND_MODE_HARD_LIGHT", + "SVG_FEBLEND_MODE_HUE", + "SVG_FEBLEND_MODE_LIGHTEN", + "SVG_FEBLEND_MODE_LUMINOSITY", + "SVG_FEBLEND_MODE_MULTIPLY", + "SVG_FEBLEND_MODE_NORMAL", + "SVG_FEBLEND_MODE_OVERLAY", + "SVG_FEBLEND_MODE_SATURATION", + "SVG_FEBLEND_MODE_SCREEN", + "SVG_FEBLEND_MODE_SOFT_LIGHT", + "SVG_FEBLEND_MODE_UNKNOWN", + "SVG_FECOLORMATRIX_TYPE_HUEROTATE", + "SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA", + "SVG_FECOLORMATRIX_TYPE_MATRIX", + "SVG_FECOLORMATRIX_TYPE_SATURATE", + "SVG_FECOLORMATRIX_TYPE_UNKNOWN", + "SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE", + "SVG_FECOMPONENTTRANSFER_TYPE_GAMMA", + "SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY", + "SVG_FECOMPONENTTRANSFER_TYPE_LINEAR", + "SVG_FECOMPONENTTRANSFER_TYPE_TABLE", + "SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN", + "SVG_FECOMPOSITE_OPERATOR_ARITHMETIC", + "SVG_FECOMPOSITE_OPERATOR_ATOP", + "SVG_FECOMPOSITE_OPERATOR_IN", + "SVG_FECOMPOSITE_OPERATOR_LIGHTER", + "SVG_FECOMPOSITE_OPERATOR_OUT", + "SVG_FECOMPOSITE_OPERATOR_OVER", + "SVG_FECOMPOSITE_OPERATOR_UNKNOWN", + "SVG_FECOMPOSITE_OPERATOR_XOR", + "SVG_INVALID_VALUE_ERR", + "SVG_LENGTHTYPE_CM", + "SVG_LENGTHTYPE_EMS", + "SVG_LENGTHTYPE_EXS", + "SVG_LENGTHTYPE_IN", + "SVG_LENGTHTYPE_MM", + "SVG_LENGTHTYPE_NUMBER", + "SVG_LENGTHTYPE_PC", + "SVG_LENGTHTYPE_PERCENTAGE", + "SVG_LENGTHTYPE_PT", + "SVG_LENGTHTYPE_PX", + "SVG_LENGTHTYPE_UNKNOWN", + "SVG_MARKERUNITS_STROKEWIDTH", + "SVG_MARKERUNITS_UNKNOWN", + "SVG_MARKERUNITS_USERSPACEONUSE", + "SVG_MARKER_ORIENT_ANGLE", + "SVG_MARKER_ORIENT_AUTO", + "SVG_MARKER_ORIENT_AUTO_START_REVERSE", + "SVG_MARKER_ORIENT_UNKNOWN", + "SVG_MASKTYPE_ALPHA", + "SVG_MASKTYPE_LUMINANCE", + "SVG_MATRIX_NOT_INVERTABLE", + "SVG_MEETORSLICE_MEET", + "SVG_MEETORSLICE_SLICE", + "SVG_MEETORSLICE_UNKNOWN", + "SVG_MORPHOLOGY_OPERATOR_DILATE", + "SVG_MORPHOLOGY_OPERATOR_ERODE", + "SVG_MORPHOLOGY_OPERATOR_UNKNOWN", + "SVG_PAINTTYPE_CURRENTCOLOR", + "SVG_PAINTTYPE_NONE", + "SVG_PAINTTYPE_RGBCOLOR", + "SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR", + "SVG_PAINTTYPE_UNKNOWN", + "SVG_PAINTTYPE_URI", + "SVG_PAINTTYPE_URI_CURRENTCOLOR", + "SVG_PAINTTYPE_URI_NONE", + "SVG_PAINTTYPE_URI_RGBCOLOR", + "SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR", + "SVG_PRESERVEASPECTRATIO_NONE", + "SVG_PRESERVEASPECTRATIO_UNKNOWN", + "SVG_PRESERVEASPECTRATIO_XMAXYMAX", + "SVG_PRESERVEASPECTRATIO_XMAXYMID", + "SVG_PRESERVEASPECTRATIO_XMAXYMIN", + "SVG_PRESERVEASPECTRATIO_XMIDYMAX", + "SVG_PRESERVEASPECTRATIO_XMIDYMID", + "SVG_PRESERVEASPECTRATIO_XMIDYMIN", + "SVG_PRESERVEASPECTRATIO_XMINYMAX", + "SVG_PRESERVEASPECTRATIO_XMINYMID", + "SVG_PRESERVEASPECTRATIO_XMINYMIN", + "SVG_SPREADMETHOD_PAD", + "SVG_SPREADMETHOD_REFLECT", + "SVG_SPREADMETHOD_REPEAT", + "SVG_SPREADMETHOD_UNKNOWN", + "SVG_STITCHTYPE_NOSTITCH", + "SVG_STITCHTYPE_STITCH", + "SVG_STITCHTYPE_UNKNOWN", + "SVG_TRANSFORM_MATRIX", + "SVG_TRANSFORM_ROTATE", + "SVG_TRANSFORM_SCALE", + "SVG_TRANSFORM_SKEWX", + "SVG_TRANSFORM_SKEWY", + "SVG_TRANSFORM_TRANSLATE", + "SVG_TRANSFORM_UNKNOWN", + "SVG_TURBULENCE_TYPE_FRACTALNOISE", + "SVG_TURBULENCE_TYPE_TURBULENCE", + "SVG_TURBULENCE_TYPE_UNKNOWN", + "SVG_UNIT_TYPE_OBJECTBOUNDINGBOX", + "SVG_UNIT_TYPE_UNKNOWN", + "SVG_UNIT_TYPE_USERSPACEONUSE", + "SVG_WRONG_TYPE_ERR", + "SVG_ZOOMANDPAN_DISABLE", + "SVG_ZOOMANDPAN_MAGNIFY", + "SVG_ZOOMANDPAN_UNKNOWN", + "SYNC_CONDITION", + "SYNC_FENCE", + "SYNC_FLAGS", + "SYNC_FLUSH_COMMANDS_BIT", + "SYNC_GPU_COMMANDS_COMPLETE", + "SYNC_STATUS", + "SYNTAX_ERR", + "SavedPages", + "Scheduler", + "Scheduling", + "Screen", + "ScreenDetailed", + "ScreenDetails", + "ScreenOrientation", + "Script", + "ScriptProcessorNode", + "ScrollAreaEvent", + "ScrollTimeline", + "SecurityPolicyViolationEvent", + "Segmenter", + "Selection", + "Sensor", + "SensorErrorEvent", + "Serial", + "SerialPort", + "ServiceWorker", + "ServiceWorkerContainer", + "ServiceWorkerRegistration", + "SessionDescription", + "Set", + "ShadowRoot", + "SharedArrayBuffer", + "SharedStorage", + "SharedStorageWorklet", + "SharedWorker", + "SimpleGestureEvent", + "SourceBuffer", + "SourceBufferList", + "SpeechSynthesis", + "SpeechSynthesisErrorEvent", + "SpeechSynthesisEvent", + "SpeechSynthesisUtterance", + "SpeechSynthesisVoice", + "StaticRange", + "StereoPannerNode", + "StopIteration", + "Storage", + "StorageBucket", + "StorageBucketManager", + "StorageEvent", + "StorageManager", + "String", + "StructType", + "StylePropertyMap", + "StylePropertyMapReadOnly", + "StyleSheet", + "StyleSheetList", + "SubmitEvent", + "SubtleCrypto", + "Symbol", + "SyncManager", + "SyntaxError", + "TEMPORARY", + "TEXTPATH_METHODTYPE_ALIGN", + "TEXTPATH_METHODTYPE_STRETCH", + "TEXTPATH_METHODTYPE_UNKNOWN", + "TEXTPATH_SPACINGTYPE_AUTO", + "TEXTPATH_SPACINGTYPE_EXACT", + "TEXTPATH_SPACINGTYPE_UNKNOWN", + "TEXTURE", + "TEXTURE0", + "TEXTURE1", + "TEXTURE10", + "TEXTURE11", + "TEXTURE12", + "TEXTURE13", + "TEXTURE14", + "TEXTURE15", + "TEXTURE16", + "TEXTURE17", + "TEXTURE18", + "TEXTURE19", + "TEXTURE2", + "TEXTURE20", + "TEXTURE21", + "TEXTURE22", + "TEXTURE23", + "TEXTURE24", + "TEXTURE25", + "TEXTURE26", + "TEXTURE27", + "TEXTURE28", + "TEXTURE29", + "TEXTURE3", + "TEXTURE30", + "TEXTURE31", + "TEXTURE4", + "TEXTURE5", + "TEXTURE6", + "TEXTURE7", + "TEXTURE8", + "TEXTURE9", + "TEXTURE_2D", + "TEXTURE_2D_ARRAY", + "TEXTURE_3D", + "TEXTURE_BASE_LEVEL", + "TEXTURE_BINDING", + "TEXTURE_BINDING_2D", + "TEXTURE_BINDING_2D_ARRAY", + "TEXTURE_BINDING_3D", + "TEXTURE_BINDING_CUBE_MAP", + "TEXTURE_COMPARE_FUNC", + "TEXTURE_COMPARE_MODE", + "TEXTURE_CUBE_MAP", + "TEXTURE_CUBE_MAP_NEGATIVE_X", + "TEXTURE_CUBE_MAP_NEGATIVE_Y", + "TEXTURE_CUBE_MAP_NEGATIVE_Z", + "TEXTURE_CUBE_MAP_POSITIVE_X", + "TEXTURE_CUBE_MAP_POSITIVE_Y", + "TEXTURE_CUBE_MAP_POSITIVE_Z", + "TEXTURE_IMMUTABLE_FORMAT", + "TEXTURE_IMMUTABLE_LEVELS", + "TEXTURE_MAG_FILTER", + "TEXTURE_MAX_ANISOTROPY_EXT", + "TEXTURE_MAX_LEVEL", + "TEXTURE_MAX_LOD", + "TEXTURE_MIN_FILTER", + "TEXTURE_MIN_LOD", + "TEXTURE_WRAP_R", + "TEXTURE_WRAP_S", + "TEXTURE_WRAP_T", + "TEXT_NODE", + "TIMEOUT", + "TIMEOUT_ERR", + "TIMEOUT_EXPIRED", + "TIMEOUT_IGNORED", + "TOO_LARGE_ERR", + "TRANSACTION_INACTIVE_ERR", + "TRANSFORM_FEEDBACK", + "TRANSFORM_FEEDBACK_ACTIVE", + "TRANSFORM_FEEDBACK_BINDING", + "TRANSFORM_FEEDBACK_BUFFER", + "TRANSFORM_FEEDBACK_BUFFER_BINDING", + "TRANSFORM_FEEDBACK_BUFFER_MODE", + "TRANSFORM_FEEDBACK_BUFFER_SIZE", + "TRANSFORM_FEEDBACK_BUFFER_START", + "TRANSFORM_FEEDBACK_PAUSED", + "TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN", + "TRANSFORM_FEEDBACK_VARYINGS", + "TRIANGLE", + "TRIANGLES", + "TRIANGLE_FAN", + "TRIANGLE_STRIP", + "TYPE_BACK_FORWARD", + "TYPE_ERR", + "TYPE_MISMATCH_ERR", + "TYPE_NAVIGATE", + "TYPE_RELOAD", + "TYPE_RESERVED", + "Table", + "Tag", + "TaskAttributionTiming", + "TaskController", + "TaskPriorityChangeEvent", + "TaskSignal", + "Text", + "TextDecoder", + "TextDecoderStream", + "TextEncoder", + "TextEncoderStream", + "TextEvent", + "TextFormat", + "TextFormatUpdateEvent", + "TextMetrics", + "TextTrack", + "TextTrackCue", + "TextTrackCueList", + "TextTrackList", + "TextUpdateEvent", + "TimeEvent", + "TimeRanges", + "ToggleEvent", + "Touch", + "TouchEvent", + "TouchList", + "TrackEvent", + "TransformStream", + "TransformStreamDefaultController", + "TransitionEvent", + "TreeWalker", + "TrustedHTML", + "TrustedScript", + "TrustedScriptURL", + "TrustedTypePolicy", + "TrustedTypePolicyFactory", + "TypeError", + "TypedObject", + "U2F", + "UIEvent", + "UNCACHED", + "UNIFORM", + "UNIFORM_ARRAY_STRIDE", + "UNIFORM_BLOCK_ACTIVE_UNIFORMS", + "UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES", + "UNIFORM_BLOCK_BINDING", + "UNIFORM_BLOCK_DATA_SIZE", + "UNIFORM_BLOCK_INDEX", + "UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER", + "UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER", + "UNIFORM_BUFFER", + "UNIFORM_BUFFER_BINDING", + "UNIFORM_BUFFER_OFFSET_ALIGNMENT", + "UNIFORM_BUFFER_SIZE", + "UNIFORM_BUFFER_START", + "UNIFORM_IS_ROW_MAJOR", + "UNIFORM_MATRIX_STRIDE", + "UNIFORM_OFFSET", + "UNIFORM_SIZE", + "UNIFORM_TYPE", + "UNKNOWN_ERR", + "UNKNOWN_RULE", + "UNMASKED_RENDERER_WEBGL", + "UNMASKED_VENDOR_WEBGL", + "UNORDERED_NODE_ITERATOR_TYPE", + "UNORDERED_NODE_SNAPSHOT_TYPE", + "UNPACK_ALIGNMENT", + "UNPACK_COLORSPACE_CONVERSION_WEBGL", + "UNPACK_FLIP_Y_WEBGL", + "UNPACK_IMAGE_HEIGHT", + "UNPACK_PREMULTIPLY_ALPHA_WEBGL", + "UNPACK_ROW_LENGTH", + "UNPACK_SKIP_IMAGES", + "UNPACK_SKIP_PIXELS", + "UNPACK_SKIP_ROWS", + "UNSCHEDULED_STATE", + "UNSENT", + "UNSIGNALED", + "UNSIGNED_BYTE", + "UNSIGNED_INT", + "UNSIGNED_INT_10F_11F_11F_REV", + "UNSIGNED_INT_24_8", + "UNSIGNED_INT_2_10_10_10_REV", + "UNSIGNED_INT_5_9_9_9_REV", + "UNSIGNED_INT_SAMPLER_2D", + "UNSIGNED_INT_SAMPLER_2D_ARRAY", + "UNSIGNED_INT_SAMPLER_3D", + "UNSIGNED_INT_SAMPLER_CUBE", + "UNSIGNED_INT_VEC2", + "UNSIGNED_INT_VEC3", + "UNSIGNED_INT_VEC4", + "UNSIGNED_NORMALIZED", + "UNSIGNED_SHORT", + "UNSIGNED_SHORT_4_4_4_4", + "UNSIGNED_SHORT_5_5_5_1", + "UNSIGNED_SHORT_5_6_5", + "UNSPECIFIED_EVENT_TYPE_ERR", + "UPDATEREADY", + "URIError", + "URL", + "URLPattern", + "URLSearchParams", + "URLUnencoded", + "URL_MISMATCH_ERR", + "USB", + "USBAlternateInterface", + "USBConfiguration", + "USBConnectionEvent", + "USBDevice", + "USBEndpoint", + "USBInTransferResult", + "USBInterface", + "USBIsochronousInTransferPacket", + "USBIsochronousInTransferResult", + "USBIsochronousOutTransferPacket", + "USBIsochronousOutTransferResult", + "USBOutTransferResult", + "UTC", + "Uint16Array", + "Uint32Array", + "Uint8Array", + "Uint8ClampedArray", + "UserActivation", + "UserMessageHandler", + "UserMessageHandlersNamespace", + "UserProximityEvent", + "VALIDATE_STATUS", + "VALIDATION_ERR", + "VARIABLES_RULE", + "VENDOR", + "VERSION", + "VERSION_CHANGE", + "VERSION_ERR", + "VERTEX", + "VERTEX_ARRAY_BINDING", + "VERTEX_ATTRIB_ARRAY_BUFFER_BINDING", + "VERTEX_ATTRIB_ARRAY_DIVISOR", + "VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE", + "VERTEX_ATTRIB_ARRAY_ENABLED", + "VERTEX_ATTRIB_ARRAY_INTEGER", + "VERTEX_ATTRIB_ARRAY_NORMALIZED", + "VERTEX_ATTRIB_ARRAY_POINTER", + "VERTEX_ATTRIB_ARRAY_SIZE", + "VERTEX_ATTRIB_ARRAY_STRIDE", + "VERTEX_ATTRIB_ARRAY_TYPE", + "VERTEX_SHADER", + "VERTICAL", + "VERTICAL_AXIS", + "VER_ERR", + "VIEWPORT", + "VIEWPORT_RULE", + "VRDisplay", + "VRDisplayCapabilities", + "VRDisplayEvent", + "VREyeParameters", + "VRFieldOfView", + "VRFrameData", + "VRPose", + "VRStageParameters", + "VTTCue", + "VTTRegion", + "ValidityState", + "VideoColorSpace", + "VideoDecoder", + "VideoEncoder", + "VideoFrame", + "VideoPlaybackQuality", + "VideoStreamTrack", + "ViewTimeline", + "ViewTransition", + "VirtualKeyboard", + "VirtualKeyboardGeometryChangeEvent", + "VisibilityStateEntry", + "VisualViewport", + "WAIT_FAILED", + "WEBKIT_FILTER_RULE", + "WEBKIT_KEYFRAMES_RULE", + "WEBKIT_KEYFRAME_RULE", + "WEBKIT_REGION_RULE", + "WGSLLanguageFeatures", + "WRITE", + "WRONG_DOCUMENT_ERR", + "WakeLock", + "WakeLockSentinel", + "WasmAnyRef", + "WaveShaperNode", + "WeakMap", + "WeakRef", + "WeakSet", + "WebAssembly", + "WebGL2RenderingContext", + "WebGLActiveInfo", + "WebGLBuffer", + "WebGLContextEvent", + "WebGLFramebuffer", + "WebGLProgram", + "WebGLQuery", + "WebGLRenderbuffer", + "WebGLRenderingContext", + "WebGLSampler", + "WebGLShader", + "WebGLShaderPrecisionFormat", + "WebGLSync", + "WebGLTexture", + "WebGLTransformFeedback", + "WebGLUniformLocation", + "WebGLVertexArray", + "WebGLVertexArrayObject", + "WebKitAnimationEvent", + "WebKitBlobBuilder", + "WebKitCSSFilterRule", + "WebKitCSSFilterValue", + "WebKitCSSKeyframeRule", + "WebKitCSSKeyframesRule", + "WebKitCSSMatrix", + "WebKitCSSRegionRule", + "WebKitCSSTransformValue", + "WebKitDataCue", + "WebKitGamepad", + "WebKitMediaKeyError", + "WebKitMediaKeyMessageEvent", + "WebKitMediaKeySession", + "WebKitMediaKeys", + "WebKitMediaSource", + "WebKitMutationObserver", + "WebKitNamespace", + "WebKitPlaybackTargetAvailabilityEvent", + "WebKitPoint", + "WebKitShadowRoot", + "WebKitSourceBuffer", + "WebKitSourceBufferList", + "WebKitTransitionEvent", + "WebSocket", + "WebSocketError", + "WebSocketStream", + "WebTransport", + "WebTransportBidirectionalStream", + "WebTransportDatagramDuplexStream", + "WebTransportError", + "WebTransportReceiveStream", + "WebTransportSendStream", + "WebkitAlignContent", + "WebkitAlignItems", + "WebkitAlignSelf", + "WebkitAnimation", + "WebkitAnimationDelay", + "WebkitAnimationDirection", + "WebkitAnimationDuration", + "WebkitAnimationFillMode", + "WebkitAnimationIterationCount", + "WebkitAnimationName", + "WebkitAnimationPlayState", + "WebkitAnimationTimingFunction", + "WebkitAppearance", + "WebkitBackfaceVisibility", + "WebkitBackgroundClip", + "WebkitBackgroundOrigin", + "WebkitBackgroundSize", + "WebkitBorderBottomLeftRadius", + "WebkitBorderBottomRightRadius", + "WebkitBorderImage", + "WebkitBorderRadius", + "WebkitBorderTopLeftRadius", + "WebkitBorderTopRightRadius", + "WebkitBoxAlign", + "WebkitBoxDirection", + "WebkitBoxFlex", + "WebkitBoxOrdinalGroup", + "WebkitBoxOrient", + "WebkitBoxPack", + "WebkitBoxShadow", + "WebkitBoxSizing", + "WebkitClipPath", + "WebkitFilter", + "WebkitFlex", + "WebkitFlexBasis", + "WebkitFlexDirection", + "WebkitFlexFlow", + "WebkitFlexGrow", + "WebkitFlexShrink", + "WebkitFlexWrap", + "WebkitJustifyContent", + "WebkitLineClamp", + "WebkitMask", + "WebkitMaskClip", + "WebkitMaskComposite", + "WebkitMaskImage", + "WebkitMaskOrigin", + "WebkitMaskPosition", + "WebkitMaskPositionX", + "WebkitMaskPositionY", + "WebkitMaskRepeat", + "WebkitMaskSize", + "WebkitOrder", + "WebkitPerspective", + "WebkitPerspectiveOrigin", + "WebkitTextFillColor", + "WebkitTextSecurity", + "WebkitTextSizeAdjust", + "WebkitTextStroke", + "WebkitTextStrokeColor", + "WebkitTextStrokeWidth", + "WebkitTransform", + "WebkitTransformOrigin", + "WebkitTransformStyle", + "WebkitTransition", + "WebkitTransitionDelay", + "WebkitTransitionDuration", + "WebkitTransitionProperty", + "WebkitTransitionTimingFunction", + "WebkitUserSelect", + "WheelEvent", + "Window", + "WindowControlsOverlay", + "WindowControlsOverlayGeometryChangeEvent", + "Worker", + "Worklet", + "WritableStream", + "WritableStreamDefaultController", + "WritableStreamDefaultWriter", + "XMLDocument", + "XMLHttpRequest", + "XMLHttpRequestEventTarget", + "XMLHttpRequestException", + "XMLHttpRequestProgressEvent", + "XMLHttpRequestUpload", + "XMLSerializer", + "XMLStylesheetProcessingInstruction", + "XPathEvaluator", + "XPathException", + "XPathExpression", + "XPathNSResolver", + "XPathResult", + "XRAnchor", + "XRAnchorSet", + "XRBoundedReferenceSpace", + "XRCPUDepthInformation", + "XRCamera", + "XRDOMOverlayState", + "XRDepthInformation", + "XRFrame", + "XRHitTestResult", + "XRHitTestSource", + "XRInputSource", + "XRInputSourceArray", + "XRInputSourceEvent", + "XRInputSourcesChangeEvent", + "XRLayer", + "XRLightEstimate", + "XRLightProbe", + "XRPose", + "XRRay", + "XRReferenceSpace", + "XRReferenceSpaceEvent", + "XRRenderState", + "XRRigidTransform", + "XRSession", + "XRSessionEvent", + "XRSpace", + "XRSystem", + "XRTransientInputHitTestResult", + "XRTransientInputHitTestSource", + "XRView", + "XRViewerPose", + "XRViewport", + "XRWebGLBinding", + "XRWebGLDepthInformation", + "XRWebGLLayer", + "XSLTProcessor", + "ZERO", + "_XD0M_", + "_YD0M_", + "__REACT_DEVTOOLS_GLOBAL_HOOK__", + "__brand", + "__defineGetter__", + "__defineSetter__", + "__lookupGetter__", + "__lookupSetter__", + "__opera", + "__proto__", + "_browserjsran", + "a", + "aLink", + "abbr", + "abort", + "aborted", + "abs", + "absolute", + "acceleration", + "accelerationIncludingGravity", + "accelerator", + "accent-color", + "accentColor", + "accept", + "acceptCharset", + "acceptNode", + "access", + "accessKey", + "accessKeyLabel", + "accuracy", + "acos", + "acosh", + "action", + "actionURL", + "actions", + "activated", + "activation", + "activationStart", + "active", + "activeCues", + "activeElement", + "activeSourceBuffers", + "activeSourceCount", + "activeTexture", + "activeVRDisplays", + "actualBoundingBoxAscent", + "actualBoundingBoxDescent", + "actualBoundingBoxLeft", + "actualBoundingBoxRight", + "adAuctionComponents", + "adAuctionHeaders", + "add", + "addAll", + "addBehavior", + "addCandidate", + "addColorStop", + "addCue", + "addElement", + "addEventListener", + "addFilter", + "addFromString", + "addFromUri", + "addIceCandidate", + "addImport", + "addListener", + "addModule", + "addNamed", + "addPageRule", + "addPath", + "addPointer", + "addRange", + "addRegion", + "addRule", + "addSearchEngine", + "addSourceBuffer", + "addStream", + "addTextTrack", + "addTrack", + "addTransceiver", + "addWakeLockListener", + "added", + "addedNodes", + "additionalName", + "additiveSymbols", + "addons", + "address", + "addressLine", + "addressModeU", + "addressModeV", + "addressModeW", + "adoptNode", + "adoptedCallback", + "adoptedStyleSheets", + "adr", + "advance", + "after", + "album", + "alert", + "algorithm", + "align", + "align-content", + "align-items", + "align-self", + "alignContent", + "alignItems", + "alignSelf", + "alignmentBaseline", + "alinkColor", + "all", + "allSettled", + "allocationSize", + "allow", + "allowFullscreen", + "allowPaymentRequest", + "allowedDirections", + "allowedFeatures", + "allowedToPlay", + "allowsFeature", + "alpha", + "alphaMode", + "alphaToCoverageEnabled", + "alphabeticBaseline", + "alt", + "altGraphKey", + "altHtml", + "altKey", + "altLeft", + "alternate", + "alternateSetting", + "alternates", + "altitude", + "altitudeAccuracy", + "altitudeAngle", + "amplitude", + "ancestorOrigins", + "anchor", + "anchorNode", + "anchorOffset", + "anchorSpace", + "anchors", + "and", + "angle", + "angularAcceleration", + "angularVelocity", + "animVal", + "animate", + "animated", + "animatedInstanceRoot", + "animatedNormalizedPathSegList", + "animatedPathSegList", + "animatedPoints", + "animation", + "animation-composition", + "animation-delay", + "animation-direction", + "animation-duration", + "animation-fill-mode", + "animation-iteration-count", + "animation-name", + "animation-play-state", + "animation-timing-function", + "animationComposition", + "animationDelay", + "animationDirection", + "animationDuration", + "animationFillMode", + "animationIterationCount", + "animationName", + "animationPlayState", + "animationStartTime", + "animationTimingFunction", + "animationsPaused", + "anniversary", + "antialias", + "anticipatedRemoval", + "any", + "app", + "appCodeName", + "appMinorVersion", + "appName", + "appNotifications", + "appVersion", + "appearance", + "append", + "appendBuffer", + "appendChild", + "appendData", + "appendItem", + "appendMedium", + "appendNamed", + "appendRule", + "appendStream", + "appendWindowEnd", + "appendWindowStart", + "applets", + "applicationCache", + "applicationServerKey", + "apply", + "applyConstraints", + "applyElement", + "arc", + "arcTo", + "architecture", + "archive", + "areas", + "arguments", + "ariaAtomic", + "ariaAutoComplete", + "ariaBrailleLabel", + "ariaBrailleRoleDescription", + "ariaBusy", + "ariaChecked", + "ariaColCount", + "ariaColIndex", + "ariaColIndexText", + "ariaColSpan", + "ariaCurrent", + "ariaDescription", + "ariaDisabled", + "ariaExpanded", + "ariaHasPopup", + "ariaHidden", + "ariaInvalid", + "ariaKeyShortcuts", + "ariaLabel", + "ariaLevel", + "ariaLive", + "ariaModal", + "ariaMultiLine", + "ariaMultiSelectable", + "ariaOrientation", + "ariaPlaceholder", + "ariaPosInSet", + "ariaPressed", + "ariaReadOnly", + "ariaRelevant", + "ariaRequired", + "ariaRoleDescription", + "ariaRowCount", + "ariaRowIndex", + "ariaRowIndexText", + "ariaRowSpan", + "ariaSelected", + "ariaSetSize", + "ariaSort", + "ariaValueMax", + "ariaValueMin", + "ariaValueNow", + "ariaValueText", + "arrayBuffer", + "arrayLayerCount", + "arrayStride", + "artist", + "artwork", + "as", + "asIntN", + "asUintN", + "ascentOverride", + "asin", + "asinh", + "aspect", + "aspect-ratio", + "aspectRatio", + "assert", + "assign", + "assignedElements", + "assignedNodes", + "assignedSlot", + "async", + "asyncIterator", + "at", + "atEnd", + "atan", + "atan2", + "atanh", + "atob", + "attachEvent", + "attachInternals", + "attachShader", + "attachShadow", + "attachedElements", + "attachments", + "attack", + "attestationObject", + "attrChange", + "attrName", + "attributeChangedCallback", + "attributeFilter", + "attributeName", + "attributeNamespace", + "attributeOldValue", + "attributeStyleMap", + "attributes", + "attribution", + "attributionSrc", + "audioBitrateMode", + "audioBitsPerSecond", + "audioTracks", + "audioWorklet", + "authenticatedSignedWrites", + "authenticatorAttachment", + "authenticatorData", + "autoIncrement", + "autobuffer", + "autocapitalize", + "autocomplete", + "autocorrect", + "autofocus", + "automationRate", + "autoplay", + "availHeight", + "availLeft", + "availTop", + "availWidth", + "availability", + "available", + "aversion", + "ax", + "axes", + "axis", + "ay", + "azimuth", + "azimuthAngle", + "b", + "back", + "backdrop-filter", + "backdropFilter", + "backends", + "backface-visibility", + "backfaceVisibility", + "background", + "background-attachment", + "background-blend-mode", + "background-clip", + "background-color", + "background-image", + "background-origin", + "background-position", + "background-position-x", + "background-position-y", + "background-repeat", + "background-size", + "backgroundAttachment", + "backgroundBlendMode", + "backgroundClip", + "backgroundColor", + "backgroundFetch", + "backgroundImage", + "backgroundOrigin", + "backgroundPosition", + "backgroundPositionX", + "backgroundPositionY", + "backgroundRepeat", + "backgroundSize", + "badInput", + "badge", + "balance", + "baseArrayLayer", + "baseFrequencyX", + "baseFrequencyY", + "baseLatency", + "baseLayer", + "baseMipLevel", + "baseNode", + "baseOffset", + "basePalette", + "baseURI", + "baseVal", + "baseline-source", + "baselineShift", + "baselineSource", + "battery", + "bday", + "before", + "beginComputePass", + "beginElement", + "beginElementAt", + "beginOcclusionQuery", + "beginPath", + "beginQuery", + "beginRenderPass", + "beginTransformFeedback", + "beginningOfPassWriteIndex", + "behavior", + "behaviorCookie", + "behaviorPart", + "behaviorUrns", + "beta", + "bezierCurveTo", + "bgColor", + "bgProperties", + "bias", + "big", + "bigint64", + "biguint64", + "binaryType", + "bind", + "bindAttribLocation", + "bindBuffer", + "bindBufferBase", + "bindBufferRange", + "bindFramebuffer", + "bindGroupLayouts", + "bindRenderbuffer", + "bindSampler", + "bindTexture", + "bindTransformFeedback", + "bindVertexArray", + "binding", + "bitness", + "blend", + "blendColor", + "blendEquation", + "blendEquationSeparate", + "blendFunc", + "blendFuncSeparate", + "blink", + "blitFramebuffer", + "blob", + "block-size", + "blockDirection", + "blockSize", + "blockedURI", + "blocking", + "blockingDuration", + "blue", + "bluetooth", + "blur", + "body", + "bodyUsed", + "bold", + "bookmarks", + "booleanValue", + "border", + "border-block", + "border-block-color", + "border-block-end", + "border-block-end-color", + "border-block-end-style", + "border-block-end-width", + "border-block-start", + "border-block-start-color", + "border-block-start-style", + "border-block-start-width", + "border-block-style", + "border-block-width", + "border-bottom", + "border-bottom-color", + "border-bottom-left-radius", + "border-bottom-right-radius", + "border-bottom-style", + "border-bottom-width", + "border-collapse", + "border-color", + "border-end-end-radius", + "border-end-start-radius", + "border-image", + "border-image-outset", + "border-image-repeat", + "border-image-slice", + "border-image-source", + "border-image-width", + "border-inline", + "border-inline-color", + "border-inline-end", + "border-inline-end-color", + "border-inline-end-style", + "border-inline-end-width", + "border-inline-start", + "border-inline-start-color", + "border-inline-start-style", + "border-inline-start-width", + "border-inline-style", + "border-inline-width", + "border-left", + "border-left-color", + "border-left-style", + "border-left-width", + "border-radius", + "border-right", + "border-right-color", + "border-right-style", + "border-right-width", + "border-spacing", + "border-start-end-radius", + "border-start-start-radius", + "border-style", + "border-top", + "border-top-color", + "border-top-left-radius", + "border-top-right-radius", + "border-top-style", + "border-top-width", + "border-width", + "borderBlock", + "borderBlockColor", + "borderBlockEnd", + "borderBlockEndColor", + "borderBlockEndStyle", + "borderBlockEndWidth", + "borderBlockStart", + "borderBlockStartColor", + "borderBlockStartStyle", + "borderBlockStartWidth", + "borderBlockStyle", + "borderBlockWidth", + "borderBottom", + "borderBottomColor", + "borderBottomLeftRadius", + "borderBottomRightRadius", + "borderBottomStyle", + "borderBottomWidth", + "borderBoxSize", + "borderCollapse", + "borderColor", + "borderColorDark", + "borderColorLight", + "borderEndEndRadius", + "borderEndStartRadius", + "borderImage", + "borderImageOutset", + "borderImageRepeat", + "borderImageSlice", + "borderImageSource", + "borderImageWidth", + "borderInline", + "borderInlineColor", + "borderInlineEnd", + "borderInlineEndColor", + "borderInlineEndStyle", + "borderInlineEndWidth", + "borderInlineStart", + "borderInlineStartColor", + "borderInlineStartStyle", + "borderInlineStartWidth", + "borderInlineStyle", + "borderInlineWidth", + "borderLeft", + "borderLeftColor", + "borderLeftStyle", + "borderLeftWidth", + "borderRadius", + "borderRight", + "borderRightColor", + "borderRightStyle", + "borderRightWidth", + "borderSpacing", + "borderStartEndRadius", + "borderStartStartRadius", + "borderStyle", + "borderTop", + "borderTopColor", + "borderTopLeftRadius", + "borderTopRightRadius", + "borderTopStyle", + "borderTopWidth", + "borderWidth", + "bottom", + "bottomMargin", + "bound", + "boundElements", + "boundingClientRect", + "boundingHeight", + "boundingLeft", + "boundingRect", + "boundingTop", + "boundingWidth", + "bounds", + "boundsGeometry", + "box-decoration-break", + "box-shadow", + "box-sizing", + "boxDecorationBreak", + "boxShadow", + "boxSizing", + "brand", + "brands", + "break-after", + "break-before", + "break-inside", + "breakAfter", + "breakBefore", + "breakInside", + "broadcast", + "browserLanguage", + "browsingTopics", + "btoa", + "bubbles", + "buffer", + "bufferData", + "bufferDepth", + "bufferSize", + "bufferSubData", + "buffered", + "bufferedAmount", + "bufferedAmountLowThreshold", + "buffers", + "buildID", + "buildNumber", + "button", + "buttonID", + "buttons", + "byobRequest", + "byteLength", + "byteOffset", + "bytesPerRow", + "bytesWritten", + "c", + "cache", + "caches", + "call", + "caller", + "camera", + "canBeFormatted", + "canBeMounted", + "canBeShared", + "canConstructInDedicatedWorker", + "canGoBack", + "canGoForward", + "canHaveChildren", + "canHaveHTML", + "canInsertDTMF", + "canIntercept", + "canLoadAdAuctionFencedFrame", + "canLoadOpaqueURL", + "canMakePayment", + "canParse", + "canPlayType", + "canPresent", + "canShare", + "canTransition", + "canTrickleIceCandidates", + "cancel", + "cancelAndHoldAtTime", + "cancelAnimationFrame", + "cancelBubble", + "cancelIdleCallback", + "cancelScheduledValues", + "cancelVideoFrameCallback", + "cancelWatchAvailability", + "cancelable", + "candidate", + "canonicalUUID", + "canvas", + "cap", + "capabilities", + "caption", + "caption-side", + "captionSide", + "capture", + "captureEvents", + "captureStackTrace", + "captureStream", + "caret-color", + "caretBidiLevel", + "caretColor", + "caretPositionFromPoint", + "caretRangeFromPoint", + "cast", + "catch", + "category", + "cbrt", + "cd", + "ceil", + "cellIndex", + "cellPadding", + "cellSpacing", + "cells", + "ch", + "chOff", + "chain", + "challenge", + "changeType", + "changed", + "changedTouches", + "channel", + "channelCount", + "channelCountMode", + "channelInterpretation", + "char", + "charAt", + "charCode", + "charCodeAt", + "charIndex", + "charLength", + "characterBounds", + "characterBoundsRangeStart", + "characterData", + "characterDataOldValue", + "characterSet", + "characteristic", + "charging", + "chargingTime", + "charset", + "check", + "checkDCE", + "checkEnclosure", + "checkFramebufferStatus", + "checkIntersection", + "checkValidity", + "checkVisibility", + "checked", + "childElementCount", + "childList", + "childNodes", + "children", + "chrome", + "ciphertext", + "cite", + "city", + "claimInterface", + "claimed", + "classList", + "className", + "classid", + "clear", + "clearAppBadge", + "clearAttributes", + "clearBuffer", + "clearBufferfi", + "clearBufferfv", + "clearBufferiv", + "clearBufferuiv", + "clearColor", + "clearData", + "clearDepth", + "clearHalt", + "clearImmediate", + "clearInterval", + "clearLiveSeekableRange", + "clearMarks", + "clearMaxGCPauseAccumulator", + "clearMeasures", + "clearOriginJoinedAdInterestGroups", + "clearParameters", + "clearRect", + "clearResourceTimings", + "clearShadow", + "clearStencil", + "clearTimeout", + "clearValue", + "clearWatch", + "click", + "clickCount", + "clientDataJSON", + "clientHeight", + "clientInformation", + "clientLeft", + "clientRect", + "clientRects", + "clientTop", + "clientWaitSync", + "clientWidth", + "clientX", + "clientY", + "clip", + "clip-path", + "clip-rule", + "clipBottom", + "clipLeft", + "clipPath", + "clipPathUnits", + "clipRight", + "clipRule", + "clipTop", + "clipboard", + "clipboardData", + "clonable", + "clone", + "cloneContents", + "cloneNode", + "cloneRange", + "close", + "closeCode", + "closePath", + "closed", + "closest", + "clz", + "clz32", + "cm", + "cmp", + "code", + "codeBase", + "codePointAt", + "codeType", + "codedHeight", + "codedRect", + "codedWidth", + "colSpan", + "collapse", + "collapseToEnd", + "collapseToStart", + "collapsed", + "collect", + "collections", + "colno", + "color", + "color-adjust", + "color-interpolation", + "color-interpolation-filters", + "color-scheme", + "colorAdjust", + "colorAttachments", + "colorDepth", + "colorFormats", + "colorInterpolation", + "colorInterpolationFilters", + "colorMask", + "colorScheme", + "colorSpace", + "colorType", + "cols", + "column-count", + "column-fill", + "column-gap", + "column-rule", + "column-rule-color", + "column-rule-style", + "column-rule-width", + "column-span", + "column-width", + "columnCount", + "columnFill", + "columnGap", + "columnNumber", + "columnRule", + "columnRuleColor", + "columnRuleStyle", + "columnRuleWidth", + "columnSpan", + "columnWidth", + "columns", + "command", + "commit", + "commitPreferences", + "commitStyles", + "commonAncestorContainer", + "compact", + "compare", + "compareBoundaryPoints", + "compareDocumentPosition", + "compareEndPoints", + "compareExchange", + "compareNode", + "comparePoint", + "compatMode", + "compatible", + "compile", + "compileShader", + "compileStreaming", + "complete", + "completed", + "component", + "componentFromPoint", + "composed", + "composedPath", + "composite", + "compositionEndOffset", + "compositionStartOffset", + "compressedTexImage2D", + "compressedTexImage3D", + "compressedTexSubImage2D", + "compressedTexSubImage3D", + "compute", + "computedStyleMap", + "concat", + "conditionText", + "coneInnerAngle", + "coneOuterAngle", + "coneOuterGain", + "config", + "configurable", + "configuration", + "configurationName", + "configurationValue", + "configurations", + "configure", + "confirm", + "confirmComposition", + "confirmSiteSpecificTrackingException", + "confirmWebWideTrackingException", + "congestionControl", + "connect", + "connectEnd", + "connectShark", + "connectStart", + "connected", + "connectedCallback", + "connection", + "connectionList", + "connectionSpeed", + "connectionState", + "connections", + "console", + "consolidate", + "constants", + "constraint", + "constrictionActive", + "construct", + "constructor", + "contactID", + "contain", + "contain-intrinsic-block-size", + "contain-intrinsic-height", + "contain-intrinsic-inline-size", + "contain-intrinsic-size", + "contain-intrinsic-width", + "containIntrinsicBlockSize", + "containIntrinsicHeight", + "containIntrinsicInlineSize", + "containIntrinsicSize", + "containIntrinsicWidth", + "container", + "container-name", + "container-type", + "containerId", + "containerName", + "containerQuery", + "containerSrc", + "containerType", + "contains", + "containsNode", + "content", + "content-visibility", + "contentBoxSize", + "contentDocument", + "contentEditable", + "contentHint", + "contentOverflow", + "contentRect", + "contentScriptType", + "contentStyleType", + "contentType", + "contentVisibility", + "contentWindow", + "context", + "contextMenu", + "contextmenu", + "continue", + "continuePrimaryKey", + "continuous", + "control", + "controlTransferIn", + "controlTransferOut", + "controller", + "controls", + "controlsList", + "convertPointFromNode", + "convertQuadFromNode", + "convertRectFromNode", + "convertToBlob", + "convertToSpecifiedUnits", + "cookie", + "cookieEnabled", + "cookieStore", + "cookies", + "coords", + "copyBufferSubData", + "copyBufferToBuffer", + "copyBufferToTexture", + "copyExternalImageToTexture", + "copyFromChannel", + "copyTexImage2D", + "copyTexSubImage2D", + "copyTexSubImage3D", + "copyTextureToBuffer", + "copyTextureToTexture", + "copyTo", + "copyToChannel", + "copyWithin", + "correspondingElement", + "correspondingUseElement", + "corruptedVideoFrames", + "cos", + "cosh", + "count", + "countReset", + "counter-increment", + "counter-reset", + "counter-set", + "counterIncrement", + "counterReset", + "counterSet", + "country", + "cpuClass", + "cpuSleepAllowed", + "cqb", + "cqh", + "cqi", + "cqmax", + "cqmin", + "cqw", + "create", + "createAnalyser", + "createAnchor", + "createAnswer", + "createAttribute", + "createAttributeNS", + "createAuctionNonce", + "createBidirectionalStream", + "createBindGroup", + "createBindGroupLayout", + "createBiquadFilter", + "createBuffer", + "createBufferSource", + "createCDATASection", + "createCSSStyleSheet", + "createCaption", + "createChannelMerger", + "createChannelSplitter", + "createCommandEncoder", + "createComment", + "createComputePipeline", + "createComputePipelineAsync", + "createConicGradient", + "createConstantSource", + "createContextualFragment", + "createControlRange", + "createConvolver", + "createDTMFSender", + "createDataChannel", + "createDelay", + "createDelayNode", + "createDocument", + "createDocumentFragment", + "createDocumentType", + "createDynamicsCompressor", + "createElement", + "createElementNS", + "createEncodedStreams", + "createEntityReference", + "createEvent", + "createEventObject", + "createExpression", + "createFramebuffer", + "createFunction", + "createGain", + "createGainNode", + "createHTML", + "createHTMLDocument", + "createIIRFilter", + "createImageBitmap", + "createImageData", + "createIndex", + "createJavaScriptNode", + "createLinearGradient", + "createMediaElementSource", + "createMediaKeys", + "createMediaStreamDestination", + "createMediaStreamSource", + "createMediaStreamTrackSource", + "createMutableFile", + "createNSResolver", + "createNodeIterator", + "createNotification", + "createObjectStore", + "createObjectURL", + "createOffer", + "createOscillator", + "createPanner", + "createPattern", + "createPeriodicWave", + "createPipelineLayout", + "createPolicy", + "createPopup", + "createProcessingInstruction", + "createProgram", + "createQuery", + "createQuerySet", + "createRadialGradient", + "createRange", + "createRangeCollection", + "createReader", + "createRenderBundleEncoder", + "createRenderPipeline", + "createRenderPipelineAsync", + "createRenderbuffer", + "createSVGAngle", + "createSVGLength", + "createSVGMatrix", + "createSVGNumber", + "createSVGPathSegArcAbs", + "createSVGPathSegArcRel", + "createSVGPathSegClosePath", + "createSVGPathSegCurvetoCubicAbs", + "createSVGPathSegCurvetoCubicRel", + "createSVGPathSegCurvetoCubicSmoothAbs", + "createSVGPathSegCurvetoCubicSmoothRel", + "createSVGPathSegCurvetoQuadraticAbs", + "createSVGPathSegCurvetoQuadraticRel", + "createSVGPathSegCurvetoQuadraticSmoothAbs", + "createSVGPathSegCurvetoQuadraticSmoothRel", + "createSVGPathSegLinetoAbs", + "createSVGPathSegLinetoHorizontalAbs", + "createSVGPathSegLinetoHorizontalRel", + "createSVGPathSegLinetoRel", + "createSVGPathSegLinetoVerticalAbs", + "createSVGPathSegLinetoVerticalRel", + "createSVGPathSegMovetoAbs", + "createSVGPathSegMovetoRel", + "createSVGPoint", + "createSVGRect", + "createSVGTransform", + "createSVGTransformFromMatrix", + "createSampler", + "createScript", + "createScriptProcessor", + "createScriptURL", + "createSession", + "createShader", + "createShaderModule", + "createShadowRoot", + "createStereoPanner", + "createStyleSheet", + "createTBody", + "createTFoot", + "createTHead", + "createTask", + "createTextNode", + "createTextRange", + "createTexture", + "createTouch", + "createTouchList", + "createTransformFeedback", + "createTreeWalker", + "createUnidirectionalStream", + "createVertexArray", + "createView", + "createWaveShaper", + "createWritable", + "creationTime", + "credentialless", + "credentials", + "criticalCHRestart", + "cropTo", + "crossOrigin", + "crossOriginIsolated", + "crypto", + "csi", + "csp", + "cssFloat", + "cssRules", + "cssText", + "cssValueType", + "ctrlKey", + "ctrlLeft", + "cues", + "cullFace", + "cullMode", + "currentDirection", + "currentEntry", + "currentLocalDescription", + "currentNode", + "currentPage", + "currentRect", + "currentRemoteDescription", + "currentScale", + "currentScreen", + "currentScript", + "currentSrc", + "currentState", + "currentStyle", + "currentTarget", + "currentTime", + "currentTranslate", + "currentView", + "cursor", + "curve", + "customElements", + "customError", + "cx", + "cy", + "d", + "data", + "dataFld", + "dataFormatAs", + "dataLoss", + "dataLossMessage", + "dataPageSize", + "dataSrc", + "dataTransfer", + "database", + "databases", + "datagrams", + "dataset", + "dateTime", + "db", + "debug", + "debuggerEnabled", + "declare", + "decode", + "decodeAudioData", + "decodeQueueSize", + "decodeURI", + "decodeURIComponent", + "decodedBodySize", + "decoding", + "decodingInfo", + "decrypt", + "default", + "defaultCharset", + "defaultChecked", + "defaultMuted", + "defaultPlaybackRate", + "defaultPolicy", + "defaultPrevented", + "defaultQueue", + "defaultRequest", + "defaultSelected", + "defaultStatus", + "defaultURL", + "defaultValue", + "defaultView", + "defaultstatus", + "defer", + "define", + "defineMagicFunction", + "defineMagicVariable", + "defineProperties", + "defineProperty", + "deg", + "delay", + "delayTime", + "delegatesFocus", + "delete", + "deleteBuffer", + "deleteCaption", + "deleteCell", + "deleteContents", + "deleteData", + "deleteDatabase", + "deleteFramebuffer", + "deleteFromDocument", + "deleteIndex", + "deleteMedium", + "deleteObjectStore", + "deleteProgram", + "deleteProperty", + "deleteQuery", + "deleteRenderbuffer", + "deleteRow", + "deleteRule", + "deleteSampler", + "deleteShader", + "deleteSync", + "deleteTFoot", + "deleteTHead", + "deleteTexture", + "deleteTransformFeedback", + "deleteVertexArray", + "deleted", + "deliverChangeRecords", + "deliveredFrames", + "delivery", + "deliveryInfo", + "deliveryStatus", + "deliveryTimestamp", + "deliveryType", + "delta", + "deltaMode", + "deltaX", + "deltaY", + "deltaZ", + "dependentLocality", + "deprecatedReplaceInURN", + "deprecatedRunAdAuctionEnforcesKAnonymity", + "deprecatedURNToURL", + "depthBias", + "depthBiasClamp", + "depthBiasSlopeScale", + "depthClearValue", + "depthCompare", + "depthDataFormat", + "depthFailOp", + "depthFar", + "depthFunc", + "depthLoadOp", + "depthMask", + "depthNear", + "depthOrArrayLayers", + "depthRange", + "depthReadOnly", + "depthStencil", + "depthStencilAttachment", + "depthStencilFormat", + "depthStoreOp", + "depthUsage", + "depthWriteEnabled", + "deref", + "deriveBits", + "deriveKey", + "descentOverride", + "description", + "deselectAll", + "designMode", + "desiredSize", + "destination", + "destinationURL", + "destroy", + "detach", + "detachEvent", + "detachShader", + "detached", + "detail", + "details", + "detect", + "detune", + "device", + "deviceClass", + "deviceId", + "deviceMemory", + "devicePixelContentBoxSize", + "devicePixelRatio", + "deviceProtocol", + "deviceSubclass", + "deviceVersionMajor", + "deviceVersionMinor", + "deviceVersionSubminor", + "deviceXDPI", + "deviceYDPI", + "didTimeout", + "difference", + "diffuseConstant", + "digest", + "dimension", + "dimensions", + "dir", + "dirName", + "direction", + "dirxml", + "disable", + "disablePictureInPicture", + "disableRemotePlayback", + "disableVertexAttribArray", + "disabled", + "discardedFrames", + "dischargingTime", + "disconnect", + "disconnectShark", + "disconnectedCallback", + "dispatchEvent", + "dispatchWorkgroups", + "dispatchWorkgroupsIndirect", + "display", + "displayHeight", + "displayId", + "displayName", + "displayWidth", + "disposition", + "distanceModel", + "div", + "divisor", + "djsapi", + "djsproxy", + "doImport", + "doNotTrack", + "doScroll", + "doctype", + "document", + "documentElement", + "documentMode", + "documentPictureInPicture", + "documentURI", + "dolphin", + "dolphinGameCenter", + "dolphininfo", + "dolphinmeta", + "domComplete", + "domContentLoadedEventEnd", + "domContentLoadedEventStart", + "domInteractive", + "domLoading", + "domOverlayState", + "domain", + "domainLookupEnd", + "domainLookupStart", + "dominant-baseline", + "dominantBaseline", + "done", + "dopplerFactor", + "dotAll", + "downDegrees", + "downlink", + "download", + "downloadRequest", + "downloadTotal", + "downloaded", + "dpcm", + "dpi", + "dppx", + "dragDrop", + "draggable", + "draw", + "drawArrays", + "drawArraysInstanced", + "drawArraysInstancedANGLE", + "drawBuffers", + "drawCustomFocusRing", + "drawElements", + "drawElementsInstanced", + "drawElementsInstancedANGLE", + "drawFocusIfNeeded", + "drawImage", + "drawImageFromRect", + "drawIndexed", + "drawIndexedIndirect", + "drawIndirect", + "drawRangeElements", + "drawSystemFocusRing", + "drawingBufferColorSpace", + "drawingBufferFormat", + "drawingBufferHeight", + "drawingBufferStorage", + "drawingBufferWidth", + "drop", + "dropEffect", + "droppedVideoFrames", + "dropzone", + "dstFactor", + "dtmf", + "dump", + "dumpProfile", + "duplicate", + "durability", + "duration", + "dvb", + "dvh", + "dvi", + "dvmax", + "dvmin", + "dvname", + "dvnum", + "dvw", + "dx", + "dy", + "dynsrc", + "e", + "edgeMode", + "editContext", + "effect", + "effectAllowed", + "effectiveDirective", + "effectiveType", + "elapsedTime", + "element", + "elementFromPoint", + "elementTiming", + "elements", + "elementsFromPoint", + "elevation", + "ellipse", + "em", + "emHeightAscent", + "emHeightDescent", + "email", + "embeds", + "emit", + "emma", + "empty", + "empty-cells", + "emptyCells", + "emptyHTML", + "emptyScript", + "emulatedPosition", + "enable", + "enableBackground", + "enableDelegations", + "enableStyleSheetsForSet", + "enableVertexAttribArray", + "enabled", + "enabledFeatures", + "enabledPlugin", + "encode", + "encodeInto", + "encodeQueueSize", + "encodeURI", + "encodeURIComponent", + "encodedBodySize", + "encoding", + "encodingInfo", + "encrypt", + "enctype", + "end", + "endContainer", + "endElement", + "endElementAt", + "endOcclusionQuery", + "endOfPassWriteIndex", + "endOfStream", + "endOffset", + "endQuery", + "endTime", + "endTransformFeedback", + "ended", + "endpoint", + "endpointNumber", + "endpoints", + "endsWith", + "enqueue", + "enterKeyHint", + "entities", + "entries", + "entry", + "entryPoint", + "entryType", + "enumerable", + "enumerate", + "enumerateDevices", + "enumerateEditable", + "environmentBlendMode", + "equals", + "error", + "errorCode", + "errorDetail", + "errorText", + "escape", + "estimate", + "eval", + "evaluate", + "event", + "eventCounts", + "eventPhase", + "every", + "ex", + "exception", + "exchange", + "exec", + "execCommand", + "execCommandShowHelp", + "execScript", + "executeBundles", + "executionStart", + "exitFullscreen", + "exitPictureInPicture", + "exitPointerLock", + "exitPresent", + "exp", + "expand", + "expandEntityReferences", + "expando", + "expansion", + "expectedImprovement", + "expiration", + "expirationTime", + "expires", + "expiryDate", + "explicitOriginalTarget", + "expm1", + "exponent", + "exponentialRampToValueAtTime", + "exportKey", + "exports", + "extend", + "extensions", + "extentNode", + "extentOffset", + "external", + "externalResourcesRequired", + "externalTexture", + "extractContents", + "extractable", + "eye", + "f", + "face", + "factoryReset", + "failOp", + "failureReason", + "fallback", + "family", + "familyName", + "farthestViewportElement", + "fastSeek", + "fatal", + "featureId", + "featurePolicy", + "featureSettings", + "features", + "fence", + "fenceSync", + "fetch", + "fetchPriority", + "fetchStart", + "fftSize", + "fgColor", + "fieldOfView", + "file", + "fileCreatedDate", + "fileHandle", + "fileModifiedDate", + "fileName", + "fileSize", + "fileUpdatedDate", + "filename", + "files", + "filesystem", + "fill", + "fill-opacity", + "fill-rule", + "fillLightMode", + "fillOpacity", + "fillRect", + "fillRule", + "fillStyle", + "fillText", + "filter", + "filterResX", + "filterResY", + "filterUnits", + "filters", + "finally", + "find", + "findIndex", + "findLast", + "findLastIndex", + "findRule", + "findText", + "finish", + "finished", + "fireEvent", + "firesTouchEvents", + "firstChild", + "firstElementChild", + "firstInterimResponseStart", + "firstPage", + "firstUIEventTimestamp", + "fixed", + "flags", + "flat", + "flatMap", + "flex", + "flex-basis", + "flex-direction", + "flex-flow", + "flex-grow", + "flex-shrink", + "flex-wrap", + "flexBasis", + "flexDirection", + "flexFlow", + "flexGrow", + "flexShrink", + "flexWrap", + "flipX", + "flipY", + "float", + "float32", + "float64", + "flood-color", + "flood-opacity", + "floodColor", + "floodOpacity", + "floor", + "flush", + "focus", + "focusNode", + "focusOffset", + "font", + "font-family", + "font-feature-settings", + "font-kerning", + "font-language-override", + "font-optical-sizing", + "font-palette", + "font-size", + "font-size-adjust", + "font-stretch", + "font-style", + "font-synthesis", + "font-synthesis-position", + "font-synthesis-small-caps", + "font-synthesis-style", + "font-synthesis-weight", + "font-variant", + "font-variant-alternates", + "font-variant-caps", + "font-variant-east-asian", + "font-variant-ligatures", + "font-variant-numeric", + "font-variant-position", + "font-variation-settings", + "font-weight", + "fontBoundingBoxAscent", + "fontBoundingBoxDescent", + "fontFamily", + "fontFeatureSettings", + "fontKerning", + "fontLanguageOverride", + "fontOpticalSizing", + "fontPalette", + "fontSize", + "fontSizeAdjust", + "fontSmoothingEnabled", + "fontStretch", + "fontStyle", + "fontSynthesis", + "fontSynthesisPosition", + "fontSynthesisSmallCaps", + "fontSynthesisStyle", + "fontSynthesisWeight", + "fontVariant", + "fontVariantAlternates", + "fontVariantCaps", + "fontVariantEastAsian", + "fontVariantLigatures", + "fontVariantNumeric", + "fontVariantPosition", + "fontVariationSettings", + "fontWeight", + "fontcolor", + "fontfaces", + "fonts", + "fontsize", + "for", + "forEach", + "force", + "forceFallbackAdapter", + "forceRedraw", + "forced-color-adjust", + "forcedColorAdjust", + "forcedStyleAndLayoutDuration", + "forget", + "form", + "formAction", + "formData", + "formEnctype", + "formMethod", + "formNoValidate", + "formTarget", + "format", + "formatToParts", + "forms", + "forward", + "forwardX", + "forwardY", + "forwardZ", + "foundation", + "fr", + "fragment", + "fragmentDirective", + "frame", + "frameBorder", + "frameCount", + "frameElement", + "frameSpacing", + "framebuffer", + "framebufferHeight", + "framebufferRenderbuffer", + "framebufferTexture2D", + "framebufferTextureLayer", + "framebufferWidth", + "frames", + "freeSpace", + "freeze", + "frequency", + "frequencyBinCount", + "from", + "fromAsync", + "fromCharCode", + "fromCodePoint", + "fromElement", + "fromEntries", + "fromFloat32Array", + "fromFloat64Array", + "fromMatrix", + "fromPoint", + "fromQuad", + "fromRect", + "frontFace", + "fround", + "fullName", + "fullPath", + "fullRange", + "fullScreen", + "fullVersionList", + "fullscreen", + "fullscreenElement", + "fullscreenEnabled", + "fx", + "fy", + "g", + "gain", + "gamepad", + "gamma", + "gap", + "gatheringState", + "gatt", + "genderIdentity", + "generateCertificate", + "generateKey", + "generateMipmap", + "generateRequest", + "geolocation", + "gestureObject", + "get", + "getActiveAttrib", + "getActiveUniform", + "getActiveUniformBlockName", + "getActiveUniformBlockParameter", + "getActiveUniforms", + "getAdjacentText", + "getAll", + "getAllKeys", + "getAllResponseHeaders", + "getAllowlistForFeature", + "getAnimations", + "getAsFile", + "getAsFileSystemHandle", + "getAsString", + "getAttachedShaders", + "getAttribLocation", + "getAttribute", + "getAttributeNS", + "getAttributeNames", + "getAttributeNode", + "getAttributeNodeNS", + "getAttributeType", + "getAudioTracks", + "getAuthenticatorData", + "getAutoplayPolicy", + "getAvailability", + "getBBox", + "getBattery", + "getBigInt64", + "getBigUint64", + "getBindGroupLayout", + "getBlob", + "getBookmark", + "getBoundingClientRect", + "getBounds", + "getBoxQuads", + "getBufferParameter", + "getBufferSubData", + "getByteFrequencyData", + "getByteTimeDomainData", + "getCSSCanvasContext", + "getCTM", + "getCameraImage", + "getCandidateWindowClientRect", + "getCanonicalLocales", + "getCapabilities", + "getCaptureHandle", + "getChannelData", + "getCharNumAtPosition", + "getCharacteristic", + "getCharacteristics", + "getClientExtensionResults", + "getClientRect", + "getClientRects", + "getCoalescedEvents", + "getCompilationInfo", + "getCompositionAlternatives", + "getComputedStyle", + "getComputedTextLength", + "getComputedTiming", + "getConfiguration", + "getConstraints", + "getContext", + "getContextAttributes", + "getContributingSources", + "getCounterValue", + "getCueAsHTML", + "getCueById", + "getCurrentPosition", + "getCurrentTexture", + "getCurrentTime", + "getData", + "getDatabaseNames", + "getDate", + "getDay", + "getDefaultComputedStyle", + "getDepthInMeters", + "getDepthInformation", + "getDescriptor", + "getDescriptors", + "getDestinationInsertionPoints", + "getDevices", + "getDirectory", + "getDirectoryHandle", + "getDisplayMedia", + "getDistributedNodes", + "getEditable", + "getElementById", + "getElementsByClassName", + "getElementsByName", + "getElementsByTagName", + "getElementsByTagNameNS", + "getEnclosureList", + "getEndPositionOfChar", + "getEntries", + "getEntriesByName", + "getEntriesByType", + "getError", + "getExtension", + "getExtentOfChar", + "getEyeParameters", + "getFeature", + "getFiberRoots", + "getFile", + "getFileHandle", + "getFiles", + "getFilesAndDirectories", + "getFingerprints", + "getFloat32", + "getFloat64", + "getFloatFrequencyData", + "getFloatTimeDomainData", + "getFloatValue", + "getFragDataLocation", + "getFrameData", + "getFramebufferAttachmentParameter", + "getFrequencyResponse", + "getFullYear", + "getGamepads", + "getHeaderExtensionsToNegotiate", + "getHighEntropyValues", + "getHitTestResults", + "getHitTestResultsForTransientInput", + "getHours", + "getIdentityAssertion", + "getIds", + "getImageData", + "getIndexedParameter", + "getInfo", + "getInnerHTML", + "getInstalledRelatedApps", + "getInt16", + "getInt32", + "getInt8", + "getInternalModuleRanges", + "getInternalformatParameter", + "getIntersectionList", + "getItem", + "getItems", + "getKey", + "getKeyframes", + "getLayers", + "getLayoutMap", + "getLightEstimate", + "getLineDash", + "getLocalCandidates", + "getLocalParameters", + "getLocalStreams", + "getManagedConfiguration", + "getMappedRange", + "getMarks", + "getMatchedCSSRules", + "getMaxGCPauseSinceClear", + "getMeasures", + "getMetadata", + "getMilliseconds", + "getMinutes", + "getModifierState", + "getMonth", + "getName", + "getNamedItem", + "getNamedItemNS", + "getNativeFramebufferScaleFactor", + "getNegotiatedHeaderExtensions", + "getNestedConfigs", + "getNotifications", + "getNotifier", + "getNumberOfChars", + "getOffsetReferenceSpace", + "getOutputTimestamp", + "getOverrideHistoryNavigationMode", + "getOverrideStyle", + "getOwnPropertyDescriptor", + "getOwnPropertyDescriptors", + "getOwnPropertyNames", + "getOwnPropertySymbols", + "getParameter", + "getParameters", + "getParent", + "getPathSegAtLength", + "getPhotoCapabilities", + "getPhotoSettings", + "getPointAtLength", + "getPorts", + "getPose", + "getPredictedEvents", + "getPreference", + "getPreferenceDefault", + "getPreferredCanvasFormat", + "getPresentationAttribute", + "getPreventDefault", + "getPrimaryService", + "getPrimaryServices", + "getProgramInfoLog", + "getProgramParameter", + "getPropertyCSSValue", + "getPropertyPriority", + "getPropertyShorthand", + "getPropertyType", + "getPropertyValue", + "getPrototypeOf", + "getPublicKey", + "getPublicKeyAlgorithm", + "getQuery", + "getQueryParameter", + "getRGBColorValue", + "getRandomValues", + "getRangeAt", + "getReader", + "getReceivers", + "getRectValue", + "getReflectionCubeMap", + "getRegistration", + "getRegistrations", + "getRemoteCandidates", + "getRemoteCertificates", + "getRemoteParameters", + "getRemoteStreams", + "getRenderbufferParameter", + "getResponseHeader", + "getRoot", + "getRootNode", + "getRotationOfChar", + "getSVGDocument", + "getSamplerParameter", + "getScreenCTM", + "getScreenDetails", + "getSeconds", + "getSelectedCandidatePair", + "getSelection", + "getSenders", + "getService", + "getSetCookie", + "getSettings", + "getShaderInfoLog", + "getShaderParameter", + "getShaderPrecisionFormat", + "getShaderSource", + "getSignals", + "getSimpleDuration", + "getSiteIcons", + "getSources", + "getSpeculativeParserUrls", + "getStartPositionOfChar", + "getStartTime", + "getState", + "getStats", + "getStatusForPolicy", + "getStorageUpdates", + "getStreamById", + "getStringValue", + "getSubStringLength", + "getSubscription", + "getSubscriptions", + "getSupportedConstraints", + "getSupportedExtensions", + "getSupportedFormats", + "getSyncParameter", + "getSynchronizationSources", + "getTags", + "getTargetRanges", + "getTexParameter", + "getTextFormats", + "getTime", + "getTimezoneOffset", + "getTiming", + "getTitlebarAreaRect", + "getTotalLength", + "getTrackById", + "getTracks", + "getTransceivers", + "getTransform", + "getTransformFeedbackVarying", + "getTransformToElement", + "getTransports", + "getType", + "getTypeMapping", + "getUTCDate", + "getUTCDay", + "getUTCFullYear", + "getUTCHours", + "getUTCMilliseconds", + "getUTCMinutes", + "getUTCMonth", + "getUTCSeconds", + "getUint16", + "getUint32", + "getUint8", + "getUniform", + "getUniformBlockIndex", + "getUniformIndices", + "getUniformLocation", + "getUserInfo", + "getUserMedia", + "getVRDisplays", + "getValues", + "getVarDate", + "getVariableValue", + "getVertexAttrib", + "getVertexAttribOffset", + "getVideoPlaybackQuality", + "getVideoTracks", + "getViewerPose", + "getViewport", + "getVoices", + "getWakeLockState", + "getWriter", + "getYear", + "givenName", + "global", + "globalAlpha", + "globalCompositeOperation", + "globalPrivacyControl", + "globalThis", + "glyphOrientationHorizontal", + "glyphOrientationVertical", + "glyphRef", + "go", + "gpu", + "grabFrame", + "grad", + "gradientTransform", + "gradientUnits", + "grammars", + "green", + "grid", + "grid-area", + "grid-auto-columns", + "grid-auto-flow", + "grid-auto-rows", + "grid-column", + "grid-column-end", + "grid-column-gap", + "grid-column-start", + "grid-gap", + "grid-row", + "grid-row-end", + "grid-row-gap", + "grid-row-start", + "grid-template", + "grid-template-areas", + "grid-template-columns", + "grid-template-rows", + "gridArea", + "gridAutoColumns", + "gridAutoFlow", + "gridAutoRows", + "gridColumn", + "gridColumnEnd", + "gridColumnGap", + "gridColumnStart", + "gridGap", + "gridRow", + "gridRowEnd", + "gridRowGap", + "gridRowStart", + "gridTemplate", + "gridTemplateAreas", + "gridTemplateColumns", + "gridTemplateRows", + "gripSpace", + "group", + "groupBy", + "groupCollapsed", + "groupEnd", + "groupId", + "groups", + "hadRecentInput", + "hand", + "handedness", + "hangingBaseline", + "hapticActuators", + "hardwareConcurrency", + "has", + "hasAttribute", + "hasAttributeNS", + "hasAttributes", + "hasBeenActive", + "hasChildNodes", + "hasComposition", + "hasDynamicOffset", + "hasEnrolledInstrument", + "hasExtension", + "hasExternalDisplay", + "hasFeature", + "hasFocus", + "hasIndices", + "hasInstance", + "hasLayout", + "hasOrientation", + "hasOwn", + "hasOwnProperty", + "hasPointerCapture", + "hasPosition", + "hasPrivateToken", + "hasReading", + "hasRedemptionRecord", + "hasRegExpGroups", + "hasStorageAccess", + "hasUAVisualTransition", + "hash", + "hashChange", + "head", + "headers", + "heading", + "height", + "hid", + "hidden", + "hide", + "hideFocus", + "hidePopover", + "high", + "highWaterMark", + "highlights", + "hint", + "hints", + "history", + "honorificPrefix", + "honorificSuffix", + "horizontalOverflow", + "host", + "hostCandidate", + "hostname", + "href", + "hrefTranslate", + "hreflang", + "hspace", + "html5TagCheckInerface", + "htmlFor", + "htmlText", + "httpEquiv", + "httpRequestStatusCode", + "hwTimestamp", + "hyphenate-character", + "hyphenateCharacter", + "hyphens", + "hypot", + "ic", + "iccId", + "iceConnectionState", + "iceGatheringState", + "iceTransport", + "icon", + "iconURL", + "id", + "identifier", + "identity", + "ideographicBaseline", + "idpLoginUrl", + "ignoreBOM", + "ignoreCase", + "ignoreDepthValues", + "image", + "image-orientation", + "image-rendering", + "imageHeight", + "imageOrientation", + "imageRendering", + "imageSizes", + "imageSmoothingEnabled", + "imageSmoothingQuality", + "imageSrcset", + "imageWidth", + "images", + "ime-mode", + "imeMode", + "implementation", + "importExternalTexture", + "importKey", + "importNode", + "importStylesheet", + "imports", + "impp", + "imul", + "in", + "in1", + "in2", + "inBandMetadataTrackDispatchType", + "inRange", + "includes", + "incomingBidirectionalStreams", + "incomingHighWaterMark", + "incomingMaxAge", + "incomingUnidirectionalStreams", + "incremental", + "indeterminate", + "index", + "indexNames", + "indexOf", + "indexedDB", + "indicate", + "indices", + "inert", + "inertiaDestinationX", + "inertiaDestinationY", + "info", + "inherits", + "init", + "initAnimationEvent", + "initBeforeLoadEvent", + "initClipboardEvent", + "initCloseEvent", + "initCommandEvent", + "initCompositionEvent", + "initCustomEvent", + "initData", + "initDataType", + "initDeviceMotionEvent", + "initDeviceOrientationEvent", + "initDragEvent", + "initErrorEvent", + "initEvent", + "initFocusEvent", + "initGestureEvent", + "initHashChangeEvent", + "initKeyEvent", + "initKeyboardEvent", + "initMSManipulationEvent", + "initMessageEvent", + "initMouseEvent", + "initMouseScrollEvent", + "initMouseWheelEvent", + "initMutationEvent", + "initNSMouseEvent", + "initOverflowEvent", + "initPageEvent", + "initPageTransitionEvent", + "initPointerEvent", + "initPopStateEvent", + "initProgressEvent", + "initScrollAreaEvent", + "initSimpleGestureEvent", + "initStorageEvent", + "initTextEvent", + "initTimeEvent", + "initTouchEvent", + "initTransitionEvent", + "initUIEvent", + "initWebKitAnimationEvent", + "initWebKitTransitionEvent", + "initWebKitWheelEvent", + "initWheelEvent", + "initialTime", + "initialValue", + "initialize", + "initiatorType", + "inject", + "ink", + "inline-size", + "inlineSize", + "inlineVerticalFieldOfView", + "inner", + "innerHTML", + "innerHeight", + "innerText", + "innerWidth", + "input", + "inputBuffer", + "inputEncoding", + "inputMethod", + "inputMode", + "inputSource", + "inputSources", + "inputType", + "inputs", + "insertAdjacentElement", + "insertAdjacentHTML", + "insertAdjacentText", + "insertBefore", + "insertCell", + "insertDTMF", + "insertData", + "insertDebugMarker", + "insertItemBefore", + "insertNode", + "insertRow", + "insertRule", + "inset", + "inset-block", + "inset-block-end", + "inset-block-start", + "inset-inline", + "inset-inline-end", + "inset-inline-start", + "insetBlock", + "insetBlockEnd", + "insetBlockStart", + "insetInline", + "insetInlineEnd", + "insetInlineStart", + "installing", + "instanceRoot", + "instantiate", + "instantiateStreaming", + "instruments", + "int16", + "int32", + "int8", + "integrity", + "interactionId", + "interactionMode", + "intercept", + "interfaceClass", + "interfaceName", + "interfaceNumber", + "interfaceProtocol", + "interfaceSubclass", + "interfaces", + "interimResults", + "internalSubset", + "interpretation", + "intersection", + "intersectionRatio", + "intersectionRect", + "intersectsNode", + "interval", + "invalidIteratorState", + "invalidateFramebuffer", + "invalidateSubFramebuffer", + "inverse", + "invertSelf", + "invoker", + "invokerType", + "is", + "is2D", + "isActive", + "isAlternate", + "isArray", + "isAutoSelected", + "isBingCurrentSearchDefault", + "isBuffer", + "isCandidateWindowVisible", + "isChar", + "isCollapsed", + "isComposing", + "isConcatSpreadable", + "isConditionalMediationAvailable", + "isConfigSupported", + "isConnected", + "isContentEditable", + "isContentHandlerRegistered", + "isContextLost", + "isDefaultNamespace", + "isDirectory", + "isDisabled", + "isDisjointFrom", + "isEnabled", + "isEqual", + "isEqualNode", + "isExtended", + "isExtensible", + "isExternalCTAP2SecurityKeySupported", + "isFallbackAdapter", + "isFile", + "isFinite", + "isFirstPersonObserver", + "isFramebuffer", + "isFrozen", + "isGenerator", + "isHTML", + "isHistoryNavigation", + "isId", + "isIdentity", + "isInjected", + "isInputPending", + "isInteger", + "isInternal", + "isIntersecting", + "isLockFree", + "isMap", + "isMultiLine", + "isNaN", + "isOpen", + "isPointInFill", + "isPointInPath", + "isPointInRange", + "isPointInStroke", + "isPrefAlternate", + "isPresenting", + "isPrimary", + "isProgram", + "isPropertyImplicit", + "isProtocolHandlerRegistered", + "isPrototypeOf", + "isQuery", + "isRawJSON", + "isRenderbuffer", + "isSafeInteger", + "isSameEntry", + "isSameNode", + "isSampler", + "isScript", + "isScriptURL", + "isSealed", + "isSecureContext", + "isSessionSupported", + "isShader", + "isSubsetOf", + "isSupersetOf", + "isSupported", + "isSync", + "isTextEdit", + "isTexture", + "isTransformFeedback", + "isTrusted", + "isTypeSupported", + "isUserVerifyingPlatformAuthenticatorAvailable", + "isVertexArray", + "isView", + "isVisible", + "isWellFormed", + "isochronousTransferIn", + "isochronousTransferOut", + "isolation", + "italics", + "item", + "itemId", + "itemProp", + "itemRef", + "itemScope", + "itemType", + "itemValue", + "items", + "iterateNext", + "iterationComposite", + "iterator", + "javaEnabled", + "jitterBufferTarget", + "jobTitle", + "join", + "joinAdInterestGroup", + "json", + "justify-content", + "justify-items", + "justify-self", + "justifyContent", + "justifyItems", + "justifySelf", + "k1", + "k2", + "k3", + "k4", + "kHz", + "keepalive", + "kernelMatrix", + "kernelUnitLengthX", + "kernelUnitLengthY", + "kerning", + "key", + "keyCode", + "keyFor", + "keyIdentifier", + "keyLightEnabled", + "keyLocation", + "keyPath", + "keyStatuses", + "keySystem", + "keyText", + "keyUsage", + "keyboard", + "keys", + "keytype", + "kind", + "knee", + "label", + "labels", + "lang", + "language", + "languages", + "largeArcFlag", + "lastChild", + "lastElementChild", + "lastEventId", + "lastIndex", + "lastIndexOf", + "lastInputTime", + "lastMatch", + "lastMessageSubject", + "lastMessageType", + "lastModified", + "lastModifiedDate", + "lastPage", + "lastParen", + "lastState", + "lastStyleSheetSet", + "latitude", + "launchQueue", + "layerName", + "layerX", + "layerY", + "layout", + "layoutFlow", + "layoutGrid", + "layoutGridChar", + "layoutGridLine", + "layoutGridMode", + "layoutGridType", + "lbound", + "leaveAdInterestGroup", + "left", + "leftContext", + "leftDegrees", + "leftMargin", + "leftProjectionMatrix", + "leftViewMatrix", + "length", + "lengthAdjust", + "lengthComputable", + "letter-spacing", + "letterSpacing", + "level", + "lh", + "lighting-color", + "lightingColor", + "limitingConeAngle", + "limits", + "line", + "line-break", + "line-height", + "lineAlign", + "lineBreak", + "lineCap", + "lineDashOffset", + "lineGapOverride", + "lineHeight", + "lineJoin", + "lineNum", + "lineNumber", + "linePos", + "lineTo", + "lineWidth", + "linearAcceleration", + "linearRampToValueAtTime", + "linearVelocity", + "lineno", + "lines", + "link", + "linkColor", + "linkProgram", + "links", + "list", + "list-style", + "list-style-image", + "list-style-position", + "list-style-type", + "listStyle", + "listStyleImage", + "listStylePosition", + "listStyleType", + "listener", + "listeners", + "load", + "loadEventEnd", + "loadEventStart", + "loadOp", + "loadTime", + "loadTimes", + "loaded", + "loading", + "localDescription", + "localName", + "localService", + "localStorage", + "locale", + "localeCompare", + "location", + "locationbar", + "lock", + "locked", + "lockedFile", + "locks", + "lodMaxClamp", + "lodMinClamp", + "log", + "log10", + "log1p", + "log2", + "logicalXDPI", + "logicalYDPI", + "login", + "loglevel", + "longDesc", + "longitude", + "lookupNamespaceURI", + "lookupPrefix", + "loop", + "loopEnd", + "loopStart", + "looping", + "lost", + "low", + "lower", + "lowerBound", + "lowerOpen", + "lowsrc", + "lvb", + "lvh", + "lvi", + "lvmax", + "lvmin", + "lvw", + "m11", + "m12", + "m13", + "m14", + "m21", + "m22", + "m23", + "m24", + "m31", + "m32", + "m33", + "m34", + "m41", + "m42", + "m43", + "m44", + "magFilter", + "makeXRCompatible", + "managed", + "manifest", + "manufacturer", + "manufacturerName", + "map", + "mapAsync", + "mapState", + "mappedAtCreation", + "mapping", + "margin", + "margin-block", + "margin-block-end", + "margin-block-start", + "margin-bottom", + "margin-inline", + "margin-inline-end", + "margin-inline-start", + "margin-left", + "margin-right", + "margin-top", + "marginBlock", + "marginBlockEnd", + "marginBlockStart", + "marginBottom", + "marginHeight", + "marginInline", + "marginInlineEnd", + "marginInlineStart", + "marginLeft", + "marginRight", + "marginTop", + "marginWidth", + "mark", + "marker", + "marker-end", + "marker-mid", + "marker-offset", + "marker-start", + "markerEnd", + "markerHeight", + "markerMid", + "markerOffset", + "markerStart", + "markerUnits", + "markerWidth", + "marks", + "mask", + "mask-clip", + "mask-composite", + "mask-image", + "mask-mode", + "mask-origin", + "mask-position", + "mask-position-x", + "mask-position-y", + "mask-repeat", + "mask-size", + "mask-type", + "maskClip", + "maskComposite", + "maskContentUnits", + "maskImage", + "maskMode", + "maskOrigin", + "maskPosition", + "maskPositionX", + "maskPositionY", + "maskRepeat", + "maskSize", + "maskType", + "maskUnits", + "match", + "matchAll", + "matchMedia", + "matchMedium", + "matches", + "math-depth", + "math-style", + "mathDepth", + "mathStyle", + "matrix", + "matrixTransform", + "max", + "max-block-size", + "max-height", + "max-inline-size", + "max-width", + "maxActions", + "maxAlternatives", + "maxAnisotropy", + "maxBindGroups", + "maxBindGroupsPlusVertexBuffers", + "maxBindingsPerBindGroup", + "maxBlockSize", + "maxBufferSize", + "maxByteLength", + "maxChannelCount", + "maxChannels", + "maxColorAttachmentBytesPerSample", + "maxColorAttachments", + "maxComputeInvocationsPerWorkgroup", + "maxComputeWorkgroupSizeX", + "maxComputeWorkgroupSizeY", + "maxComputeWorkgroupSizeZ", + "maxComputeWorkgroupStorageSize", + "maxComputeWorkgroupsPerDimension", + "maxConnectionsPerServer", + "maxDatagramSize", + "maxDecibels", + "maxDistance", + "maxDrawCount", + "maxDynamicStorageBuffersPerPipelineLayout", + "maxDynamicUniformBuffersPerPipelineLayout", + "maxHeight", + "maxInlineSize", + "maxInterStageShaderComponents", + "maxInterStageShaderVariables", + "maxLayers", + "maxLength", + "maxMessageSize", + "maxPacketLifeTime", + "maxRetransmits", + "maxSampledTexturesPerShaderStage", + "maxSamplersPerShaderStage", + "maxStorageBufferBindingSize", + "maxStorageBuffersPerShaderStage", + "maxStorageTexturesPerShaderStage", + "maxTextureArrayLayers", + "maxTextureDimension1D", + "maxTextureDimension2D", + "maxTextureDimension3D", + "maxTouchPoints", + "maxUniformBufferBindingSize", + "maxUniformBuffersPerShaderStage", + "maxValue", + "maxVertexAttributes", + "maxVertexBufferArrayStride", + "maxVertexBuffers", + "maxWidth", + "measure", + "measureText", + "media", + "mediaCapabilities", + "mediaDevices", + "mediaElement", + "mediaGroup", + "mediaKeys", + "mediaSession", + "mediaStream", + "mediaText", + "meetOrSlice", + "memory", + "menubar", + "mergeAttributes", + "message", + "messageClass", + "messageHandlers", + "messageType", + "messages", + "metaKey", + "metadata", + "method", + "methodDetails", + "methodName", + "mid", + "mimeType", + "mimeTypes", + "min", + "min-block-size", + "min-height", + "min-inline-size", + "min-width", + "minBindingSize", + "minBlockSize", + "minDecibels", + "minFilter", + "minHeight", + "minInlineSize", + "minLength", + "minStorageBufferOffsetAlignment", + "minUniformBufferOffsetAlignment", + "minValue", + "minWidth", + "mipLevel", + "mipLevelCount", + "mipmapFilter", + "miterLimit", + "mix-blend-mode", + "mixBlendMode", + "mm", + "mobile", + "mode", + "model", + "modify", + "module", + "mount", + "move", + "moveBy", + "moveEnd", + "moveFirst", + "moveFocusDown", + "moveFocusLeft", + "moveFocusRight", + "moveFocusUp", + "moveNext", + "moveRow", + "moveStart", + "moveTo", + "moveToBookmark", + "moveToElementText", + "moveToPoint", + "movementX", + "movementY", + "mozAdd", + "mozAnimationStartTime", + "mozAnon", + "mozApps", + "mozAudioCaptured", + "mozAudioChannelType", + "mozAutoplayEnabled", + "mozCancelAnimationFrame", + "mozCancelFullScreen", + "mozCancelRequestAnimationFrame", + "mozCaptureStream", + "mozCaptureStreamUntilEnded", + "mozClearDataAt", + "mozContact", + "mozContacts", + "mozCreateFileHandle", + "mozCurrentTransform", + "mozCurrentTransformInverse", + "mozCursor", + "mozDash", + "mozDashOffset", + "mozDecodedFrames", + "mozExitPointerLock", + "mozFillRule", + "mozFragmentEnd", + "mozFrameDelay", + "mozFullScreen", + "mozFullScreenElement", + "mozFullScreenEnabled", + "mozGetAll", + "mozGetAllKeys", + "mozGetAsFile", + "mozGetDataAt", + "mozGetMetadata", + "mozGetUserMedia", + "mozHasAudio", + "mozHasItem", + "mozHidden", + "mozImageSmoothingEnabled", + "mozIndexedDB", + "mozInnerScreenX", + "mozInnerScreenY", + "mozInputSource", + "mozIsTextField", + "mozItem", + "mozItemCount", + "mozItems", + "mozLength", + "mozLockOrientation", + "mozMatchesSelector", + "mozMovementX", + "mozMovementY", + "mozOpaque", + "mozOrientation", + "mozPaintCount", + "mozPaintedFrames", + "mozParsedFrames", + "mozPay", + "mozPointerLockElement", + "mozPresentedFrames", + "mozPreservesPitch", + "mozPressure", + "mozPrintCallback", + "mozRTCIceCandidate", + "mozRTCPeerConnection", + "mozRTCSessionDescription", + "mozRemove", + "mozRequestAnimationFrame", + "mozRequestFullScreen", + "mozRequestPointerLock", + "mozSetDataAt", + "mozSetImageElement", + "mozSourceNode", + "mozSrcObject", + "mozSystem", + "mozTCPSocket", + "mozTextStyle", + "mozTypesAt", + "mozUnlockOrientation", + "mozUserCancelled", + "mozVisibilityState", + "ms", + "msAnimation", + "msAnimationDelay", + "msAnimationDirection", + "msAnimationDuration", + "msAnimationFillMode", + "msAnimationIterationCount", + "msAnimationName", + "msAnimationPlayState", + "msAnimationStartTime", + "msAnimationTimingFunction", + "msBackfaceVisibility", + "msBlockProgression", + "msCSSOMElementFloatMetrics", + "msCaching", + "msCachingEnabled", + "msCancelRequestAnimationFrame", + "msCapsLockWarningOff", + "msClearImmediate", + "msClose", + "msContentZoomChaining", + "msContentZoomFactor", + "msContentZoomLimit", + "msContentZoomLimitMax", + "msContentZoomLimitMin", + "msContentZoomSnap", + "msContentZoomSnapPoints", + "msContentZoomSnapType", + "msContentZooming", + "msConvertURL", + "msCrypto", + "msDoNotTrack", + "msElementsFromPoint", + "msElementsFromRect", + "msExitFullscreen", + "msExtendedCode", + "msFillRule", + "msFirstPaint", + "msFlex", + "msFlexAlign", + "msFlexDirection", + "msFlexFlow", + "msFlexItemAlign", + "msFlexLinePack", + "msFlexNegative", + "msFlexOrder", + "msFlexPack", + "msFlexPositive", + "msFlexPreferredSize", + "msFlexWrap", + "msFlowFrom", + "msFlowInto", + "msFontFeatureSettings", + "msFullscreenElement", + "msFullscreenEnabled", + "msGetInputContext", + "msGetRegionContent", + "msGetUntransformedBounds", + "msGraphicsTrustStatus", + "msGridColumn", + "msGridColumnAlign", + "msGridColumnSpan", + "msGridColumns", + "msGridRow", + "msGridRowAlign", + "msGridRowSpan", + "msGridRows", + "msHidden", + "msHighContrastAdjust", + "msHyphenateLimitChars", + "msHyphenateLimitLines", + "msHyphenateLimitZone", + "msHyphens", + "msImageSmoothingEnabled", + "msImeAlign", + "msIndexedDB", + "msInterpolationMode", + "msIsStaticHTML", + "msKeySystem", + "msKeys", + "msLaunchUri", + "msLockOrientation", + "msManipulationViewsEnabled", + "msMatchMedia", + "msMatchesSelector", + "msMaxTouchPoints", + "msOrientation", + "msOverflowStyle", + "msPerspective", + "msPerspectiveOrigin", + "msPlayToDisabled", + "msPlayToPreferredSourceUri", + "msPlayToPrimary", + "msPointerEnabled", + "msRegionOverflow", + "msReleasePointerCapture", + "msRequestAnimationFrame", + "msRequestFullscreen", + "msSaveBlob", + "msSaveOrOpenBlob", + "msScrollChaining", + "msScrollLimit", + "msScrollLimitXMax", + "msScrollLimitXMin", + "msScrollLimitYMax", + "msScrollLimitYMin", + "msScrollRails", + "msScrollSnapPointsX", + "msScrollSnapPointsY", + "msScrollSnapType", + "msScrollSnapX", + "msScrollSnapY", + "msScrollTranslation", + "msSetImmediate", + "msSetMediaKeys", + "msSetPointerCapture", + "msTextCombineHorizontal", + "msTextSizeAdjust", + "msToBlob", + "msTouchAction", + "msTouchSelect", + "msTraceAsyncCallbackCompleted", + "msTraceAsyncCallbackStarting", + "msTraceAsyncOperationCompleted", + "msTraceAsyncOperationStarting", + "msTransform", + "msTransformOrigin", + "msTransformStyle", + "msTransition", + "msTransitionDelay", + "msTransitionDuration", + "msTransitionProperty", + "msTransitionTimingFunction", + "msUnlockOrientation", + "msUpdateAsyncCallbackRelation", + "msUserSelect", + "msVisibilityState", + "msWrapFlow", + "msWrapMargin", + "msWrapThrough", + "msWriteProfilerMark", + "msZoom", + "msZoomTo", + "mt", + "mul", + "multiEntry", + "multiSelectionObj", + "multiline", + "multiple", + "multiply", + "multiplySelf", + "multisample", + "multisampled", + "mutableFile", + "muted", + "n", + "name", + "nameList", + "nameProp", + "namedItem", + "namedRecordset", + "names", + "namespaceURI", + "namespaces", + "nativeMap", + "nativeObjectCreate", + "nativeSet", + "nativeWeakMap", + "naturalHeight", + "naturalWidth", + "navigate", + "navigation", + "navigationMode", + "navigationPreload", + "navigationStart", + "navigationType", + "navigator", + "near", + "nearestViewportElement", + "negative", + "negotiated", + "netscape", + "networkState", + "newScale", + "newState", + "newTranslate", + "newURL", + "newValue", + "newValueSpecifiedUnits", + "newVersion", + "newhome", + "next", + "nextElementSibling", + "nextHopProtocol", + "nextNode", + "nextPage", + "nextSibling", + "nickname", + "noHref", + "noModule", + "noResize", + "noShade", + "noValidate", + "noWrap", + "node", + "nodeName", + "nodeType", + "nodeValue", + "nonce", + "normDepthBufferFromNormView", + "normalize", + "normalizedPathSegList", + "notRestoredReasons", + "notationName", + "notations", + "note", + "noteGrainOn", + "noteOff", + "noteOn", + "notify", + "now", + "numOctaves", + "number", + "numberOfChannels", + "numberOfFrames", + "numberOfInputs", + "numberOfItems", + "numberOfOutputs", + "numberValue", + "oMatchesSelector", + "object", + "object-fit", + "object-position", + "objectFit", + "objectPosition", + "objectStore", + "objectStoreNames", + "objectType", + "observe", + "occlusionQuerySet", + "of", + "off", + "offscreenBuffering", + "offset", + "offset-anchor", + "offset-distance", + "offset-path", + "offset-position", + "offset-rotate", + "offsetAnchor", + "offsetDistance", + "offsetHeight", + "offsetLeft", + "offsetNode", + "offsetParent", + "offsetPath", + "offsetPosition", + "offsetRotate", + "offsetTop", + "offsetWidth", + "offsetX", + "offsetY", + "ok", + "oldState", + "oldURL", + "oldValue", + "oldVersion", + "olderShadowRoot", + "on", + "onCommitFiberRoot", + "onCommitFiberUnmount", + "onLine", + "onPostCommitFiberRoot", + "onSubmittedWorkDone", + "onabort", + "onabsolutedeviceorientation", + "onactivate", + "onactive", + "onaddsourcebuffer", + "onaddstream", + "onaddtrack", + "onafterprint", + "onafterscriptexecute", + "onafterupdate", + "onanimationcancel", + "onanimationend", + "onanimationiteration", + "onanimationstart", + "onappinstalled", + "onaudioend", + "onaudioprocess", + "onaudiostart", + "onautocomplete", + "onautocompleteerror", + "onauxclick", + "onbeforeactivate", + "onbeforecopy", + "onbeforecut", + "onbeforedeactivate", + "onbeforeeditfocus", + "onbeforeinput", + "onbeforeinstallprompt", + "onbeforematch", + "onbeforepaste", + "onbeforeprint", + "onbeforescriptexecute", + "onbeforetoggle", + "onbeforeunload", + "onbeforeupdate", + "onbeforexrselect", + "onbegin", + "onblocked", + "onblur", + "onbounce", + "onboundary", + "onbufferedamountlow", + "oncached", + "oncancel", + "oncandidatewindowhide", + "oncandidatewindowshow", + "oncandidatewindowupdate", + "oncanplay", + "oncanplaythrough", + "oncapturehandlechange", + "once", + "oncellchange", + "onchange", + "oncharacterboundsupdate", + "oncharacteristicvaluechanged", + "onchargingchange", + "onchargingtimechange", + "onchecking", + "onclick", + "onclose", + "onclosing", + "oncompassneedscalibration", + "oncomplete", + "oncompositionend", + "oncompositionstart", + "onconnect", + "onconnecting", + "onconnectionavailable", + "onconnectionstatechange", + "oncontentvisibilityautostatechange", + "oncontextlost", + "oncontextmenu", + "oncontextrestored", + "oncontrollerchange", + "oncontrolselect", + "oncopy", + "oncuechange", + "oncurrententrychange", + "oncurrentscreenchange", + "oncut", + "ondataavailable", + "ondatachannel", + "ondatasetchanged", + "ondatasetcomplete", + "ondblclick", + "ondeactivate", + "ondequeue", + "ondevicechange", + "ondevicelight", + "ondevicemotion", + "ondeviceorientation", + "ondeviceorientationabsolute", + "ondeviceproximity", + "ondischargingtimechange", + "ondisconnect", + "ondisplay", + "ondispose", + "ondownloading", + "ondrag", + "ondragend", + "ondragenter", + "ondragexit", + "ondragleave", + "ondragover", + "ondragstart", + "ondrop", + "ondurationchange", + "onemptied", + "onencrypted", + "onend", + "onended", + "onenter", + "onenterpictureinpicture", + "onerror", + "onerrorupdate", + "onexit", + "onfencedtreeclick", + "onfilterchange", + "onfinish", + "onfocus", + "onfocusin", + "onfocusout", + "onformdata", + "onfreeze", + "onfullscreenchange", + "onfullscreenerror", + "ongamepadconnected", + "ongamepaddisconnected", + "ongatheringstatechange", + "ongattserverdisconnected", + "ongeometrychange", + "ongesturechange", + "ongestureend", + "ongesturestart", + "ongotpointercapture", + "onhashchange", + "onhelp", + "onicecandidate", + "onicecandidateerror", + "oniceconnectionstatechange", + "onicegatheringstatechange", + "oninactive", + "oninput", + "oninputreport", + "oninputsourceschange", + "oninvalid", + "onkeydown", + "onkeypress", + "onkeystatuseschange", + "onkeyup", + "onlanguagechange", + "onlayoutcomplete", + "onleavepictureinpicture", + "onlevelchange", + "onload", + "onloadeddata", + "onloadedmetadata", + "onloadend", + "onloading", + "onloadingdone", + "onloadingerror", + "onloadstart", + "onlosecapture", + "onlostpointercapture", + "only", + "onmanagedconfigurationchange", + "onmark", + "onmessage", + "onmessageerror", + "onmidimessage", + "onmousedown", + "onmouseenter", + "onmouseleave", + "onmousemove", + "onmouseout", + "onmouseover", + "onmouseup", + "onmousewheel", + "onmove", + "onmoveend", + "onmovestart", + "onmozfullscreenchange", + "onmozfullscreenerror", + "onmozorientationchange", + "onmozpointerlockchange", + "onmozpointerlockerror", + "onmscontentzoom", + "onmsfullscreenchange", + "onmsfullscreenerror", + "onmsgesturechange", + "onmsgesturedoubletap", + "onmsgestureend", + "onmsgesturehold", + "onmsgesturestart", + "onmsgesturetap", + "onmsgotpointercapture", + "onmsinertiastart", + "onmslostpointercapture", + "onmsmanipulationstatechanged", + "onmsneedkey", + "onmsorientationchange", + "onmspointercancel", + "onmspointerdown", + "onmspointerenter", + "onmspointerhover", + "onmspointerleave", + "onmspointermove", + "onmspointerout", + "onmspointerover", + "onmspointerup", + "onmssitemodejumplistitemremoved", + "onmsthumbnailclick", + "onmute", + "onnavigate", + "onnavigateerror", + "onnavigatesuccess", + "onnegotiationneeded", + "onnomatch", + "onnoupdate", + "onobsolete", + "onoffline", + "ononline", + "onopen", + "onorientationchange", + "onpagechange", + "onpagehide", + "onpagereveal", + "onpageshow", + "onpageswap", + "onpaste", + "onpause", + "onpayerdetailchange", + "onpaymentmethodchange", + "onplay", + "onplaying", + "onpluginstreamstart", + "onpointercancel", + "onpointerdown", + "onpointerenter", + "onpointerleave", + "onpointerlockchange", + "onpointerlockerror", + "onpointermove", + "onpointerout", + "onpointerover", + "onpointerrawupdate", + "onpointerup", + "onpopstate", + "onprerenderingchange", + "onprioritychange", + "onprocessorerror", + "onprogress", + "onpropertychange", + "onratechange", + "onreading", + "onreadystatechange", + "onreflectionchange", + "onrejectionhandled", + "onrelease", + "onremove", + "onremovesourcebuffer", + "onremovestream", + "onremovetrack", + "onrepeat", + "onreset", + "onresize", + "onresizeend", + "onresizestart", + "onresourcetimingbufferfull", + "onresult", + "onresume", + "onrowenter", + "onrowexit", + "onrowsdelete", + "onrowsinserted", + "onscreenschange", + "onscroll", + "onscrollend", + "onsearch", + "onsecuritypolicyviolation", + "onseeked", + "onseeking", + "onselect", + "onselectedcandidatepairchange", + "onselectend", + "onselectionchange", + "onselectstart", + "onshippingaddresschange", + "onshippingoptionchange", + "onshow", + "onsignalingstatechange", + "onsinkchange", + "onslotchange", + "onsoundend", + "onsoundstart", + "onsourceclose", + "onsourceclosed", + "onsourceended", + "onsourceopen", + "onspeechend", + "onspeechstart", + "onsqueeze", + "onsqueezeend", + "onsqueezestart", + "onstalled", + "onstart", + "onstatechange", + "onstop", + "onstorage", + "onstoragecommit", + "onsubmit", + "onsuccess", + "onsuspend", + "onterminate", + "ontextformatupdate", + "ontextinput", + "ontextupdate", + "ontimeout", + "ontimeupdate", + "ontoggle", + "ontonechange", + "ontouchcancel", + "ontouchend", + "ontouchmove", + "ontouchstart", + "ontrack", + "ontransitioncancel", + "ontransitionend", + "ontransitionrun", + "ontransitionstart", + "onuncapturederror", + "onunhandledrejection", + "onunload", + "onunmute", + "onupdate", + "onupdateend", + "onupdatefound", + "onupdateready", + "onupdatestart", + "onupgradeneeded", + "onuserproximity", + "onversionchange", + "onvisibilitychange", + "onvoiceschanged", + "onvolumechange", + "onvrdisplayactivate", + "onvrdisplayconnect", + "onvrdisplaydeactivate", + "onvrdisplaydisconnect", + "onvrdisplaypresentchange", + "onwaiting", + "onwaitingforkey", + "onwarning", + "onwebkitanimationend", + "onwebkitanimationiteration", + "onwebkitanimationstart", + "onwebkitcurrentplaybacktargetiswirelesschanged", + "onwebkitfullscreenchange", + "onwebkitfullscreenerror", + "onwebkitkeyadded", + "onwebkitkeyerror", + "onwebkitkeymessage", + "onwebkitneedkey", + "onwebkitorientationchange", + "onwebkitplaybacktargetavailabilitychanged", + "onwebkitpointerlockchange", + "onwebkitpointerlockerror", + "onwebkitresourcetimingbufferfull", + "onwebkittransitionend", + "onwheel", + "onzoom", + "opacity", + "open", + "openCursor", + "openDatabase", + "openKeyCursor", + "opened", + "opener", + "opera", + "operation", + "operationType", + "operator", + "opr", + "optimum", + "options", + "or", + "order", + "orderX", + "orderY", + "ordered", + "org", + "organization", + "orient", + "orientAngle", + "orientType", + "orientation", + "orientationX", + "orientationY", + "orientationZ", + "origin", + "originAgentCluster", + "originalPolicy", + "originalTarget", + "orphans", + "oscpu", + "outerHTML", + "outerHeight", + "outerText", + "outerWidth", + "outgoingHighWaterMark", + "outgoingMaxAge", + "outline", + "outline-color", + "outline-offset", + "outline-style", + "outline-width", + "outlineColor", + "outlineOffset", + "outlineStyle", + "outlineWidth", + "outputBuffer", + "outputChannelCount", + "outputLatency", + "outputs", + "overflow", + "overflow-anchor", + "overflow-block", + "overflow-clip-margin", + "overflow-inline", + "overflow-wrap", + "overflow-x", + "overflow-y", + "overflowAnchor", + "overflowBlock", + "overflowClipMargin", + "overflowInline", + "overflowWrap", + "overflowX", + "overflowY", + "overlaysContent", + "overrideColors", + "overrideMimeType", + "oversample", + "overscroll-behavior", + "overscroll-behavior-block", + "overscroll-behavior-inline", + "overscroll-behavior-x", + "overscroll-behavior-y", + "overscrollBehavior", + "overscrollBehaviorBlock", + "overscrollBehaviorInline", + "overscrollBehaviorX", + "overscrollBehaviorY", + "ownKeys", + "ownerDocument", + "ownerElement", + "ownerNode", + "ownerRule", + "ownerSVGElement", + "owningElement", + "p1", + "p2", + "p3", + "p4", + "packetSize", + "packets", + "pad", + "padEnd", + "padStart", + "padding", + "padding-block", + "padding-block-end", + "padding-block-start", + "padding-bottom", + "padding-inline", + "padding-inline-end", + "padding-inline-start", + "padding-left", + "padding-right", + "padding-top", + "paddingBlock", + "paddingBlockEnd", + "paddingBlockStart", + "paddingBottom", + "paddingInline", + "paddingInlineEnd", + "paddingInlineStart", + "paddingLeft", + "paddingRight", + "paddingTop", + "page", + "page-break-after", + "page-break-before", + "page-break-inside", + "pageBreakAfter", + "pageBreakBefore", + "pageBreakInside", + "pageCount", + "pageLeft", + "pageTop", + "pageX", + "pageXOffset", + "pageY", + "pageYOffset", + "pages", + "paint-order", + "paintOrder", + "paintRequests", + "paintType", + "paintWorklet", + "palette", + "pan", + "panningModel", + "parameterData", + "parameters", + "parent", + "parentElement", + "parentNode", + "parentRule", + "parentStyleSheet", + "parentTextEdit", + "parentWindow", + "parse", + "parseAll", + "parseCreationOptionsFromJSON", + "parseFloat", + "parseFromString", + "parseHTMLUnsafe", + "parseInt", + "parseRequestOptionsFromJSON", + "part", + "participants", + "passOp", + "passive", + "password", + "pasteHTML", + "path", + "pathLength", + "pathSegList", + "pathSegType", + "pathSegTypeAsLetter", + "pathname", + "pattern", + "patternContentUnits", + "patternMismatch", + "patternTransform", + "patternUnits", + "pause", + "pauseAnimations", + "pauseDuration", + "pauseOnExit", + "pauseProfilers", + "pauseTransformFeedback", + "paused", + "payerEmail", + "payerName", + "payerPhone", + "paymentManager", + "pc", + "pdfViewerEnabled", + "peerIdentity", + "pending", + "pendingLocalDescription", + "pendingRemoteDescription", + "percent", + "performance", + "periodicSync", + "permission", + "permissionState", + "permissions", + "persist", + "persisted", + "personalbar", + "perspective", + "perspective-origin", + "perspectiveOrigin", + "phone", + "phoneticFamilyName", + "phoneticGivenName", + "photo", + "pictureInPictureElement", + "pictureInPictureEnabled", + "pictureInPictureWindow", + "ping", + "pipeThrough", + "pipeTo", + "pitch", + "pixelBottom", + "pixelDepth", + "pixelHeight", + "pixelLeft", + "pixelRight", + "pixelStorei", + "pixelTop", + "pixelUnitToMillimeterX", + "pixelUnitToMillimeterY", + "pixelWidth", + "place-content", + "place-items", + "place-self", + "placeContent", + "placeItems", + "placeSelf", + "placeholder", + "platform", + "platformVersion", + "platforms", + "play", + "playEffect", + "playState", + "playbackRate", + "playbackState", + "playbackTime", + "played", + "playoutDelayHint", + "playsInline", + "plugins", + "pluginspage", + "pname", + "pointer-events", + "pointerBeforeReferenceNode", + "pointerEnabled", + "pointerEvents", + "pointerId", + "pointerLockElement", + "pointerType", + "points", + "pointsAtX", + "pointsAtY", + "pointsAtZ", + "polygonOffset", + "pop", + "popDebugGroup", + "popErrorScope", + "popover", + "popoverTargetAction", + "popoverTargetElement", + "populateMatrix", + "popupWindowFeatures", + "popupWindowName", + "popupWindowURI", + "port", + "port1", + "port2", + "ports", + "posBottom", + "posHeight", + "posLeft", + "posRight", + "posTop", + "posWidth", + "pose", + "position", + "positionAlign", + "positionX", + "positionY", + "positionZ", + "postError", + "postMessage", + "postTask", + "postalCode", + "poster", + "postscriptName", + "pow", + "powerEfficient", + "powerOff", + "powerPreference", + "preMultiplySelf", + "precision", + "preferredReflectionFormat", + "preferredStyleSheetSet", + "preferredStylesheetSet", + "prefix", + "preload", + "premultipliedAlpha", + "prepend", + "prerendering", + "presentation", + "presentationArea", + "preserveAlpha", + "preserveAspectRatio", + "preserveAspectRatioString", + "preservesPitch", + "pressed", + "pressure", + "prevValue", + "preventDefault", + "preventExtensions", + "preventSilentAccess", + "previousElementSibling", + "previousNode", + "previousPage", + "previousPriority", + "previousRect", + "previousScale", + "previousSibling", + "previousTranslate", + "primaries", + "primaryKey", + "primaryLightDirection", + "primaryLightIntensity", + "primitive", + "primitiveType", + "primitiveUnits", + "principals", + "print", + "print-color-adjust", + "printColorAdjust", + "priority", + "privateKey", + "privateToken", + "probablySupportsContext", + "probeSpace", + "process", + "processIceMessage", + "processingEnd", + "processingStart", + "processorOptions", + "product", + "productId", + "productName", + "productSub", + "profile", + "profileEnd", + "profiles", + "projectionMatrix", + "promise", + "prompt", + "properties", + "propertyIsEnumerable", + "propertyName", + "protocol", + "protocolLong", + "prototype", + "provider", + "pseudoClass", + "pseudoElement", + "pt", + "publicId", + "publicKey", + "published", + "pulse", + "push", + "pushDebugGroup", + "pushErrorScope", + "pushManager", + "pushNotification", + "pushState", + "put", + "putImageData", + "px", + "quadraticCurveTo", + "qualifier", + "quaternion", + "query", + "queryCommandEnabled", + "queryCommandIndeterm", + "queryCommandState", + "queryCommandSupported", + "queryCommandText", + "queryCommandValue", + "queryLocalFonts", + "queryPermission", + "querySelector", + "querySelectorAll", + "querySet", + "queue", + "queueMicrotask", + "quote", + "quotes", + "r", + "r1", + "r2", + "race", + "rad", + "radiogroup", + "radiusX", + "radiusY", + "random", + "randomUUID", + "range", + "rangeCount", + "rangeEnd", + "rangeMax", + "rangeMin", + "rangeOffset", + "rangeOverflow", + "rangeParent", + "rangeStart", + "rangeUnderflow", + "rate", + "ratio", + "raw", + "rawId", + "rawJSON", + "rawValueToMeters", + "rcap", + "rch", + "read", + "readAsArrayBuffer", + "readAsBinaryString", + "readAsBlob", + "readAsDataURL", + "readAsText", + "readBuffer", + "readEntries", + "readOnly", + "readPixels", + "readReportRequested", + "readText", + "readValue", + "readable", + "ready", + "readyState", + "reason", + "reasons", + "reboot", + "receiveFeatureReport", + "receivedAlert", + "receiver", + "receivers", + "recipient", + "recommendedViewportScale", + "reconnect", + "recordNumber", + "recordsAvailable", + "recordset", + "rect", + "red", + "redEyeReduction", + "redirect", + "redirectCount", + "redirectEnd", + "redirectStart", + "redirected", + "reduce", + "reduceRight", + "reduction", + "refDistance", + "refX", + "refY", + "referenceNode", + "referenceSpace", + "referrer", + "referrerPolicy", + "refresh", + "region", + "regionAnchorX", + "regionAnchorY", + "regionId", + "regions", + "register", + "registerContentHandler", + "registerElement", + "registerInternalModuleStart", + "registerInternalModuleStop", + "registerProperty", + "registerProtocolHandler", + "reject", + "rel", + "relList", + "relatedAddress", + "relatedNode", + "relatedPort", + "relatedTarget", + "relayProtocol", + "release", + "releaseCapture", + "releaseEvents", + "releaseInterface", + "releaseLock", + "releasePointerCapture", + "releaseShaderCompiler", + "released", + "reliability", + "reliable", + "reliableWrite", + "reload", + "rem", + "remainingSpace", + "remote", + "remoteDescription", + "remove", + "removeAllRanges", + "removeAttribute", + "removeAttributeNS", + "removeAttributeNode", + "removeBehavior", + "removeChild", + "removeCue", + "removeEntry", + "removeEventListener", + "removeFilter", + "removeImport", + "removeItem", + "removeListener", + "removeNamedItem", + "removeNamedItemNS", + "removeNode", + "removeParameter", + "removeProperty", + "removeRange", + "removeRegion", + "removeRule", + "removeSiteSpecificTrackingException", + "removeSourceBuffer", + "removeStream", + "removeTrack", + "removeVariable", + "removeWakeLockListener", + "removeWebWideTrackingException", + "removed", + "removedNodes", + "renderBlockingStatus", + "renderHeight", + "renderStart", + "renderState", + "renderTime", + "renderWidth", + "renderbufferStorage", + "renderbufferStorageMultisample", + "renderedBuffer", + "rendererInterfaces", + "renderers", + "renderingMode", + "renotify", + "repeat", + "repetitionCount", + "replace", + "replaceAdjacentText", + "replaceAll", + "replaceChild", + "replaceChildren", + "replaceData", + "replaceId", + "replaceItem", + "replaceNode", + "replaceState", + "replaceSync", + "replaceTrack", + "replaceWholeText", + "replaceWith", + "reportError", + "reportEvent", + "reportId", + "reportValidity", + "request", + "requestAdapter", + "requestAdapterInfo", + "requestAnimationFrame", + "requestAutocomplete", + "requestData", + "requestDevice", + "requestFrame", + "requestFullscreen", + "requestHitTestSource", + "requestHitTestSourceForTransientInput", + "requestId", + "requestIdleCallback", + "requestLightProbe", + "requestMIDIAccess", + "requestMediaKeySystemAccess", + "requestPermission", + "requestPictureInPicture", + "requestPointerLock", + "requestPort", + "requestPresent", + "requestPresenter", + "requestReferenceSpace", + "requestSession", + "requestStart", + "requestStorageAccess", + "requestStorageAccessFor", + "requestSubmit", + "requestVideoFrameCallback", + "requestViewportScale", + "requestWindow", + "requestingWindow", + "requireInteraction", + "required", + "requiredExtensions", + "requiredFeatures", + "requiredLimits", + "reset", + "resetPose", + "resetTransform", + "resizable", + "resize", + "resizeBy", + "resizeTo", + "resolve", + "resolveQuerySet", + "resolveTarget", + "resource", + "respond", + "respondWithNewView", + "response", + "responseBody", + "responseEnd", + "responseReady", + "responseStart", + "responseStatus", + "responseText", + "responseType", + "responseURL", + "responseXML", + "restartIce", + "restore", + "result", + "resultIndex", + "resultType", + "results", + "resume", + "resumeProfilers", + "resumeTransformFeedback", + "retry", + "returnValue", + "rev", + "reverse", + "reversed", + "revocable", + "revokeObjectURL", + "rex", + "rgbColor", + "ric", + "right", + "rightContext", + "rightDegrees", + "rightMargin", + "rightProjectionMatrix", + "rightViewMatrix", + "rlh", + "role", + "rolloffFactor", + "root", + "rootBounds", + "rootElement", + "rootMargin", + "rotate", + "rotateAxisAngle", + "rotateAxisAngleSelf", + "rotateFromVector", + "rotateFromVectorSelf", + "rotateSelf", + "rotation", + "rotationAngle", + "rotationRate", + "round", + "roundRect", + "row-gap", + "rowGap", + "rowIndex", + "rowSpan", + "rows", + "rowsPerImage", + "rtcpTransport", + "rtt", + "ruby-align", + "ruby-position", + "rubyAlign", + "rubyOverhang", + "rubyPosition", + "rules", + "run", + "runAdAuction", + "runtime", + "runtimeStyle", + "rx", + "ry", + "s", + "safari", + "sameDocument", + "sample", + "sampleCount", + "sampleCoverage", + "sampleInterval", + "sampleRate", + "sampleType", + "sampler", + "samplerParameterf", + "samplerParameteri", + "sandbox", + "save", + "saveData", + "scale", + "scale3d", + "scale3dSelf", + "scaleNonUniform", + "scaleNonUniformSelf", + "scaleSelf", + "scheduler", + "scheduling", + "scheme", + "scissor", + "scope", + "scopeName", + "scoped", + "screen", + "screenBrightness", + "screenEnabled", + "screenLeft", + "screenPixelToMillimeterX", + "screenPixelToMillimeterY", + "screenState", + "screenTop", + "screenX", + "screenY", + "screens", + "scriptURL", + "scripts", + "scroll", + "scroll-behavior", + "scroll-margin", + "scroll-margin-block", + "scroll-margin-block-end", + "scroll-margin-block-start", + "scroll-margin-bottom", + "scroll-margin-inline", + "scroll-margin-inline-end", + "scroll-margin-inline-start", + "scroll-margin-left", + "scroll-margin-right", + "scroll-margin-top", + "scroll-padding", + "scroll-padding-block", + "scroll-padding-block-end", + "scroll-padding-block-start", + "scroll-padding-bottom", + "scroll-padding-inline", + "scroll-padding-inline-end", + "scroll-padding-inline-start", + "scroll-padding-left", + "scroll-padding-right", + "scroll-padding-top", + "scroll-snap-align", + "scroll-snap-stop", + "scroll-snap-type", + "scrollAmount", + "scrollBehavior", + "scrollBy", + "scrollByLines", + "scrollByPages", + "scrollDelay", + "scrollHeight", + "scrollIntoView", + "scrollIntoViewIfNeeded", + "scrollLeft", + "scrollLeftMax", + "scrollMargin", + "scrollMarginBlock", + "scrollMarginBlockEnd", + "scrollMarginBlockStart", + "scrollMarginBottom", + "scrollMarginInline", + "scrollMarginInlineEnd", + "scrollMarginInlineStart", + "scrollMarginLeft", + "scrollMarginRight", + "scrollMarginTop", + "scrollMaxX", + "scrollMaxY", + "scrollPadding", + "scrollPaddingBlock", + "scrollPaddingBlockEnd", + "scrollPaddingBlockStart", + "scrollPaddingBottom", + "scrollPaddingInline", + "scrollPaddingInlineEnd", + "scrollPaddingInlineStart", + "scrollPaddingLeft", + "scrollPaddingRight", + "scrollPaddingTop", + "scrollRestoration", + "scrollSnapAlign", + "scrollSnapStop", + "scrollSnapType", + "scrollTo", + "scrollTop", + "scrollTopMax", + "scrollWidth", + "scrollX", + "scrollY", + "scrollbar-color", + "scrollbar-gutter", + "scrollbar-width", + "scrollbar3dLightColor", + "scrollbarArrowColor", + "scrollbarBaseColor", + "scrollbarColor", + "scrollbarDarkShadowColor", + "scrollbarFaceColor", + "scrollbarGutter", + "scrollbarHighlightColor", + "scrollbarShadowColor", + "scrollbarTrackColor", + "scrollbarWidth", + "scrollbars", + "scrolling", + "scrollingElement", + "sctp", + "sctpCauseCode", + "sdp", + "sdpLineNumber", + "sdpMLineIndex", + "sdpMid", + "seal", + "search", + "searchBox", + "searchBoxJavaBridge_", + "searchParams", + "sectionRowIndex", + "secureConnectionStart", + "security", + "seed", + "seek", + "seekToNextFrame", + "seekable", + "seeking", + "select", + "selectAllChildren", + "selectAlternateInterface", + "selectAudioOutput", + "selectConfiguration", + "selectNode", + "selectNodeContents", + "selectNodes", + "selectSingleNode", + "selectSubString", + "selectURL", + "selected", + "selectedIndex", + "selectedOptions", + "selectedStyleSheetSet", + "selectedStylesheetSet", + "selectedTrack", + "selection", + "selectionDirection", + "selectionEnd", + "selectionStart", + "selector", + "selectorText", + "self", + "send", + "sendAsBinary", + "sendBeacon", + "sendFeatureReport", + "sendOrder", + "sendReport", + "sender", + "sentAlert", + "sentTimestamp", + "separator", + "serial", + "serialNumber", + "serializeToString", + "serverTiming", + "service", + "serviceWorker", + "session", + "sessionId", + "sessionStorage", + "set", + "setActionHandler", + "setActive", + "setAlpha", + "setAppBadge", + "setAttribute", + "setAttributeNS", + "setAttributeNode", + "setAttributeNodeNS", + "setAttributionReporting", + "setBaseAndExtent", + "setBigInt64", + "setBigUint64", + "setBindGroup", + "setBingCurrentSearchDefault", + "setBlendConstant", + "setCameraActive", + "setCapture", + "setCaptureHandleConfig", + "setCodecPreferences", + "setColor", + "setCompositeOperation", + "setConfiguration", + "setConsumer", + "setCurrentTime", + "setCustomValidity", + "setData", + "setDate", + "setDragImage", + "setEnd", + "setEndAfter", + "setEndBefore", + "setEndPoint", + "setExpires", + "setFillColor", + "setFilterRes", + "setFloat32", + "setFloat64", + "setFloatValue", + "setFocusBehavior", + "setFormValue", + "setFullYear", + "setHTMLUnsafe", + "setHeaderExtensionsToNegotiate", + "setHeaderValue", + "setHours", + "setIdentityProvider", + "setImmediate", + "setIndexBuffer", + "setInt16", + "setInt32", + "setInt8", + "setInterval", + "setItem", + "setKeyframes", + "setLineCap", + "setLineDash", + "setLineJoin", + "setLineWidth", + "setLiveSeekableRange", + "setLocalDescription", + "setMatrix", + "setMatrixValue", + "setMediaKeys", + "setMicrophoneActive", + "setMilliseconds", + "setMinutes", + "setMiterLimit", + "setMonth", + "setNamedItem", + "setNamedItemNS", + "setNonUserCodeExceptions", + "setOrientToAngle", + "setOrientToAuto", + "setOrientation", + "setOverrideHistoryNavigationMode", + "setPaint", + "setParameter", + "setParameters", + "setPeriodicWave", + "setPipeline", + "setPointerCapture", + "setPosition", + "setPositionState", + "setPreference", + "setPriority", + "setPrivateToken", + "setProperty", + "setPrototypeOf", + "setRGBColor", + "setRGBColorICCColor", + "setRadius", + "setRangeText", + "setRemoteDescription", + "setReportEventDataForAutomaticBeacons", + "setRequestHeader", + "setResizable", + "setResourceTimingBufferSize", + "setRotate", + "setScale", + "setScissorRect", + "setSeconds", + "setSelectionRange", + "setServerCertificate", + "setShadow", + "setSharedStorageContext", + "setSignals", + "setSinkId", + "setSkewX", + "setSkewY", + "setStart", + "setStartAfter", + "setStartBefore", + "setStatus", + "setStdDeviation", + "setStencilReference", + "setStreams", + "setStrictMode", + "setStringValue", + "setStrokeColor", + "setSuggestResult", + "setTargetAtTime", + "setTargetValueAtTime", + "setTime", + "setTimeout", + "setTransform", + "setTranslate", + "setUTCDate", + "setUTCFullYear", + "setUTCHours", + "setUTCMilliseconds", + "setUTCMinutes", + "setUTCMonth", + "setUTCSeconds", + "setUint16", + "setUint32", + "setUint8", + "setUri", + "setValidity", + "setValueAtTime", + "setValueCurveAtTime", + "setVariable", + "setVelocity", + "setVersion", + "setVertexBuffer", + "setViewport", + "setYear", + "settingName", + "settingValue", + "sex", + "shaderLocation", + "shaderSource", + "shadowBlur", + "shadowColor", + "shadowOffsetX", + "shadowOffsetY", + "shadowRoot", + "shadowRootClonable", + "shadowRootDelegatesFocus", + "shadowRootMode", + "shape", + "shape-image-threshold", + "shape-margin", + "shape-outside", + "shape-rendering", + "shapeImageThreshold", + "shapeMargin", + "shapeOutside", + "shapeRendering", + "share", + "sharedStorage", + "sharedStorageWritable", + "sheet", + "shift", + "shiftKey", + "shiftLeft", + "shippingAddress", + "shippingOption", + "shippingType", + "show", + "showDirectoryPicker", + "showHelp", + "showModal", + "showModalDialog", + "showModelessDialog", + "showNotification", + "showOpenFilePicker", + "showPicker", + "showPopover", + "showSaveFilePicker", + "sidebar", + "sign", + "signal", + "signalingState", + "signature", + "silent", + "sin", + "singleNodeValue", + "sinh", + "sinkId", + "sittingToStandingTransform", + "size", + "sizeAdjust", + "sizeToContent", + "sizeX", + "sizeZ", + "sizes", + "skewX", + "skewXSelf", + "skewY", + "skewYSelf", + "skipTransition", + "skipped", + "slice", + "slope", + "slot", + "slotAssignment", + "small", + "smil", + "smooth", + "smoothingTimeConstant", + "snapToLines", + "snapshotItem", + "snapshotLength", + "some", + "sort", + "sortingCode", + "source", + "sourceBuffer", + "sourceBuffers", + "sourceCapabilities", + "sourceCharPosition", + "sourceFile", + "sourceFunctionName", + "sourceIndex", + "sourceMap", + "sourceURL", + "sources", + "spacing", + "span", + "speak", + "speakAs", + "speaking", + "species", + "specified", + "specularConstant", + "specularExponent", + "speechSynthesis", + "speed", + "speedOfSound", + "spellcheck", + "sphericalHarmonicsCoefficients", + "splice", + "split", + "splitText", + "spreadMethod", + "sqrt", + "src", + "srcElement", + "srcFactor", + "srcFilter", + "srcObject", + "srcUrn", + "srcdoc", + "srclang", + "srcset", + "stack", + "stackTraceLimit", + "stacktrace", + "stageParameters", + "standalone", + "standby", + "start", + "startContainer", + "startIce", + "startMessages", + "startNotifications", + "startOffset", + "startProfiling", + "startRendering", + "startShark", + "startTime", + "startViewTransition", + "startsWith", + "state", + "states", + "stats", + "status", + "statusCode", + "statusMessage", + "statusText", + "statusbar", + "stdDeviationX", + "stdDeviationY", + "stencilBack", + "stencilClearValue", + "stencilFront", + "stencilFunc", + "stencilFuncSeparate", + "stencilLoadOp", + "stencilMask", + "stencilMaskSeparate", + "stencilOp", + "stencilOpSeparate", + "stencilReadMask", + "stencilReadOnly", + "stencilStoreOp", + "stencilWriteMask", + "step", + "stepDown", + "stepMismatch", + "stepMode", + "stepUp", + "sticky", + "stitchTiles", + "stop", + "stop-color", + "stop-opacity", + "stopColor", + "stopImmediatePropagation", + "stopNotifications", + "stopOpacity", + "stopProfiling", + "stopPropagation", + "stopShark", + "stopped", + "storage", + "storageArea", + "storageBuckets", + "storageName", + "storageStatus", + "storageTexture", + "store", + "storeOp", + "storeSiteSpecificTrackingException", + "storeWebWideTrackingException", + "stpVersion", + "stream", + "streamErrorCode", + "streams", + "stretch", + "strike", + "string", + "stringValue", + "stringify", + "stripIndexFormat", + "stroke", + "stroke-dasharray", + "stroke-dashoffset", + "stroke-linecap", + "stroke-linejoin", + "stroke-miterlimit", + "stroke-opacity", + "stroke-width", + "strokeDasharray", + "strokeDashoffset", + "strokeLinecap", + "strokeLinejoin", + "strokeMiterlimit", + "strokeOpacity", + "strokeRect", + "strokeStyle", + "strokeText", + "strokeWidth", + "structuredClone", + "style", + "styleAndLayoutStart", + "styleFloat", + "styleMap", + "styleMedia", + "styleSheet", + "styleSheetSets", + "styleSheets", + "sub", + "subarray", + "subject", + "submit", + "submitFrame", + "submitter", + "subscribe", + "substr", + "substring", + "substringData", + "subtle", + "subtree", + "suffix", + "suffixes", + "summary", + "sup", + "supported", + "supportedContentEncodings", + "supportedEntryTypes", + "supportedValuesOf", + "supports", + "supportsFiber", + "supportsSession", + "supportsText", + "surfaceScale", + "surroundContents", + "suspend", + "suspendRedraw", + "svb", + "svh", + "svi", + "svmax", + "svmin", + "svw", + "swapCache", + "swapNode", + "sweepFlag", + "symbols", + "symmetricDifference", + "sync", + "syntax", + "sysexEnabled", + "system", + "systemCode", + "systemId", + "systemLanguage", + "systemXDPI", + "systemYDPI", + "tBodies", + "tFoot", + "tHead", + "tab-size", + "tabIndex", + "tabSize", + "table", + "table-layout", + "tableLayout", + "tableValues", + "tag", + "tagName", + "tagUrn", + "tags", + "taintEnabled", + "take", + "takePhoto", + "takeRecords", + "tan", + "tangentialPressure", + "tanh", + "target", + "targetAddressSpace", + "targetElement", + "targetRayMode", + "targetRaySpace", + "targetTouches", + "targetURL", + "targetX", + "targetY", + "targets", + "tcpType", + "tee", + "tel", + "terminate", + "test", + "texImage2D", + "texImage3D", + "texParameterf", + "texParameteri", + "texStorage2D", + "texStorage3D", + "texSubImage2D", + "texSubImage3D", + "text", + "text-align", + "text-align-last", + "text-anchor", + "text-combine-upright", + "text-decoration", + "text-decoration-color", + "text-decoration-line", + "text-decoration-skip-ink", + "text-decoration-style", + "text-decoration-thickness", + "text-emphasis", + "text-emphasis-color", + "text-emphasis-position", + "text-emphasis-style", + "text-indent", + "text-justify", + "text-orientation", + "text-overflow", + "text-rendering", + "text-shadow", + "text-transform", + "text-underline-offset", + "text-underline-position", + "text-wrap", + "text-wrap-mode", + "text-wrap-style", + "textAlign", + "textAlignLast", + "textAnchor", + "textAutospace", + "textBaseline", + "textCombineUpright", + "textContent", + "textDecoration", + "textDecorationBlink", + "textDecorationColor", + "textDecorationLine", + "textDecorationLineThrough", + "textDecorationNone", + "textDecorationOverline", + "textDecorationSkipInk", + "textDecorationStyle", + "textDecorationThickness", + "textDecorationUnderline", + "textEmphasis", + "textEmphasisColor", + "textEmphasisPosition", + "textEmphasisStyle", + "textIndent", + "textJustify", + "textJustifyTrim", + "textKashida", + "textKashidaSpace", + "textLength", + "textOrientation", + "textOverflow", + "textRendering", + "textShadow", + "textTracks", + "textTransform", + "textUnderlineOffset", + "textUnderlinePosition", + "textWrap", + "textWrapMode", + "textWrapStyle", + "texture", + "then", + "threadId", + "threshold", + "thresholds", + "throwIfAborted", + "tiltX", + "tiltY", + "time", + "timeEnd", + "timeLog", + "timeOrigin", + "timeRemaining", + "timeStamp", + "timecode", + "timeline", + "timelineTime", + "timeout", + "timestamp", + "timestampOffset", + "timestampWrites", + "timing", + "title", + "titlebarAreaRect", + "to", + "toArray", + "toBlob", + "toDataURL", + "toDateString", + "toElement", + "toExponential", + "toFixed", + "toFloat32Array", + "toFloat64Array", + "toGMTString", + "toISOString", + "toJSON", + "toLocaleDateString", + "toLocaleFormat", + "toLocaleLowerCase", + "toLocaleString", + "toLocaleTimeString", + "toLocaleUpperCase", + "toLowerCase", + "toMatrix", + "toMethod", + "toPrecision", + "toPrimitive", + "toReversed", + "toSdp", + "toSorted", + "toSource", + "toSpliced", + "toStaticHTML", + "toString", + "toStringTag", + "toSum", + "toTimeString", + "toUTCString", + "toUpperCase", + "toWellFormed", + "toggle", + "toggleAttribute", + "toggleLongPressEnabled", + "togglePopover", + "token", + "tone", + "toneBuffer", + "tooLong", + "tooShort", + "toolbar", + "top", + "topMargin", + "topology", + "total", + "totalFrameDelay", + "totalFrames", + "totalVideoFrames", + "touch-action", + "touchAction", + "touched", + "touches", + "trace", + "track", + "trackVisibility", + "trackedAnchors", + "tracks", + "transaction", + "transactions", + "transceiver", + "transfer", + "transferControlToOffscreen", + "transferFromImageBitmap", + "transferImageBitmap", + "transferIn", + "transferOut", + "transferSize", + "transferToFixedLength", + "transferToImageBitmap", + "transform", + "transform-box", + "transform-origin", + "transform-style", + "transformBox", + "transformFeedbackVaryings", + "transformOrigin", + "transformPoint", + "transformString", + "transformStyle", + "transformToDocument", + "transformToFragment", + "transition", + "transition-delay", + "transition-duration", + "transition-property", + "transition-timing-function", + "transitionDelay", + "transitionDuration", + "transitionProperty", + "transitionTimingFunction", + "translate", + "translateSelf", + "translationX", + "translationY", + "transport", + "traverseTo", + "trim", + "trimEnd", + "trimLeft", + "trimRight", + "trimStart", + "trueSpeed", + "trunc", + "truncate", + "trustedTypes", + "turn", + "twist", + "type", + "typeDetail", + "typeMismatch", + "typeMustMatch", + "types", + "u2f", + "ubound", + "uint16", + "uint32", + "uint8", + "uint8Clamped", + "unadjustedMovement", + "unclippedDepth", + "unconfigure", + "undefined", + "underlineStyle", + "underlineThickness", + "unescape", + "uneval", + "unicode", + "unicode-bidi", + "unicodeBidi", + "unicodeRange", + "unicodeSets", + "uniform1f", + "uniform1fv", + "uniform1i", + "uniform1iv", + "uniform1ui", + "uniform1uiv", + "uniform2f", + "uniform2fv", + "uniform2i", + "uniform2iv", + "uniform2ui", + "uniform2uiv", + "uniform3f", + "uniform3fv", + "uniform3i", + "uniform3iv", + "uniform3ui", + "uniform3uiv", + "uniform4f", + "uniform4fv", + "uniform4i", + "uniform4iv", + "uniform4ui", + "uniform4uiv", + "uniformBlockBinding", + "uniformMatrix2fv", + "uniformMatrix2x3fv", + "uniformMatrix2x4fv", + "uniformMatrix3fv", + "uniformMatrix3x2fv", + "uniformMatrix3x4fv", + "uniformMatrix4fv", + "uniformMatrix4x2fv", + "uniformMatrix4x3fv", + "union", + "unique", + "uniqueID", + "uniqueNumber", + "unit", + "unitType", + "units", + "unloadEventEnd", + "unloadEventStart", + "unlock", + "unmap", + "unmount", + "unobserve", + "unpackColorSpace", + "unpause", + "unpauseAnimations", + "unreadCount", + "unregister", + "unregisterContentHandler", + "unregisterProtocolHandler", + "unscopables", + "unselectable", + "unshift", + "unsubscribe", + "unsuspendRedraw", + "unsuspendRedrawAll", + "unwatch", + "unwrapKey", + "upDegrees", + "upX", + "upY", + "upZ", + "update", + "updateAdInterestGroups", + "updateCallbackDone", + "updateCharacterBounds", + "updateCommands", + "updateControlBounds", + "updateCurrentEntry", + "updateIce", + "updateInkTrailStartPoint", + "updateInterval", + "updatePlaybackRate", + "updateRangeEnd", + "updateRangeStart", + "updateRenderState", + "updateSelection", + "updateSelectionBounds", + "updateSettings", + "updateText", + "updateTiming", + "updateViaCache", + "updateWith", + "updated", + "updating", + "upgrade", + "upload", + "uploadTotal", + "uploaded", + "upper", + "upperBound", + "upperOpen", + "uri", + "url", + "urn", + "urns", + "usage", + "usages", + "usb", + "usbVersionMajor", + "usbVersionMinor", + "usbVersionSubminor", + "useCurrentView", + "useMap", + "useProgram", + "usedSpace", + "user-select", + "userActivation", + "userAgent", + "userAgentData", + "userChoice", + "userHandle", + "userHint", + "userInitiated", + "userLanguage", + "userSelect", + "userState", + "userVisibleOnly", + "username", + "usernameFragment", + "utterance", + "uuid", + "v8BreakIterator", + "vAlign", + "vLink", + "valid", + "validate", + "validateProgram", + "validationMessage", + "validity", + "value", + "valueAsDate", + "valueAsNumber", + "valueAsString", + "valueInSpecifiedUnits", + "valueMissing", + "valueOf", + "valueText", + "valueType", + "values", + "variable", + "variant", + "variationSettings", + "vb", + "vector-effect", + "vectorEffect", + "velocityAngular", + "velocityExpansion", + "velocityX", + "velocityY", + "vendor", + "vendorId", + "vendorSub", + "verify", + "version", + "vertex", + "vertexAttrib1f", + "vertexAttrib1fv", + "vertexAttrib2f", + "vertexAttrib2fv", + "vertexAttrib3f", + "vertexAttrib3fv", + "vertexAttrib4f", + "vertexAttrib4fv", + "vertexAttribDivisor", + "vertexAttribDivisorANGLE", + "vertexAttribI4i", + "vertexAttribI4iv", + "vertexAttribI4ui", + "vertexAttribI4uiv", + "vertexAttribIPointer", + "vertexAttribPointer", + "vertical", + "vertical-align", + "verticalAlign", + "verticalOverflow", + "vh", + "vi", + "vibrate", + "vibrationActuator", + "videoBitsPerSecond", + "videoHeight", + "videoTracks", + "videoWidth", + "view", + "viewBox", + "viewBoxString", + "viewDimension", + "viewFormats", + "viewTarget", + "viewTargetString", + "viewport", + "viewportAnchorX", + "viewportAnchorY", + "viewportElement", + "views", + "violatedDirective", + "virtualKeyboard", + "virtualKeyboardPolicy", + "visibility", + "visibilityState", + "visible", + "visibleRect", + "visualViewport", + "vlinkColor", + "vmax", + "vmin", + "voice", + "voiceURI", + "volume", + "vrml", + "vspace", + "vw", + "w", + "wait", + "waitAsync", + "waitSync", + "waiting", + "wake", + "wakeLock", + "wand", + "warn", + "wasClean", + "wasDiscarded", + "watch", + "watchAvailability", + "watchPosition", + "webdriver", + "webkitAddKey", + "webkitAlignContent", + "webkitAlignItems", + "webkitAlignSelf", + "webkitAnimation", + "webkitAnimationDelay", + "webkitAnimationDirection", + "webkitAnimationDuration", + "webkitAnimationFillMode", + "webkitAnimationIterationCount", + "webkitAnimationName", + "webkitAnimationPlayState", + "webkitAnimationTimingFunction", + "webkitAppearance", + "webkitAudioContext", + "webkitAudioDecodedByteCount", + "webkitAudioPannerNode", + "webkitBackfaceVisibility", + "webkitBackground", + "webkitBackgroundAttachment", + "webkitBackgroundClip", + "webkitBackgroundColor", + "webkitBackgroundImage", + "webkitBackgroundOrigin", + "webkitBackgroundPosition", + "webkitBackgroundPositionX", + "webkitBackgroundPositionY", + "webkitBackgroundRepeat", + "webkitBackgroundSize", + "webkitBackingStorePixelRatio", + "webkitBorderBottomLeftRadius", + "webkitBorderBottomRightRadius", + "webkitBorderImage", + "webkitBorderImageOutset", + "webkitBorderImageRepeat", + "webkitBorderImageSlice", + "webkitBorderImageSource", + "webkitBorderImageWidth", + "webkitBorderRadius", + "webkitBorderTopLeftRadius", + "webkitBorderTopRightRadius", + "webkitBoxAlign", + "webkitBoxDirection", + "webkitBoxFlex", + "webkitBoxOrdinalGroup", + "webkitBoxOrient", + "webkitBoxPack", + "webkitBoxShadow", + "webkitBoxSizing", + "webkitCancelAnimationFrame", + "webkitCancelFullScreen", + "webkitCancelKeyRequest", + "webkitCancelRequestAnimationFrame", + "webkitClearResourceTimings", + "webkitClipPath", + "webkitClosedCaptionsVisible", + "webkitConvertPointFromNodeToPage", + "webkitConvertPointFromPageToNode", + "webkitCreateShadowRoot", + "webkitCurrentFullScreenElement", + "webkitCurrentPlaybackTargetIsWireless", + "webkitDecodedFrameCount", + "webkitDirectionInvertedFromDevice", + "webkitDisplayingFullscreen", + "webkitDroppedFrameCount", + "webkitEnterFullScreen", + "webkitEnterFullscreen", + "webkitEntries", + "webkitExitFullScreen", + "webkitExitFullscreen", + "webkitExitPointerLock", + "webkitFilter", + "webkitFlex", + "webkitFlexBasis", + "webkitFlexDirection", + "webkitFlexFlow", + "webkitFlexGrow", + "webkitFlexShrink", + "webkitFlexWrap", + "webkitFullScreenKeyboardInputAllowed", + "webkitFullscreenElement", + "webkitFullscreenEnabled", + "webkitGenerateKeyRequest", + "webkitGetAsEntry", + "webkitGetDatabaseNames", + "webkitGetEntries", + "webkitGetEntriesByName", + "webkitGetEntriesByType", + "webkitGetFlowByName", + "webkitGetGamepads", + "webkitGetImageDataHD", + "webkitGetNamedFlows", + "webkitGetRegionFlowRanges", + "webkitGetUserMedia", + "webkitHasClosedCaptions", + "webkitHidden", + "webkitIDBCursor", + "webkitIDBDatabase", + "webkitIDBDatabaseError", + "webkitIDBDatabaseException", + "webkitIDBFactory", + "webkitIDBIndex", + "webkitIDBKeyRange", + "webkitIDBObjectStore", + "webkitIDBRequest", + "webkitIDBTransaction", + "webkitImageSmoothingEnabled", + "webkitIndexedDB", + "webkitInitMessageEvent", + "webkitIsFullScreen", + "webkitJustifyContent", + "webkitKeys", + "webkitLineClamp", + "webkitLineDashOffset", + "webkitLockOrientation", + "webkitMask", + "webkitMaskClip", + "webkitMaskComposite", + "webkitMaskImage", + "webkitMaskOrigin", + "webkitMaskPosition", + "webkitMaskPositionX", + "webkitMaskPositionY", + "webkitMaskRepeat", + "webkitMaskSize", + "webkitMatchesSelector", + "webkitMediaStream", + "webkitNotifications", + "webkitOfflineAudioContext", + "webkitOrder", + "webkitOrientation", + "webkitPeerConnection00", + "webkitPersistentStorage", + "webkitPerspective", + "webkitPerspectiveOrigin", + "webkitPointerLockElement", + "webkitPostMessage", + "webkitPreservesPitch", + "webkitPutImageDataHD", + "webkitRTCPeerConnection", + "webkitRegionOverset", + "webkitRelativePath", + "webkitRequestAnimationFrame", + "webkitRequestFileSystem", + "webkitRequestFullScreen", + "webkitRequestFullscreen", + "webkitRequestPointerLock", + "webkitResolveLocalFileSystemURL", + "webkitSetMediaKeys", + "webkitSetResourceTimingBufferSize", + "webkitShadowRoot", + "webkitShowPlaybackTargetPicker", + "webkitSlice", + "webkitSpeechGrammar", + "webkitSpeechGrammarList", + "webkitSpeechRecognition", + "webkitSpeechRecognitionError", + "webkitSpeechRecognitionEvent", + "webkitStorageInfo", + "webkitSupportsFullscreen", + "webkitTemporaryStorage", + "webkitTextFillColor", + "webkitTextSecurity", + "webkitTextSizeAdjust", + "webkitTextStroke", + "webkitTextStrokeColor", + "webkitTextStrokeWidth", + "webkitTransform", + "webkitTransformOrigin", + "webkitTransformStyle", + "webkitTransition", + "webkitTransitionDelay", + "webkitTransitionDuration", + "webkitTransitionProperty", + "webkitTransitionTimingFunction", + "webkitURL", + "webkitUnlockOrientation", + "webkitUserSelect", + "webkitVideoDecodedByteCount", + "webkitVisibilityState", + "webkitWirelessVideoPlaybackDisabled", + "webkitdirectory", + "webkitdropzone", + "webstore", + "weight", + "wgslLanguageFeatures", + "whatToShow", + "wheelDelta", + "wheelDeltaX", + "wheelDeltaY", + "whenDefined", + "which", + "white-space", + "white-space-collapse", + "whiteSpace", + "whiteSpaceCollapse", + "wholeText", + "widows", + "width", + "will-change", + "willChange", + "willValidate", + "window", + "windowAttribution", + "windowControlsOverlay", + "with", + "withCredentials", + "withResolvers", + "word-break", + "word-spacing", + "word-wrap", + "wordBreak", + "wordSpacing", + "wordWrap", + "workerStart", + "worklet", + "wow64", + "wrap", + "wrapKey", + "writable", + "writableAuxiliaries", + "write", + "writeBuffer", + "writeMask", + "writeText", + "writeTexture", + "writeTimestamp", + "writeValue", + "writeValueWithResponse", + "writeValueWithoutResponse", + "writeWithoutResponse", + "writeln", + "writing-mode", + "writingMode", + "writingSuggestions", + "x", + "x1", + "x2", + "xChannelSelector", + "xmlEncoding", + "xmlStandalone", + "xmlVersion", + "xmlbase", + "xmllang", + "xmlspace", + "xor", + "xr", + "y", + "y1", + "y2", + "yChannelSelector", + "yandex", + "z", + "z-index", + "zIndex", + "zoom", + "zoomAndPan", + "zoomRectScreen", +]; + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +function find_builtins(reserved) { + domprops.forEach(add); + + // Compatibility fix for some standard defined globals not defined on every js environment + var new_globals = ["Symbol", "Map", "Promise", "Proxy", "Reflect", "Set", "WeakMap", "WeakSet"]; + var objects = {}; + var global_ref = typeof global === "object" ? global : self; + + new_globals.forEach(function (new_global) { + objects[new_global] = global_ref[new_global] || function() {}; + }); + + [ + "null", + "true", + "false", + "NaN", + "Infinity", + "-Infinity", + "undefined", + ].forEach(add); + [ Object, Array, Function, Number, + String, Boolean, Error, Math, + Date, RegExp, objects.Symbol, ArrayBuffer, + DataView, decodeURI, decodeURIComponent, + encodeURI, encodeURIComponent, eval, EvalError, + Float32Array, Float64Array, Int8Array, Int16Array, + Int32Array, isFinite, isNaN, JSON, objects.Map, parseFloat, + parseInt, objects.Promise, objects.Proxy, RangeError, ReferenceError, + objects.Reflect, objects.Set, SyntaxError, TypeError, Uint8Array, + Uint8ClampedArray, Uint16Array, Uint32Array, URIError, + objects.WeakMap, objects.WeakSet + ].forEach(function(ctor) { + Object.getOwnPropertyNames(ctor).map(add); + if (ctor.prototype) { + Object.getOwnPropertyNames(ctor.prototype).map(add); + } + }); + function add(name) { + reserved.add(name); + } +} + +function reserve_quoted_keys(ast, reserved) { + function add(name) { + push_uniq(reserved, name); + } + + ast.walk(new TreeWalker(function(node) { + if (node instanceof AST_ObjectKeyVal && node.quote) { + add(node.key); + } else if (node instanceof AST_ObjectProperty && node.quote) { + add(node.key.name); + } else if (node instanceof AST_Sub) { + addStrings(node.property, add); + } + })); +} + +function addStrings(node, add) { + node.walk(new TreeWalker(function(node) { + if (node instanceof AST_Sequence) { + addStrings(node.tail_node(), add); + } else if (node instanceof AST_String) { + add(node.value); + } else if (node instanceof AST_Conditional) { + addStrings(node.consequent, add); + addStrings(node.alternative, add); + } + return true; + })); +} + +function mangle_private_properties(ast, options) { + var cprivate = -1; + var private_cache = new Map(); + var nth_identifier = options.nth_identifier || base54; + + ast = ast.transform(new TreeTransformer(function(node) { + if ( + node instanceof AST_ClassPrivateProperty + || node instanceof AST_PrivateMethod + || node instanceof AST_PrivateGetter + || node instanceof AST_PrivateSetter + || node instanceof AST_PrivateIn + ) { + node.key.name = mangle_private(node.key.name); + } else if (node instanceof AST_DotHash) { + node.property = mangle_private(node.property); + } + })); + return ast; + + function mangle_private(name) { + let mangled = private_cache.get(name); + if (!mangled) { + mangled = nth_identifier.get(++cprivate); + private_cache.set(name, mangled); + } + + return mangled; + } +} + +function find_annotated_props(ast) { + var annotated_props = new Set(); + walk(ast, node => { + if ( + node instanceof AST_ClassPrivateProperty + || node instanceof AST_PrivateMethod + || node instanceof AST_PrivateGetter + || node instanceof AST_PrivateSetter + || node instanceof AST_DotHash + ) ; else if (node instanceof AST_ObjectKeyVal) { + if (typeof node.key == "string" && has_annotation(node, _MANGLEPROP)) { + annotated_props.add(node.key); + } + } else if (node instanceof AST_ObjectProperty) { + // setter or getter, since KeyVal is handled above + if (has_annotation(node, _MANGLEPROP)) { + annotated_props.add(node.key.name); + } + } else if (node instanceof AST_Dot) { + if (has_annotation(node, _MANGLEPROP)) { + annotated_props.add(node.property); + } + } else if (node instanceof AST_Sub) { + if (node.property instanceof AST_String && has_annotation(node, _MANGLEPROP)) { + annotated_props.add(node.property.value); + } + } + }); + return annotated_props; +} + +function mangle_properties(ast, options, annotated_props = find_annotated_props(ast)) { + options = defaults(options, { + builtins: false, + cache: null, + debug: false, + keep_quoted: false, + nth_identifier: base54, + only_cache: false, + regex: null, + reserved: null, + undeclared: false, + only_annotated: false, + }, true); + + var nth_identifier = options.nth_identifier; + + var reserved_option = options.reserved; + if (!Array.isArray(reserved_option)) reserved_option = [reserved_option]; + var reserved = new Set(reserved_option); + if (!options.builtins) find_builtins(reserved); + + var cname = -1; + + var cache; + if (options.cache) { + cache = options.cache.props; + } else { + cache = new Map(); + } + + var only_annotated = options.only_annotated; + var regex = options.regex && new RegExp(options.regex); + + // note debug is either false (disabled), or a string of the debug suffix to use (enabled). + // note debug may be enabled as an empty string, which is falsey. Also treat passing 'true' + // the same as passing an empty string. + var debug = options.debug !== false; + var debug_name_suffix; + if (debug) { + debug_name_suffix = (options.debug === true ? "" : options.debug); + } + + var names_to_mangle = new Set(); + var unmangleable = new Set(); + // Track each already-mangled name to prevent nth_identifier from generating + // the same name. + cache.forEach((mangled_name) => unmangleable.add(mangled_name)); + + var keep_quoted = !!options.keep_quoted; + + // step 1: find candidates to mangle + ast.walk(new TreeWalker(function(node) { + if ( + node instanceof AST_ClassPrivateProperty + || node instanceof AST_PrivateMethod + || node instanceof AST_PrivateGetter + || node instanceof AST_PrivateSetter + || node instanceof AST_DotHash + ) ; else if (node instanceof AST_ObjectKeyVal) { + if (typeof node.key == "string" && (!keep_quoted || !node.quote)) { + add(node.key); + } + } else if (node instanceof AST_ObjectProperty) { + // setter or getter, since KeyVal is handled above + if (!keep_quoted || !node.quote) { + add(node.key.name); + } + } else if (node instanceof AST_Dot) { + var declared = !!options.undeclared; + if (!declared) { + var root = node; + while (root.expression) { + root = root.expression; + } + declared = !(root.thedef && root.thedef.undeclared); + } + if (declared && + (!keep_quoted || !node.quote)) { + add(node.property); + } + } else if (node instanceof AST_Sub) { + if (!keep_quoted) { + addStrings(node.property, add); + } + } else if (node instanceof AST_Call + && node.expression.print_to_string() == "Object.defineProperty") { + addStrings(node.args[1], add); + } else if (node instanceof AST_Binary && node.operator === "in") { + addStrings(node.left, add); + } else if (node instanceof AST_String && has_annotation(node, _KEY)) { + add(node.value); + } + })); + + // step 2: transform the tree, renaming properties + return ast.transform(new TreeTransformer(function(node) { + if ( + node instanceof AST_ClassPrivateProperty + || node instanceof AST_PrivateMethod + || node instanceof AST_PrivateGetter + || node instanceof AST_PrivateSetter + || node instanceof AST_DotHash + ) ; else if (node instanceof AST_ObjectKeyVal) { + if (typeof node.key == "string" && (!keep_quoted || !node.quote)) { + node.key = mangle(node.key); + } + } else if (node instanceof AST_ObjectProperty) { + // setter, getter, method or class field + if (!keep_quoted || !node.quote) { + node.key.name = mangle(node.key.name); + } + } else if (node instanceof AST_Dot) { + if (!keep_quoted || !node.quote) { + node.property = mangle(node.property); + } + } else if (!keep_quoted && node instanceof AST_Sub) { + node.property = mangleStrings(node.property); + } else if (node instanceof AST_Call + && node.expression.print_to_string() == "Object.defineProperty") { + node.args[1] = mangleStrings(node.args[1]); + } else if (node instanceof AST_Binary && node.operator === "in") { + node.left = mangleStrings(node.left); + } else if (node instanceof AST_String && has_annotation(node, _KEY)) { + // Clear _KEY annotation to prevent double mangling + clear_annotation(node, _KEY); + node.value = mangle(node.value); + } + })); + + // only function declarations after this line + + function can_mangle(name) { + if (unmangleable.has(name)) return false; + if (reserved.has(name)) return false; + if (options.only_cache) { + return cache.has(name); + } + if (/^-?[0-9]+(\.[0-9]+)?(e[+-][0-9]+)?$/.test(name)) return false; + return true; + } + + function should_mangle(name) { + if (only_annotated && !annotated_props.has(name)) return false; + if (regex && !regex.test(name)) { + return annotated_props.has(name); + } + if (reserved.has(name)) return false; + return cache.has(name) + || names_to_mangle.has(name); + } + + function add(name) { + if (can_mangle(name)) { + names_to_mangle.add(name); + } + + if (!should_mangle(name)) { + unmangleable.add(name); + } + } + + function mangle(name) { + if (!should_mangle(name)) { + return name; + } + + var mangled = cache.get(name); + if (!mangled) { + if (debug) { + // debug mode: use a prefix and suffix to preserve readability, e.g. o.foo -> o._$foo$NNN_. + var debug_mangled = "_$" + name + "$" + debug_name_suffix + "_"; + + if (can_mangle(debug_mangled)) { + mangled = debug_mangled; + } + } + + // either debug mode is off, or it is on and we could not use the mangled name + if (!mangled) { + do { + mangled = nth_identifier.get(++cname); + } while (!can_mangle(mangled)); + } + + cache.set(name, mangled); + } + return mangled; + } + + function mangleStrings(node) { + return node.transform(new TreeTransformer(function(node) { + if (node instanceof AST_Sequence) { + var last = node.expressions.length - 1; + node.expressions[last] = mangleStrings(node.expressions[last]); + } else if (node instanceof AST_String) { + // Clear _KEY annotation to prevent double mangling + clear_annotation(node, _KEY); + node.value = mangle(node.value); + } else if (node instanceof AST_Conditional) { + node.consequent = mangleStrings(node.consequent); + node.alternative = mangleStrings(node.alternative); + } + return node; + })); + } +} + +// to/from base64 functions +// Prefer built-in Buffer, if available, then use hack +// https://developer.mozilla.org/en-US/docs/Glossary/Base64#The_Unicode_Problem +var to_ascii = typeof Buffer !== "undefined" + ? (b64) => Buffer.from(b64, "base64").toString() + : (b64) => decodeURIComponent(escape(atob(b64))); +var to_base64 = typeof Buffer !== "undefined" + ? (str) => Buffer.from(str).toString("base64") + : (str) => btoa(unescape(encodeURIComponent(str))); + +function read_source_map(code) { + var match = /(?:^|[^.])\/\/# sourceMappingURL=data:application\/json(;[\w=-]*)?;base64,([+/0-9A-Za-z]*=*)\s*$/.exec(code); + if (!match) { + console.warn("inline source map not found"); + return null; + } + return to_ascii(match[2]); +} + +function set_shorthand(name, options, keys) { + if (options[name]) { + keys.forEach(function(key) { + if (options[key]) { + if (typeof options[key] != "object") options[key] = {}; + if (!(name in options[key])) options[key][name] = options[name]; + } + }); + } +} + +function init_cache(cache) { + if (!cache) return; + if (!("props" in cache)) { + cache.props = new Map(); + } else if (!(cache.props instanceof Map)) { + cache.props = map_from_object(cache.props); + } +} + +function cache_to_json(cache) { + return { + props: map_to_object(cache.props) + }; +} + +function log_input(files, options, fs, debug_folder) { + if (!(fs && fs.writeFileSync && fs.mkdirSync)) { + return; + } + + try { + fs.mkdirSync(debug_folder); + } catch (e) { + if (e.code !== "EEXIST") throw e; + } + + const log_path = `${debug_folder}/terser-debug-${(Math.random() * 9999999) | 0}.log`; + + options = options || {}; + + const options_str = JSON.stringify(options, (_key, thing) => { + if (typeof thing === "function") return "[Function " + thing.toString() + "]"; + if (thing instanceof RegExp) return "[RegExp " + thing.toString() + "]"; + return thing; + }, 4); + + const files_str = (file) => { + if (typeof file === "object" && options.parse && options.parse.spidermonkey) { + return JSON.stringify(file, null, 2); + } else if (typeof file === "object") { + return Object.keys(file) + .map((key) => key + ": " + files_str(file[key])) + .join("\n\n"); + } else if (typeof file === "string") { + return "```\n" + file + "\n```"; + } else { + return file; // What do? + } + }; + + fs.writeFileSync(log_path, "Options: \n" + options_str + "\n\nInput files:\n\n" + files_str(files) + "\n"); +} + +function* minify_sync_or_async(files, options, _fs_module) { + if ( + _fs_module + && typeof process === "object" + && process.env + && typeof process.env.TERSER_DEBUG_DIR === "string" + ) { + log_input(files, options, _fs_module, process.env.TERSER_DEBUG_DIR); + } + + options = defaults(options, { + compress: {}, + ecma: undefined, + enclose: false, + ie8: false, + keep_classnames: undefined, + keep_fnames: false, + mangle: {}, + module: false, + nameCache: null, + output: null, + format: null, + parse: {}, + rename: undefined, + safari10: false, + sourceMap: false, + spidermonkey: false, + timings: false, + toplevel: false, + warnings: false, + wrap: false, + }, true); + + var timings = options.timings && { + start: Date.now() + }; + if (options.keep_classnames === undefined) { + options.keep_classnames = options.keep_fnames; + } + if (options.rename === undefined) { + options.rename = options.compress && options.mangle; + } + if (options.output && options.format) { + throw new Error("Please only specify either output or format option, preferrably format."); + } + options.format = options.format || options.output || {}; + set_shorthand("ecma", options, [ "parse", "compress", "format" ]); + set_shorthand("ie8", options, [ "compress", "mangle", "format" ]); + set_shorthand("keep_classnames", options, [ "compress", "mangle" ]); + set_shorthand("keep_fnames", options, [ "compress", "mangle" ]); + set_shorthand("module", options, [ "parse", "compress", "mangle" ]); + set_shorthand("safari10", options, [ "mangle", "format" ]); + set_shorthand("toplevel", options, [ "compress", "mangle" ]); + set_shorthand("warnings", options, [ "compress" ]); // legacy + var quoted_props; + if (options.mangle) { + options.mangle = defaults(options.mangle, { + cache: options.nameCache && (options.nameCache.vars || {}), + eval: false, + ie8: false, + keep_classnames: false, + keep_fnames: false, + module: false, + nth_identifier: base54, + properties: false, + reserved: [], + safari10: false, + toplevel: false, + }, true); + if (options.mangle.properties) { + if (typeof options.mangle.properties != "object") { + options.mangle.properties = {}; + } + if (options.mangle.properties.keep_quoted) { + quoted_props = options.mangle.properties.reserved; + if (!Array.isArray(quoted_props)) quoted_props = []; + options.mangle.properties.reserved = quoted_props; + } + if (options.nameCache && !("cache" in options.mangle.properties)) { + options.mangle.properties.cache = options.nameCache.props || {}; + } + } + init_cache(options.mangle.cache); + init_cache(options.mangle.properties.cache); + } + if (options.sourceMap) { + options.sourceMap = defaults(options.sourceMap, { + asObject: false, + content: null, + filename: null, + includeSources: false, + root: null, + url: null, + }, true); + } + + // -- Parse phase -- + if (timings) timings.parse = Date.now(); + var toplevel; + if (files instanceof AST_Toplevel) { + toplevel = files; + } else { + if (typeof files == "string" || (options.parse.spidermonkey && !Array.isArray(files))) { + files = [ files ]; + } + options.parse = options.parse || {}; + options.parse.toplevel = null; + + if (options.parse.spidermonkey) { + options.parse.toplevel = AST_Node.from_mozilla_ast(Object.keys(files).reduce(function(toplevel, name) { + if (!toplevel) return files[name]; + toplevel.body = toplevel.body.concat(files[name].body); + return toplevel; + }, null)); + } else { + delete options.parse.spidermonkey; + + for (var name in files) if (HOP(files, name)) { + options.parse.filename = name; + options.parse.toplevel = parse(files[name], options.parse); + if (options.sourceMap && options.sourceMap.content == "inline") { + if (Object.keys(files).length > 1) + throw new Error("inline source map only works with singular input"); + options.sourceMap.content = read_source_map(files[name]); + } + } + } + if (options.parse.toplevel === null) { + throw new Error("no source file given"); + } + + toplevel = options.parse.toplevel; + } + if (quoted_props && options.mangle.properties.keep_quoted !== "strict") { + reserve_quoted_keys(toplevel, quoted_props); + } + var annotated_props; + if (options.mangle && options.mangle.properties) { + annotated_props = find_annotated_props(toplevel); + } + if (options.wrap) { + toplevel = toplevel.wrap_commonjs(options.wrap); + } + if (options.enclose) { + toplevel = toplevel.wrap_enclose(options.enclose); + } + if (timings) timings.rename = Date.now(); + + // -- Compress phase -- + if (timings) timings.compress = Date.now(); + if (options.compress) { + toplevel = new Compressor(options.compress, { + mangle_options: options.mangle + }).compress(toplevel); + } + + // -- Mangle phase -- + if (timings) timings.scope = Date.now(); + if (options.mangle) toplevel.figure_out_scope(options.mangle); + if (timings) timings.mangle = Date.now(); + if (options.mangle) { + toplevel.compute_char_frequency(options.mangle); + toplevel.mangle_names(options.mangle); + toplevel = mangle_private_properties(toplevel, options.mangle); + } + if (timings) timings.properties = Date.now(); + if (options.mangle && options.mangle.properties) { + toplevel = mangle_properties(toplevel, options.mangle.properties, annotated_props); + } + + // Format phase + if (timings) timings.format = Date.now(); + var result = {}; + if (options.format.ast) { + result.ast = toplevel; + } + if (options.format.spidermonkey) { + result.ast = toplevel.to_mozilla_ast(); + } + let format_options; + if (!HOP(options.format, "code") || options.format.code) { + // Make a shallow copy so that we can modify without mutating the user's input. + format_options = {...options.format}; + if (!format_options.ast) { + // Destroy stuff to save RAM. (unless the deprecated `ast` option is on) + format_options._destroy_ast = true; + + walk(toplevel, node => { + if (node instanceof AST_Scope) { + node.variables = undefined; + node.enclosed = undefined; + node.parent_scope = undefined; + } + if (node.block_scope) { + node.block_scope.variables = undefined; + node.block_scope.enclosed = undefined; + node.parent_scope = undefined; + } + }); + } + + if (options.sourceMap) { + if (options.sourceMap.includeSources && files instanceof AST_Toplevel) { + throw new Error("original source content unavailable"); + } + format_options.source_map = yield* SourceMap({ + file: options.sourceMap.filename, + orig: options.sourceMap.content, + root: options.sourceMap.root, + files: options.sourceMap.includeSources ? files : null, + }); + } + delete format_options.ast; + delete format_options.code; + delete format_options.spidermonkey; + var stream = OutputStream(format_options); + toplevel.print(stream); + result.code = stream.get(); + if (options.sourceMap) { + Object.defineProperty(result, "map", { + configurable: true, + enumerable: true, + get() { + const map = format_options.source_map.getEncoded(); + return (result.map = options.sourceMap.asObject ? map : JSON.stringify(map)); + }, + set(value) { + Object.defineProperty(result, "map", { + value, + writable: true, + }); + } + }); + result.decoded_map = format_options.source_map.getDecoded(); + if (options.sourceMap.url == "inline") { + var sourceMap = typeof result.map === "object" ? JSON.stringify(result.map) : result.map; + result.code += "\n//# sourceMappingURL=data:application/json;charset=utf-8;base64," + to_base64(sourceMap); + } else if (options.sourceMap.url) { + result.code += "\n//# sourceMappingURL=" + options.sourceMap.url; + } + } + } + if (options.nameCache && options.mangle) { + if (options.mangle.cache) options.nameCache.vars = cache_to_json(options.mangle.cache); + if (options.mangle.properties && options.mangle.properties.cache) { + options.nameCache.props = cache_to_json(options.mangle.properties.cache); + } + } + if (format_options && format_options.source_map) { + format_options.source_map.destroy(); + } + if (timings) { + timings.end = Date.now(); + result.timings = { + parse: 1e-3 * (timings.rename - timings.parse), + rename: 1e-3 * (timings.compress - timings.rename), + compress: 1e-3 * (timings.scope - timings.compress), + scope: 1e-3 * (timings.mangle - timings.scope), + mangle: 1e-3 * (timings.properties - timings.mangle), + properties: 1e-3 * (timings.format - timings.properties), + format: 1e-3 * (timings.end - timings.format), + total: 1e-3 * (timings.end - timings.start) + }; + } + return result; +} + +async function minify(files, options, _fs_module) { + const gen = minify_sync_or_async(files, options, _fs_module); + + let yielded; + let val; + do { + val = gen.next(await yielded); + yielded = val.value; + } while (!val.done); + + return val.value; +} + +function minify_sync(files, options, _fs_module) { + const gen = minify_sync_or_async(files, options, _fs_module); + + let yielded; + let val; + do { + if (yielded && typeof yielded.then === "function") { + throw new Error("minify_sync cannot be used with the legacy source-map module"); + } + val = gen.next(yielded); + yielded = val.value; + } while (!val.done); + + return val.value; +} + +async function run_cli({ program, packageJson, fs, path }) { + const skip_keys = new Set([ "cname", "parent_scope", "scope", "uses_eval", "uses_with" ]); + var files = {}; + var options = { + compress: false, + mangle: false + }; + const default_options = await _default_options(); + program.version(packageJson.name + " " + packageJson.version); + program.parseArgv = program.parse; + program.parse = undefined; + + if (process.argv.includes("ast")) program.helpInformation = describe_ast; + else if (process.argv.includes("options")) program.helpInformation = function() { + var text = []; + for (var option in default_options) { + text.push("--" + (option === "sourceMap" ? "source-map" : option) + " options:"); + text.push(format_object(default_options[option])); + text.push(""); + } + return text.join("\n"); + }; + + program.option("-p, --parse ", "Specify parser options.", parse_js()); + program.option("-c, --compress [options]", "Enable compressor/specify compressor options.", parse_js()); + program.option("-m, --mangle [options]", "Mangle names/specify mangler options.", parse_js()); + program.option("--mangle-props [options]", "Mangle properties/specify mangler options.", parse_js()); + program.option("-f, --format [options]", "Format options.", parse_js()); + program.option("-b, --beautify [options]", "Alias for --format.", parse_js()); + program.option("-o, --output ", "Output file (default STDOUT)."); + program.option("--comments [filter]", "Preserve copyright comments in the output."); + program.option("--config-file ", "Read minify() options from JSON file."); + program.option("-d, --define [=value]", "Global definitions.", parse_js("define")); + program.option("--ecma ", "Specify ECMAScript release: 5, 2015, 2016 or 2017..."); + program.option("-e, --enclose [arg[,...][:value[,...]]]", "Embed output in a big function with configurable arguments and values."); + program.option("--ie8", "Support non-standard Internet Explorer 8."); + program.option("--keep-classnames", "Do not mangle/drop class names."); + program.option("--keep-fnames", "Do not mangle/drop function names. Useful for code relying on Function.prototype.name."); + program.option("--module", "Input is an ES6 module"); + program.option("--name-cache ", "File to hold mangled name mappings."); + program.option("--rename", "Force symbol expansion."); + program.option("--no-rename", "Disable symbol expansion."); + program.option("--safari10", "Support non-standard Safari 10."); + program.option("--source-map [options]", "Enable source map/specify source map options.", parse_js()); + program.option("--timings", "Display operations run time on STDERR."); + program.option("--toplevel", "Compress and/or mangle variables in toplevel scope."); + program.option("--wrap ", "Embed everything as a function with “exports” corresponding to “name” globally."); + program.arguments("[files...]").parseArgv(process.argv); + if (program.configFile) { + options = JSON.parse(read_file(program.configFile)); + } + if (!program.output && program.sourceMap && program.sourceMap.url != "inline") { + fatal("ERROR: cannot write source map to STDOUT"); + } + + [ + "compress", + "enclose", + "ie8", + "mangle", + "module", + "safari10", + "sourceMap", + "toplevel", + "wrap" + ].forEach(function(name) { + if (name in program) { + options[name] = program[name]; + } + }); + + if ("ecma" in program) { + if (program.ecma != (program.ecma | 0)) fatal("ERROR: ecma must be an integer"); + const ecma = program.ecma | 0; + if (ecma > 5 && ecma < 2015) + options.ecma = ecma + 2009; + else + options.ecma = ecma; + } + if (program.format || program.beautify) { + const chosenOption = program.format || program.beautify; + options.format = typeof chosenOption === "object" ? chosenOption : {}; + } + if (program.comments) { + if (typeof options.format != "object") options.format = {}; + options.format.comments = typeof program.comments == "string" ? (program.comments == "false" ? false : program.comments) : "some"; + } + if (program.define) { + if (typeof options.compress != "object") options.compress = {}; + if (typeof options.compress.global_defs != "object") options.compress.global_defs = {}; + for (var expr in program.define) { + options.compress.global_defs[expr] = program.define[expr]; + } + } + if (program.keepClassnames) { + options.keep_classnames = true; + } + if (program.keepFnames) { + options.keep_fnames = true; + } + if (program.mangleProps) { + if (program.mangleProps.domprops) { + delete program.mangleProps.domprops; + } else { + if (typeof program.mangleProps != "object") program.mangleProps = {}; + if (!Array.isArray(program.mangleProps.reserved)) program.mangleProps.reserved = []; + } + if (typeof options.mangle != "object") options.mangle = {}; + options.mangle.properties = program.mangleProps; + } + if (program.nameCache) { + options.nameCache = JSON.parse(read_file(program.nameCache, "{}")); + } + if (program.output == "ast") { + options.format = { + ast: true, + code: false + }; + } + if (program.parse) { + if (!program.parse.acorn && !program.parse.spidermonkey) { + options.parse = program.parse; + } else if (program.sourceMap && program.sourceMap.content == "inline") { + fatal("ERROR: inline source map only works with built-in parser"); + } + } + if (~program.rawArgs.indexOf("--rename")) { + options.rename = true; + } else if (!program.rename) { + options.rename = false; + } + + let convert_path = name => name; + if (typeof program.sourceMap == "object" && "base" in program.sourceMap) { + convert_path = function() { + var base = program.sourceMap.base; + delete options.sourceMap.base; + return function(name) { + return path.relative(base, name); + }; + }(); + } + + let filesList; + if (options.files && options.files.length) { + filesList = options.files; + + delete options.files; + } else if (program.args.length) { + filesList = program.args; + } + + if (filesList) { + simple_glob(filesList).forEach(function(name) { + files[convert_path(name)] = read_file(name); + }); + } else { + await new Promise((resolve) => { + var chunks = []; + process.stdin.setEncoding("utf8"); + process.stdin.on("data", function(chunk) { + chunks.push(chunk); + }).on("end", function() { + files = [ chunks.join("") ]; + resolve(); + }); + process.stdin.resume(); + }); + } + + await run_cli(); + + function convert_ast(fn) { + return AST_Node.from_mozilla_ast(Object.keys(files).reduce(fn, null)); + } + + async function run_cli() { + var content = program.sourceMap && program.sourceMap.content; + if (content && content !== "inline") { + options.sourceMap.content = read_file(content, content); + } + if (program.timings) options.timings = true; + + try { + if (program.parse) { + if (program.parse.acorn) { + files = convert_ast(function(toplevel, name) { + return require("acorn").parse(files[name], { + ecmaVersion: 2018, + locations: true, + program: toplevel, + sourceFile: name, + sourceType: options.module || program.parse.module ? "module" : "script" + }); + }); + } else if (program.parse.spidermonkey) { + files = convert_ast(function(toplevel, name) { + var obj = JSON.parse(files[name]); + if (!toplevel) return obj; + toplevel.body = toplevel.body.concat(obj.body); + return toplevel; + }); + } + } + } catch (ex) { + fatal(ex); + } + + let result; + try { + result = await minify(files, options, fs); + } catch (ex) { + if (ex.name == "SyntaxError") { + print_error("Parse error at " + ex.filename + ":" + ex.line + "," + ex.col); + var col = ex.col; + var lines = files[ex.filename].split(/\r?\n/); + var line = lines[ex.line - 1]; + if (!line && !col) { + line = lines[ex.line - 2]; + col = line.length; + } + if (line) { + var limit = 70; + if (col > limit) { + line = line.slice(col - limit); + col = limit; + } + print_error(line.slice(0, 80)); + print_error(line.slice(0, col).replace(/\S/g, " ") + "^"); + } + } + if (ex.defs) { + print_error("Supported options:"); + print_error(format_object(ex.defs)); + } + fatal(ex); + return; + } + + if (program.output == "ast") { + if (!options.compress && !options.mangle) { + result.ast.figure_out_scope({}); + } + console.log(JSON.stringify(result.ast, function(key, value) { + if (value) switch (key) { + case "thedef": + return symdef(value); + case "enclosed": + return value.length ? value.map(symdef) : undefined; + case "variables": + case "globals": + return value.size ? collect_from_map(value, symdef) : undefined; + } + if (skip_keys.has(key)) return; + if (value instanceof AST_Token) return; + if (value instanceof Map) return; + if (value instanceof AST_Node) { + var result = { + _class: "AST_" + value.TYPE + }; + if (value.block_scope) { + result.variables = value.block_scope.variables; + result.enclosed = value.block_scope.enclosed; + } + value.CTOR.PROPS.forEach(function(prop) { + if (prop !== "block_scope") { + result[prop] = value[prop]; + } + }); + return result; + } + return value; + }, 2)); + } else if (program.output == "spidermonkey") { + try { + const minified = await minify( + result.code, + { + compress: false, + mangle: false, + format: { + ast: true, + code: false + } + }, + fs + ); + console.log(JSON.stringify(minified.ast.to_mozilla_ast(), null, 2)); + } catch (ex) { + fatal(ex); + return; + } + } else if (program.output) { + fs.writeFileSync(program.output, result.code); + if (options.sourceMap && options.sourceMap.url !== "inline" && result.map) { + fs.writeFileSync(program.output + ".map", result.map); + } + } else { + console.log(result.code); + } + if (program.nameCache) { + fs.writeFileSync(program.nameCache, JSON.stringify(options.nameCache)); + } + if (result.timings) for (var phase in result.timings) { + print_error("- " + phase + ": " + result.timings[phase].toFixed(3) + "s"); + } + } + + function fatal(message) { + if (message instanceof Error) message = message.stack.replace(/^\S*?Error:/, "ERROR:"); + print_error(message); + process.exit(1); + } + + // A file glob function that only supports "*" and "?" wildcards in the basename. + // Example: "foo/bar/*baz??.*.js" + // Argument `glob` may be a string or an array of strings. + // Returns an array of strings. Garbage in, garbage out. + function simple_glob(glob) { + if (Array.isArray(glob)) { + return [].concat.apply([], glob.map(simple_glob)); + } + if (glob && glob.match(/[*?]/)) { + var dir = path.dirname(glob); + try { + var entries = fs.readdirSync(dir); + } catch (ex) {} + if (entries) { + var pattern = "^" + path.basename(glob) + .replace(/[.+^$[\]\\(){}]/g, "\\$&") + .replace(/\*/g, "[^/\\\\]*") + .replace(/\?/g, "[^/\\\\]") + "$"; + var mod = process.platform === "win32" ? "i" : ""; + var rx = new RegExp(pattern, mod); + var results = entries.filter(function(name) { + return rx.test(name); + }).map(function(name) { + return path.join(dir, name); + }); + if (results.length) return results; + } + } + return [ glob ]; + } + + function read_file(path, default_value) { + try { + return fs.readFileSync(path, "utf8"); + } catch (ex) { + if ((ex.code == "ENOENT" || ex.code == "ENAMETOOLONG") && default_value != null) return default_value; + fatal(ex); + } + } + + function parse_js(flag) { + return function(value, options) { + options = options || {}; + try { + walk(parse(value, { expression: true }), node => { + if (node instanceof AST_Assign) { + var name = node.left.print_to_string(); + var value = node.right; + if (flag) { + options[name] = value; + } else if (value instanceof AST_Array) { + options[name] = value.elements.map(to_string); + } else if (value instanceof AST_RegExp) { + value = value.value; + options[name] = new RegExp(value.source, value.flags); + } else { + options[name] = to_string(value); + } + return true; + } + if (node instanceof AST_Symbol || node instanceof AST_PropAccess) { + var name = node.print_to_string(); + options[name] = true; + return true; + } + if (!(node instanceof AST_Sequence)) throw node; + + function to_string(value) { + return value instanceof AST_Constant ? value.getValue() : value.print_to_string({ + quote_keys: true + }); + } + }); + } catch(ex) { + if (flag) { + fatal("Error parsing arguments for '" + flag + "': " + value); + } else { + options[value] = null; + } + } + return options; + }; + } + + function symdef(def) { + var ret = (1e6 + def.id) + " " + def.name; + if (def.mangled_name) ret += " " + def.mangled_name; + return ret; + } + + function collect_from_map(map, callback) { + var result = []; + map.forEach(function (def) { + result.push(callback(def)); + }); + return result; + } + + function format_object(obj) { + var lines = []; + var padding = ""; + Object.keys(obj).map(function(name) { + if (padding.length < name.length) padding = Array(name.length + 1).join(" "); + return [ name, JSON.stringify(obj[name]) ]; + }).forEach(function(tokens) { + lines.push(" " + tokens[0] + padding.slice(tokens[0].length - 2) + tokens[1]); + }); + return lines.join("\n"); + } + + function print_error(msg) { + process.stderr.write(msg); + process.stderr.write("\n"); + } + + function describe_ast() { + var out = OutputStream({ beautify: true }); + function doitem(ctor) { + out.print("AST_" + ctor.TYPE); + const props = ctor.SELF_PROPS.filter(prop => !/^\$/.test(prop)); + + if (props.length > 0) { + out.space(); + out.with_parens(function() { + props.forEach(function(prop, i) { + if (i) out.space(); + out.print(prop); + }); + }); + } + + if (ctor.documentation) { + out.space(); + out.print_string(ctor.documentation); + } + + if (ctor.SUBCLASSES.length > 0) { + out.space(); + out.with_block(function() { + ctor.SUBCLASSES.forEach(function(ctor) { + out.indent(); + doitem(ctor); + out.newline(); + }); + }); + } + } + doitem(AST_Node); + return out + "\n"; + } +} + +async function _default_options() { + const defs = {}; + + Object.keys(infer_options({ 0: 0 })).forEach((component) => { + const options = infer_options({ + [component]: {0: 0} + }); + + if (options) defs[component] = options; + }); + return defs; +} + +async function infer_options(options) { + try { + await minify("", options); + } catch (error) { + return error.defs; + } +} + +exports._default_options = _default_options; +exports._run_cli = run_cli; +exports.minify = minify; +exports.minify_sync = minify_sync; + +}))); diff --git a/node_modules/terser/dist/package.json b/node_modules/terser/dist/package.json new file mode 100644 index 0000000..a4cb7d1 --- /dev/null +++ b/node_modules/terser/dist/package.json @@ -0,0 +1,10 @@ +{ + "name": "dist", + "private": true, + "version": "1.0.0", + "main": "bundle.min.js", + "type": "commonjs", + "author": "", + "license": "BSD-2-Clause", + "description": "A package to hold the Terser dist bundle as commonjs while keeping the rest of it ESM. Nothing to see here." +} diff --git a/node_modules/terser/lib/ast.js b/node_modules/terser/lib/ast.js new file mode 100644 index 0000000..9f6ff9a --- /dev/null +++ b/node_modules/terser/lib/ast.js @@ -0,0 +1,3357 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { + HOP, + MAP, + noop +} from "./utils/index.js"; +import { parse } from "./parse.js"; + +function DEFNODE(type, props, ctor, methods, base = AST_Node) { + if (!props) props = []; + else props = props.split(/\s+/); + var self_props = props; + if (base && base.PROPS) + props = props.concat(base.PROPS); + const proto = base && Object.create(base.prototype); + if (proto) { + ctor.prototype = proto; + ctor.BASE = base; + } + if (base) base.SUBCLASSES.push(ctor); + ctor.prototype.CTOR = ctor; + ctor.prototype.constructor = ctor; + ctor.PROPS = props || null; + ctor.SELF_PROPS = self_props; + ctor.SUBCLASSES = []; + if (type) { + ctor.prototype.TYPE = ctor.TYPE = type; + } + if (methods) for (let i in methods) if (HOP(methods, i)) { + if (i[0] === "$") { + ctor[i.substr(1)] = methods[i]; + } else { + ctor.prototype[i] = methods[i]; + } + } + ctor.DEFMETHOD = function(name, method) { + this.prototype[name] = method; + }; + return ctor; +} + +const has_tok_flag = (tok, flag) => Boolean(tok.flags & flag); +const set_tok_flag = (tok, flag, truth) => { + if (truth) { + tok.flags |= flag; + } else { + tok.flags &= ~flag; + } +}; + +const TOK_FLAG_NLB = 0b0001; +const TOK_FLAG_QUOTE_SINGLE = 0b0010; +const TOK_FLAG_QUOTE_EXISTS = 0b0100; +const TOK_FLAG_TEMPLATE_END = 0b1000; + +class AST_Token { + constructor(type, value, line, col, pos, nlb, comments_before, comments_after, file) { + this.flags = (nlb ? 1 : 0); + + this.type = type; + this.value = value; + this.line = line; + this.col = col; + this.pos = pos; + this.comments_before = comments_before; + this.comments_after = comments_after; + this.file = file; + + Object.seal(this); + } + + // Return a string summary of the token for node.js console.log + [Symbol.for("nodejs.util.inspect.custom")](_depth, options) { + const special = str => options.stylize(str, "special"); + const quote = typeof this.value === "string" && this.value.includes("`") ? "'" : "`"; + const value = `${quote}${this.value}${quote}`; + return `${special("[AST_Token")} ${value} at ${this.line}:${this.col}${special("]")}`; + } + + get nlb() { + return has_tok_flag(this, TOK_FLAG_NLB); + } + + set nlb(new_nlb) { + set_tok_flag(this, TOK_FLAG_NLB, new_nlb); + } + + get quote() { + return !has_tok_flag(this, TOK_FLAG_QUOTE_EXISTS) + ? "" + : (has_tok_flag(this, TOK_FLAG_QUOTE_SINGLE) ? "'" : '"'); + } + + set quote(quote_type) { + set_tok_flag(this, TOK_FLAG_QUOTE_SINGLE, quote_type === "'"); + set_tok_flag(this, TOK_FLAG_QUOTE_EXISTS, !!quote_type); + } + + get template_end() { + return has_tok_flag(this, TOK_FLAG_TEMPLATE_END); + } + + set template_end(new_template_end) { + set_tok_flag(this, TOK_FLAG_TEMPLATE_END, new_template_end); + } +} + +var AST_Node = DEFNODE("Node", "start end", function AST_Node(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + _clone: function(deep) { + if (deep) { + var self = this.clone(); + return self.transform(new TreeTransformer(function(node) { + if (node !== self) { + return node.clone(true); + } + })); + } + return new this.CTOR(this); + }, + clone: function(deep) { + return this._clone(deep); + }, + $documentation: "Base class of all AST nodes", + $propdoc: { + start: "[AST_Token] The first token of this node", + end: "[AST_Token] The last token of this node" + }, + _walk: function(visitor) { + return visitor._visit(this); + }, + walk: function(visitor) { + return this._walk(visitor); // not sure the indirection will be any help + }, + _children_backwards: () => {} +}, null); + +/* -----[ statements ]----- */ + +var AST_Statement = DEFNODE("Statement", null, function AST_Statement(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class of all statements", +}); + +var AST_Debugger = DEFNODE("Debugger", null, function AST_Debugger(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Represents a debugger statement", +}, AST_Statement); + +var AST_Directive = DEFNODE("Directive", "value quote", function AST_Directive(props) { + if (props) { + this.value = props.value; + this.quote = props.quote; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Represents a directive, like \"use strict\";", + $propdoc: { + value: "[string] The value of this directive as a plain string (it's not an AST_String!)", + quote: "[string] the original quote character" + }, +}, AST_Statement); + +var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", function AST_SimpleStatement(props) { + if (props) { + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A statement consisting of an expression, i.e. a = 1 + 2", + $propdoc: { + body: "[AST_Node] an expression node (should not be instanceof AST_Statement)" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + } +}, AST_Statement); + +function walk_body(node, visitor) { + const body = node.body; + for (var i = 0, len = body.length; i < len; i++) { + body[i]._walk(visitor); + } +} + +function clone_block_scope(deep) { + var clone = this._clone(deep); + if (this.block_scope) { + clone.block_scope = this.block_scope.clone(); + } + return clone; +} + +var AST_Block = DEFNODE("Block", "body block_scope", function AST_Block(props) { + if (props) { + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A body of statements (usually braced)", + $propdoc: { + body: "[AST_Statement*] an array of statements", + block_scope: "[AST_Scope] the block scope" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + }, + clone: clone_block_scope +}, AST_Statement); + +var AST_BlockStatement = DEFNODE("BlockStatement", null, function AST_BlockStatement(props) { + if (props) { + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A block statement", +}, AST_Block); + +var AST_EmptyStatement = DEFNODE("EmptyStatement", null, function AST_EmptyStatement(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The empty statement (empty block or simply a semicolon)" +}, AST_Statement); + +var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", function AST_StatementWithBody(props) { + if (props) { + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`", + $propdoc: { + body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement" + } +}, AST_Statement); + +var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", function AST_LabeledStatement(props) { + if (props) { + this.label = props.label; + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Statement with a label", + $propdoc: { + label: "[AST_Label] a label definition" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.label._walk(visitor); + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + push(this.label); + }, + clone: function(deep) { + var node = this._clone(deep); + if (deep) { + var label = node.label; + var def = this.label; + node.walk(new TreeWalker(function(node) { + if (node instanceof AST_LoopControl + && node.label && node.label.thedef === def) { + node.label.thedef = label; + label.references.push(node); + } + })); + } + return node; + } +}, AST_StatementWithBody); + +var AST_IterationStatement = DEFNODE( + "IterationStatement", + "block_scope", + function AST_IterationStatement(props) { + if (props) { + this.block_scope = props.block_scope; + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; + }, + { + $documentation: "Internal class. All loops inherit from it.", + $propdoc: { + block_scope: "[AST_Scope] the block scope for this iteration statement." + }, + clone: clone_block_scope + }, + AST_StatementWithBody +); + +var AST_DWLoop = DEFNODE("DWLoop", "condition", function AST_DWLoop(props) { + if (props) { + this.condition = props.condition; + this.block_scope = props.block_scope; + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for do/while statements", + $propdoc: { + condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement" + } +}, AST_IterationStatement); + +var AST_Do = DEFNODE("Do", null, function AST_Do(props) { + if (props) { + this.condition = props.condition; + this.block_scope = props.block_scope; + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `do` statement", + _walk: function(visitor) { + return visitor._visit(this, function() { + this.body._walk(visitor); + this.condition._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.condition); + push(this.body); + } +}, AST_DWLoop); + +var AST_While = DEFNODE("While", null, function AST_While(props) { + if (props) { + this.condition = props.condition; + this.block_scope = props.block_scope; + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `while` statement", + _walk: function(visitor) { + return visitor._visit(this, function() { + this.condition._walk(visitor); + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + push(this.condition); + }, +}, AST_DWLoop); + +var AST_For = DEFNODE("For", "init condition step", function AST_For(props) { + if (props) { + this.init = props.init; + this.condition = props.condition; + this.step = props.step; + this.block_scope = props.block_scope; + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `for` statement", + $propdoc: { + init: "[AST_Node?] the `for` initialization code, or null if empty", + condition: "[AST_Node?] the `for` termination clause, or null if empty", + step: "[AST_Node?] the `for` update clause, or null if empty" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.init) this.init._walk(visitor); + if (this.condition) this.condition._walk(visitor); + if (this.step) this.step._walk(visitor); + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + if (this.step) push(this.step); + if (this.condition) push(this.condition); + if (this.init) push(this.init); + }, +}, AST_IterationStatement); + +var AST_ForIn = DEFNODE("ForIn", "init object", function AST_ForIn(props) { + if (props) { + this.init = props.init; + this.object = props.object; + this.block_scope = props.block_scope; + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `for ... in` statement", + $propdoc: { + init: "[AST_Node] the `for/in` initialization code", + object: "[AST_Node] the object that we're looping through" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.init._walk(visitor); + this.object._walk(visitor); + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + if (this.object) push(this.object); + if (this.init) push(this.init); + }, +}, AST_IterationStatement); + +var AST_ForOf = DEFNODE("ForOf", "await", function AST_ForOf(props) { + if (props) { + this.await = props.await; + this.init = props.init; + this.object = props.object; + this.block_scope = props.block_scope; + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `for ... of` statement", +}, AST_ForIn); + +var AST_With = DEFNODE("With", "expression", function AST_With(props) { + if (props) { + this.expression = props.expression; + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `with` statement", + $propdoc: { + expression: "[AST_Node] the `with` expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + this.body._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.body); + push(this.expression); + }, +}, AST_StatementWithBody); + +/* -----[ scope and functions ]----- */ + +var AST_Scope = DEFNODE( + "Scope", + "variables uses_with uses_eval parent_scope enclosed cname", + function AST_Scope(props) { + if (props) { + this.variables = props.variables; + this.uses_with = props.uses_with; + this.uses_eval = props.uses_eval; + this.parent_scope = props.parent_scope; + this.enclosed = props.enclosed; + this.cname = props.cname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; + }, + { + $documentation: "Base class for all statements introducing a lexical scope", + $propdoc: { + variables: "[Map/S] a map of name -> SymbolDef for all variables/functions defined in this scope", + uses_with: "[boolean/S] tells whether this scope uses the `with` statement", + uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`", + parent_scope: "[AST_Scope?/S] link to the parent scope", + enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes", + cname: "[integer/S] current index for mangling variables (used internally by the mangler)", + }, + get_defun_scope: function() { + var self = this; + while (self.is_block_scope()) { + self = self.parent_scope; + } + return self; + }, + clone: function(deep, toplevel) { + var node = this._clone(deep); + if (deep && this.variables && toplevel && !this._block_scope) { + node.figure_out_scope({}, { + toplevel: toplevel, + parent_scope: this.parent_scope + }); + } else { + if (this.variables) node.variables = new Map(this.variables); + if (this.enclosed) node.enclosed = this.enclosed.slice(); + if (this._block_scope) node._block_scope = this._block_scope; + } + return node; + }, + pinned: function() { + return this.uses_eval || this.uses_with; + } + }, + AST_Block +); + +var AST_Toplevel = DEFNODE("Toplevel", "globals", function AST_Toplevel(props) { + if (props) { + this.globals = props.globals; + this.variables = props.variables; + this.uses_with = props.uses_with; + this.uses_eval = props.uses_eval; + this.parent_scope = props.parent_scope; + this.enclosed = props.enclosed; + this.cname = props.cname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The toplevel scope", + $propdoc: { + globals: "[Map/S] a map of name -> SymbolDef for all undeclared names", + }, + wrap_commonjs: function(name) { + var body = this.body; + var wrapped_tl = "(function(exports){'$ORIG';})(typeof " + name + "=='undefined'?(" + name + "={}):" + name + ");"; + wrapped_tl = parse(wrapped_tl); + wrapped_tl = wrapped_tl.transform(new TreeTransformer(function(node) { + if (node instanceof AST_Directive && node.value == "$ORIG") { + return MAP.splice(body); + } + })); + return wrapped_tl; + }, + wrap_enclose: function(args_values) { + if (typeof args_values != "string") args_values = ""; + var index = args_values.indexOf(":"); + if (index < 0) index = args_values.length; + var body = this.body; + return parse([ + "(function(", + args_values.slice(0, index), + '){"$ORIG"})(', + args_values.slice(index + 1), + ")" + ].join("")).transform(new TreeTransformer(function(node) { + if (node instanceof AST_Directive && node.value == "$ORIG") { + return MAP.splice(body); + } + })); + } +}, AST_Scope); + +var AST_Expansion = DEFNODE("Expansion", "expression", function AST_Expansion(props) { + if (props) { + this.expression = props.expression; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "An expandible argument, such as ...rest, a splat, such as [1,2,...all], or an expansion in a variable declaration, such as var [first, ...rest] = list", + $propdoc: { + expression: "[AST_Node] the thing to be expanded" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression.walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}); + +var AST_Lambda = DEFNODE( + "Lambda", + "name argnames uses_arguments is_generator async", + function AST_Lambda(props) { + if (props) { + this.name = props.name; + this.argnames = props.argnames; + this.uses_arguments = props.uses_arguments; + this.is_generator = props.is_generator; + this.async = props.async; + this.variables = props.variables; + this.uses_with = props.uses_with; + this.uses_eval = props.uses_eval; + this.parent_scope = props.parent_scope; + this.enclosed = props.enclosed; + this.cname = props.cname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; + }, + { + $documentation: "Base class for functions", + $propdoc: { + name: "[AST_SymbolDeclaration?] the name of this function", + argnames: "[AST_SymbolFunarg|AST_Destructuring|AST_Expansion|AST_DefaultAssign*] array of function arguments, destructurings, or expanding arguments", + uses_arguments: "[boolean/S] tells whether this function accesses the arguments array", + is_generator: "[boolean] is this a generator method", + async: "[boolean] is this method async", + }, + args_as_names: function () { + var out = []; + for (var i = 0; i < this.argnames.length; i++) { + if (this.argnames[i] instanceof AST_Destructuring) { + out.push(...this.argnames[i].all_symbols()); + } else { + out.push(this.argnames[i]); + } + } + return out; + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.name) this.name._walk(visitor); + var argnames = this.argnames; + for (var i = 0, len = argnames.length; i < len; i++) { + argnames[i]._walk(visitor); + } + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + + i = this.argnames.length; + while (i--) push(this.argnames[i]); + + if (this.name) push(this.name); + }, + is_braceless() { + return this.body[0] instanceof AST_Return && this.body[0].value; + }, + // Default args and expansion don't count, so .argnames.length doesn't cut it + length_property() { + let length = 0; + + for (const arg of this.argnames) { + if (arg instanceof AST_SymbolFunarg || arg instanceof AST_Destructuring) { + length++; + } + } + + return length; + } + }, + AST_Scope +); + +var AST_Accessor = DEFNODE("Accessor", null, function AST_Accessor(props) { + if (props) { + this.name = props.name; + this.argnames = props.argnames; + this.uses_arguments = props.uses_arguments; + this.is_generator = props.is_generator; + this.async = props.async; + this.variables = props.variables; + this.uses_with = props.uses_with; + this.uses_eval = props.uses_eval; + this.parent_scope = props.parent_scope; + this.enclosed = props.enclosed; + this.cname = props.cname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A setter/getter function. The `name` property is always null." +}, AST_Lambda); + +var AST_Function = DEFNODE("Function", null, function AST_Function(props) { + if (props) { + this.name = props.name; + this.argnames = props.argnames; + this.uses_arguments = props.uses_arguments; + this.is_generator = props.is_generator; + this.async = props.async; + this.variables = props.variables; + this.uses_with = props.uses_with; + this.uses_eval = props.uses_eval; + this.parent_scope = props.parent_scope; + this.enclosed = props.enclosed; + this.cname = props.cname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A function expression" +}, AST_Lambda); + +var AST_Arrow = DEFNODE("Arrow", null, function AST_Arrow(props) { + if (props) { + this.name = props.name; + this.argnames = props.argnames; + this.uses_arguments = props.uses_arguments; + this.is_generator = props.is_generator; + this.async = props.async; + this.variables = props.variables; + this.uses_with = props.uses_with; + this.uses_eval = props.uses_eval; + this.parent_scope = props.parent_scope; + this.enclosed = props.enclosed; + this.cname = props.cname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "An ES6 Arrow function ((a) => b)" +}, AST_Lambda); + +var AST_Defun = DEFNODE("Defun", null, function AST_Defun(props) { + if (props) { + this.name = props.name; + this.argnames = props.argnames; + this.uses_arguments = props.uses_arguments; + this.is_generator = props.is_generator; + this.async = props.async; + this.variables = props.variables; + this.uses_with = props.uses_with; + this.uses_eval = props.uses_eval; + this.parent_scope = props.parent_scope; + this.enclosed = props.enclosed; + this.cname = props.cname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A function definition" +}, AST_Lambda); + +/* -----[ DESTRUCTURING ]----- */ +var AST_Destructuring = DEFNODE("Destructuring", "names is_array", function AST_Destructuring(props) { + if (props) { + this.names = props.names; + this.is_array = props.is_array; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A destructuring of several names. Used in destructuring assignment and with destructuring function argument names", + $propdoc: { + "names": "[AST_Node*] Array of properties or elements", + "is_array": "[Boolean] Whether the destructuring represents an object or array" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.names.forEach(function(name) { + name._walk(visitor); + }); + }); + }, + _children_backwards(push) { + let i = this.names.length; + while (i--) push(this.names[i]); + }, + all_symbols: function() { + var out = []; + walk(this, node => { + if (node instanceof AST_SymbolDeclaration) { + out.push(node); + } + if (node instanceof AST_Lambda) { + return true; + } + }); + return out; + } +}); + +var AST_PrefixedTemplateString = DEFNODE( + "PrefixedTemplateString", + "template_string prefix", + function AST_PrefixedTemplateString(props) { + if (props) { + this.template_string = props.template_string; + this.prefix = props.prefix; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; + }, + { + $documentation: "A templatestring with a prefix, such as String.raw`foobarbaz`", + $propdoc: { + template_string: "[AST_TemplateString] The template string", + prefix: "[AST_Node] The prefix, which will get called." + }, + _walk: function(visitor) { + return visitor._visit(this, function () { + this.prefix._walk(visitor); + this.template_string._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.template_string); + push(this.prefix); + }, + } +); + +var AST_TemplateString = DEFNODE("TemplateString", "segments", function AST_TemplateString(props) { + if (props) { + this.segments = props.segments; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A template string literal", + $propdoc: { + segments: "[AST_Node*] One or more segments, starting with AST_TemplateSegment. AST_Node may follow AST_TemplateSegment, but each AST_Node must be followed by AST_TemplateSegment." + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.segments.forEach(function(seg) { + seg._walk(visitor); + }); + }); + }, + _children_backwards(push) { + let i = this.segments.length; + while (i--) push(this.segments[i]); + } +}); + +var AST_TemplateSegment = DEFNODE("TemplateSegment", "value raw", function AST_TemplateSegment(props) { + if (props) { + this.value = props.value; + this.raw = props.raw; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A segment of a template string literal", + $propdoc: { + value: "Content of the segment", + raw: "Raw source of the segment", + } +}); + +/* -----[ JUMPS ]----- */ + +var AST_Jump = DEFNODE("Jump", null, function AST_Jump(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)" +}, AST_Statement); + +/** Base class for “exits” (`return` and `throw`) */ +var AST_Exit = DEFNODE("Exit", "value", function AST_Exit(props) { + if (props) { + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for “exits” (`return` and `throw`)", + $propdoc: { + value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return" + }, + _walk: function(visitor) { + return visitor._visit(this, this.value && function() { + this.value._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.value) push(this.value); + }, +}, AST_Jump); + +var AST_Return = DEFNODE("Return", null, function AST_Return(props) { + if (props) { + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `return` statement" +}, AST_Exit); + +var AST_Throw = DEFNODE("Throw", null, function AST_Throw(props) { + if (props) { + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `throw` statement" +}, AST_Exit); + +var AST_LoopControl = DEFNODE("LoopControl", "label", function AST_LoopControl(props) { + if (props) { + this.label = props.label; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for loop control statements (`break` and `continue`)", + $propdoc: { + label: "[AST_LabelRef?] the label, or null if none", + }, + _walk: function(visitor) { + return visitor._visit(this, this.label && function() { + this.label._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.label) push(this.label); + }, +}, AST_Jump); + +var AST_Break = DEFNODE("Break", null, function AST_Break(props) { + if (props) { + this.label = props.label; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `break` statement" +}, AST_LoopControl); + +var AST_Continue = DEFNODE("Continue", null, function AST_Continue(props) { + if (props) { + this.label = props.label; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `continue` statement" +}, AST_LoopControl); + +var AST_Await = DEFNODE("Await", "expression", function AST_Await(props) { + if (props) { + this.expression = props.expression; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "An `await` statement", + $propdoc: { + expression: "[AST_Node] the mandatory expression being awaited", + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}); + +var AST_Yield = DEFNODE("Yield", "expression is_star", function AST_Yield(props) { + if (props) { + this.expression = props.expression; + this.is_star = props.is_star; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `yield` statement", + $propdoc: { + expression: "[AST_Node?] the value returned or thrown by this statement; could be null (representing undefined) but only when is_star is set to false", + is_star: "[Boolean] Whether this is a yield or yield* statement" + }, + _walk: function(visitor) { + return visitor._visit(this, this.expression && function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.expression) push(this.expression); + } +}); + +/* -----[ IF ]----- */ + +var AST_If = DEFNODE("If", "condition alternative", function AST_If(props) { + if (props) { + this.condition = props.condition; + this.alternative = props.alternative; + this.body = props.body; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `if` statement", + $propdoc: { + condition: "[AST_Node] the `if` condition", + alternative: "[AST_Statement?] the `else` part, or null if not present" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.condition._walk(visitor); + this.body._walk(visitor); + if (this.alternative) this.alternative._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.alternative) { + push(this.alternative); + } + push(this.body); + push(this.condition); + } +}, AST_StatementWithBody); + +/* -----[ SWITCH ]----- */ + +var AST_Switch = DEFNODE("Switch", "expression", function AST_Switch(props) { + if (props) { + this.expression = props.expression; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `switch` statement", + $propdoc: { + expression: "[AST_Node] the `switch` “discriminant”" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + push(this.expression); + } +}, AST_Block); + +var AST_SwitchBranch = DEFNODE("SwitchBranch", null, function AST_SwitchBranch(props) { + if (props) { + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for `switch` branches", +}, AST_Block); + +var AST_Default = DEFNODE("Default", null, function AST_Default(props) { + if (props) { + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `default` switch branch", +}, AST_SwitchBranch); + +var AST_Case = DEFNODE("Case", "expression", function AST_Case(props) { + if (props) { + this.expression = props.expression; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `case` switch branch", + $propdoc: { + expression: "[AST_Node] the `case` expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + push(this.expression); + }, +}, AST_SwitchBranch); + +/* -----[ EXCEPTIONS ]----- */ + +var AST_Try = DEFNODE("Try", "body bcatch bfinally", function AST_Try(props) { + if (props) { + this.body = props.body; + this.bcatch = props.bcatch; + this.bfinally = props.bfinally; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `try` statement", + $propdoc: { + body: "[AST_TryBlock] the try block", + bcatch: "[AST_Catch?] the catch block, or null if not present", + bfinally: "[AST_Finally?] the finally block, or null if not present" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.body._walk(visitor); + if (this.bcatch) this.bcatch._walk(visitor); + if (this.bfinally) this.bfinally._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.bfinally) push(this.bfinally); + if (this.bcatch) push(this.bcatch); + push(this.body); + }, +}, AST_Statement); + +var AST_TryBlock = DEFNODE("TryBlock", null, function AST_TryBlock(props) { + if (props) { + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The `try` block of a try statement" +}, AST_Block); + +var AST_Catch = DEFNODE("Catch", "argname", function AST_Catch(props) { + if (props) { + this.argname = props.argname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `catch` node; only makes sense as part of a `try` statement", + $propdoc: { + argname: "[AST_SymbolCatch|AST_Destructuring|AST_Expansion|AST_DefaultAssign] symbol for the exception" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.argname) this.argname._walk(visitor); + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + if (this.argname) push(this.argname); + }, +}, AST_Block); + +var AST_Finally = DEFNODE("Finally", null, function AST_Finally(props) { + if (props) { + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `finally` node; only makes sense as part of a `try` statement" +}, AST_Block); + +/* -----[ VAR/CONST ]----- */ + +var AST_Definitions = DEFNODE("Definitions", "definitions", function AST_Definitions(props) { + if (props) { + this.definitions = props.definitions; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)", + $propdoc: { + definitions: "[AST_VarDef*] array of variable definitions" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + var definitions = this.definitions; + for (var i = 0, len = definitions.length; i < len; i++) { + definitions[i]._walk(visitor); + } + }); + }, + _children_backwards(push) { + let i = this.definitions.length; + while (i--) push(this.definitions[i]); + }, +}, AST_Statement); + +var AST_Var = DEFNODE("Var", null, function AST_Var(props) { + if (props) { + this.definitions = props.definitions; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `var` statement" +}, AST_Definitions); + +var AST_Let = DEFNODE("Let", null, function AST_Let(props) { + if (props) { + this.definitions = props.definitions; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `let` statement" +}, AST_Definitions); + +var AST_Const = DEFNODE("Const", null, function AST_Const(props) { + if (props) { + this.definitions = props.definitions; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A `const` statement" +}, AST_Definitions); + +var AST_VarDef = DEFNODE("VarDef", "name value", function AST_VarDef(props) { + if (props) { + this.name = props.name; + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A variable declaration; only appears in a AST_Definitions node", + $propdoc: { + name: "[AST_Destructuring|AST_SymbolConst|AST_SymbolLet|AST_SymbolVar] name of the variable", + value: "[AST_Node?] initializer, or null of there's no initializer" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.name._walk(visitor); + if (this.value) this.value._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.value) push(this.value); + push(this.name); + }, + declarations_as_names() { + if (this.name instanceof AST_SymbolDeclaration) { + return [this]; + } else { + return this.name.all_symbols(); + } + } +}); + +var AST_NameMapping = DEFNODE("NameMapping", "foreign_name name", function AST_NameMapping(props) { + if (props) { + this.foreign_name = props.foreign_name; + this.name = props.name; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The part of the export/import statement that declare names from a module.", + $propdoc: { + foreign_name: "[AST_SymbolExportForeign|AST_SymbolImportForeign] The name being exported/imported (as specified in the module)", + name: "[AST_SymbolExport|AST_SymbolImport] The name as it is visible to this module." + }, + _walk: function (visitor) { + return visitor._visit(this, function() { + this.foreign_name._walk(visitor); + this.name._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.name); + push(this.foreign_name); + }, +}); + +var AST_Import = DEFNODE( + "Import", + "imported_name imported_names module_name assert_clause", + function AST_Import(props) { + if (props) { + this.imported_name = props.imported_name; + this.imported_names = props.imported_names; + this.module_name = props.module_name; + this.assert_clause = props.assert_clause; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; + }, + { + $documentation: "An `import` statement", + $propdoc: { + imported_name: "[AST_SymbolImport] The name of the variable holding the module's default export.", + imported_names: "[AST_NameMapping*] The names of non-default imported variables", + module_name: "[AST_String] String literal describing where this module came from", + assert_clause: "[AST_Object?] The import assertion" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.imported_name) { + this.imported_name._walk(visitor); + } + if (this.imported_names) { + this.imported_names.forEach(function(name_import) { + name_import._walk(visitor); + }); + } + this.module_name._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.module_name); + if (this.imported_names) { + let i = this.imported_names.length; + while (i--) push(this.imported_names[i]); + } + if (this.imported_name) push(this.imported_name); + }, + } +); + +var AST_ImportMeta = DEFNODE("ImportMeta", null, function AST_ImportMeta(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A reference to import.meta", +}); + +var AST_Export = DEFNODE( + "Export", + "exported_definition exported_value is_default exported_names module_name assert_clause", + function AST_Export(props) { + if (props) { + this.exported_definition = props.exported_definition; + this.exported_value = props.exported_value; + this.is_default = props.is_default; + this.exported_names = props.exported_names; + this.module_name = props.module_name; + this.assert_clause = props.assert_clause; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; + }, + { + $documentation: "An `export` statement", + $propdoc: { + exported_definition: "[AST_Defun|AST_Definitions|AST_DefClass?] An exported definition", + exported_value: "[AST_Node?] An exported value", + exported_names: "[AST_NameMapping*?] List of exported names", + module_name: "[AST_String?] Name of the file to load exports from", + is_default: "[Boolean] Whether this is the default exported value of this module", + assert_clause: "[AST_Object?] The import assertion" + }, + _walk: function (visitor) { + return visitor._visit(this, function () { + if (this.exported_definition) { + this.exported_definition._walk(visitor); + } + if (this.exported_value) { + this.exported_value._walk(visitor); + } + if (this.exported_names) { + this.exported_names.forEach(function(name_export) { + name_export._walk(visitor); + }); + } + if (this.module_name) { + this.module_name._walk(visitor); + } + }); + }, + _children_backwards(push) { + if (this.module_name) push(this.module_name); + if (this.exported_names) { + let i = this.exported_names.length; + while (i--) push(this.exported_names[i]); + } + if (this.exported_value) push(this.exported_value); + if (this.exported_definition) push(this.exported_definition); + } + }, + AST_Statement +); + +/* -----[ OTHER ]----- */ + +var AST_Call = DEFNODE( + "Call", + "expression args optional _annotations", + function AST_Call(props) { + if (props) { + this.expression = props.expression; + this.args = props.args; + this.optional = props.optional; + this._annotations = props._annotations; + this.start = props.start; + this.end = props.end; + this.initialize(); + } + + this.flags = 0; + }, + { + $documentation: "A function call expression", + $propdoc: { + expression: "[AST_Node] expression to invoke as function", + args: "[AST_Node*] array of arguments", + optional: "[boolean] whether this is an optional call (IE ?.() )", + _annotations: "[number] bitfield containing information about the call" + }, + initialize() { + if (this._annotations == null) this._annotations = 0; + }, + _walk(visitor) { + return visitor._visit(this, function() { + var args = this.args; + for (var i = 0, len = args.length; i < len; i++) { + args[i]._walk(visitor); + } + this.expression._walk(visitor); // TODO why do we need to crawl this last? + }); + }, + _children_backwards(push) { + let i = this.args.length; + while (i--) push(this.args[i]); + push(this.expression); + }, + } +); + +var AST_New = DEFNODE("New", null, function AST_New(props) { + if (props) { + this.expression = props.expression; + this.args = props.args; + this.optional = props.optional; + this._annotations = props._annotations; + this.start = props.start; + this.end = props.end; + this.initialize(); + } + + this.flags = 0; +}, { + $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties" +}, AST_Call); + +var AST_Sequence = DEFNODE("Sequence", "expressions", function AST_Sequence(props) { + if (props) { + this.expressions = props.expressions; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A sequence expression (comma-separated expressions)", + $propdoc: { + expressions: "[AST_Node*] array of expressions (at least two)" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expressions.forEach(function(node) { + node._walk(visitor); + }); + }); + }, + _children_backwards(push) { + let i = this.expressions.length; + while (i--) push(this.expressions[i]); + }, +}); + +var AST_PropAccess = DEFNODE( + "PropAccess", + "expression property optional", + function AST_PropAccess(props) { + if (props) { + this.expression = props.expression; + this.property = props.property; + this.optional = props.optional; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; + }, + { + $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`", + $propdoc: { + expression: "[AST_Node] the “container” expression", + property: "[AST_Node|string] the property to access. For AST_Dot & AST_DotHash this is always a plain string, while for AST_Sub it's an arbitrary AST_Node", + + optional: "[boolean] whether this is an optional property access (IE ?.)" + } + } +); + +var AST_Dot = DEFNODE("Dot", "quote", function AST_Dot(props) { + if (props) { + this.quote = props.quote; + this.expression = props.expression; + this.property = props.property; + this.optional = props.optional; + this._annotations = props._annotations; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A dotted property access expression", + $propdoc: { + quote: "[string] the original quote character when transformed from AST_Sub", + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}, AST_PropAccess); + +var AST_DotHash = DEFNODE("DotHash", "", function AST_DotHash(props) { + if (props) { + this.expression = props.expression; + this.property = props.property; + this.optional = props.optional; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A dotted property access to a private property", + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}, AST_PropAccess); + +var AST_Sub = DEFNODE("Sub", null, function AST_Sub(props) { + if (props) { + this.expression = props.expression; + this.property = props.property; + this.optional = props.optional; + this._annotations = props._annotations; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Index-style property access, i.e. `a[\"foo\"]`", + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + this.property._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.property); + push(this.expression); + }, +}, AST_PropAccess); + +var AST_Chain = DEFNODE("Chain", "expression", function AST_Chain(props) { + if (props) { + this.expression = props.expression; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A chain expression like a?.b?.(c)?.[d]", + $propdoc: { + expression: "[AST_Call|AST_Dot|AST_DotHash|AST_Sub] chain element." + }, + _walk: function (visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}); + +var AST_Unary = DEFNODE("Unary", "operator expression", function AST_Unary(props) { + if (props) { + this.operator = props.operator; + this.expression = props.expression; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for unary expressions", + $propdoc: { + operator: "[string] the operator", + expression: "[AST_Node] expression that this unary operator applies to" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.expression._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.expression); + }, +}); + +var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, function AST_UnaryPrefix(props) { + if (props) { + this.operator = props.operator; + this.expression = props.expression; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`" +}, AST_Unary); + +var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, function AST_UnaryPostfix(props) { + if (props) { + this.operator = props.operator; + this.expression = props.expression; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Unary postfix expression, i.e. `i++`" +}, AST_Unary); + +var AST_Binary = DEFNODE("Binary", "operator left right", function AST_Binary(props) { + if (props) { + this.operator = props.operator; + this.left = props.left; + this.right = props.right; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Binary expression, i.e. `a + b`", + $propdoc: { + left: "[AST_Node] left-hand side expression", + operator: "[string] the operator", + right: "[AST_Node] right-hand side expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.left._walk(visitor); + this.right._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.right); + push(this.left); + }, +}); + +var AST_Conditional = DEFNODE( + "Conditional", + "condition consequent alternative", + function AST_Conditional(props) { + if (props) { + this.condition = props.condition; + this.consequent = props.consequent; + this.alternative = props.alternative; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; + }, + { + $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`", + $propdoc: { + condition: "[AST_Node]", + consequent: "[AST_Node]", + alternative: "[AST_Node]" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + this.condition._walk(visitor); + this.consequent._walk(visitor); + this.alternative._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.alternative); + push(this.consequent); + push(this.condition); + }, + } +); + +var AST_Assign = DEFNODE("Assign", "logical", function AST_Assign(props) { + if (props) { + this.logical = props.logical; + this.operator = props.operator; + this.left = props.left; + this.right = props.right; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "An assignment expression — `a = b + 5`", + $propdoc: { + logical: "Whether it's a logical assignment" + } +}, AST_Binary); + +var AST_DefaultAssign = DEFNODE("DefaultAssign", null, function AST_DefaultAssign(props) { + if (props) { + this.operator = props.operator; + this.left = props.left; + this.right = props.right; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A default assignment expression like in `(a = 3) => a`" +}, AST_Binary); + +/* -----[ LITERALS ]----- */ + +var AST_Array = DEFNODE("Array", "elements", function AST_Array(props) { + if (props) { + this.elements = props.elements; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "An array literal", + $propdoc: { + elements: "[AST_Node*] array of elements" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + var elements = this.elements; + for (var i = 0, len = elements.length; i < len; i++) { + elements[i]._walk(visitor); + } + }); + }, + _children_backwards(push) { + let i = this.elements.length; + while (i--) push(this.elements[i]); + }, +}); + +var AST_Object = DEFNODE("Object", "properties", function AST_Object(props) { + if (props) { + this.properties = props.properties; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "An object literal", + $propdoc: { + properties: "[AST_ObjectProperty*] array of properties" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + var properties = this.properties; + for (var i = 0, len = properties.length; i < len; i++) { + properties[i]._walk(visitor); + } + }); + }, + _children_backwards(push) { + let i = this.properties.length; + while (i--) push(this.properties[i]); + }, +}); + +var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", function AST_ObjectProperty(props) { + if (props) { + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + this._annotations = props._annotations; + } + + this.flags = 0; +}, { + $documentation: "Base class for literal object properties", + $propdoc: { + key: "[string|AST_Node] property name. For ObjectKeyVal this is a string. For getters, setters and computed property this is an AST_Node.", + value: "[AST_Node] property value. For getters and setters this is an AST_Accessor." + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.key instanceof AST_Node) + this.key._walk(visitor); + this.value._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.value); + if (this.key instanceof AST_Node) push(this.key); + } +}); + +var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", "quote", function AST_ObjectKeyVal(props) { + if (props) { + this.quote = props.quote; + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + this._annotations = props._annotations; + } + + this.flags = 0; +}, { + $documentation: "A key: value object property", + $propdoc: { + quote: "[string] the original quote character" + }, + computed_key() { + return this.key instanceof AST_Node; + } +}, AST_ObjectProperty); + +var AST_PrivateSetter = DEFNODE("PrivateSetter", "static", function AST_PrivateSetter(props) { + if (props) { + this.static = props.static; + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $propdoc: { + static: "[boolean] whether this is a static private setter" + }, + $documentation: "A private setter property", + computed_key() { + return false; + } +}, AST_ObjectProperty); + +var AST_PrivateGetter = DEFNODE("PrivateGetter", "static", function AST_PrivateGetter(props) { + if (props) { + this.static = props.static; + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $propdoc: { + static: "[boolean] whether this is a static private getter" + }, + $documentation: "A private getter property", + computed_key() { + return false; + } +}, AST_ObjectProperty); + +var AST_ObjectSetter = DEFNODE("ObjectSetter", "quote static", function AST_ObjectSetter(props) { + if (props) { + this.quote = props.quote; + this.static = props.static; + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + this._annotations = props._annotations; + } + + this.flags = 0; +}, { + $propdoc: { + quote: "[string|undefined] the original quote character, if any", + static: "[boolean] whether this is a static setter (classes only)" + }, + $documentation: "An object setter property", + computed_key() { + return !(this.key instanceof AST_SymbolMethod); + } +}, AST_ObjectProperty); + +var AST_ObjectGetter = DEFNODE("ObjectGetter", "quote static", function AST_ObjectGetter(props) { + if (props) { + this.quote = props.quote; + this.static = props.static; + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + this._annotations = props._annotations; + } + + this.flags = 0; +}, { + $propdoc: { + quote: "[string|undefined] the original quote character, if any", + static: "[boolean] whether this is a static getter (classes only)" + }, + $documentation: "An object getter property", + computed_key() { + return !(this.key instanceof AST_SymbolMethod); + } +}, AST_ObjectProperty); + +var AST_ConciseMethod = DEFNODE( + "ConciseMethod", + "quote static is_generator async", + function AST_ConciseMethod(props) { + if (props) { + this.quote = props.quote; + this.static = props.static; + this.is_generator = props.is_generator; + this.async = props.async; + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + this._annotations = props._annotations; + } + + this.flags = 0; + }, + { + $propdoc: { + quote: "[string|undefined] the original quote character, if any", + static: "[boolean] is this method static (classes only)", + is_generator: "[boolean] is this a generator method", + async: "[boolean] is this method async", + }, + $documentation: "An ES6 concise method inside an object or class", + computed_key() { + return !(this.key instanceof AST_SymbolMethod); + } + }, + AST_ObjectProperty +); + +var AST_PrivateMethod = DEFNODE("PrivateMethod", "", function AST_PrivateMethod(props) { + if (props) { + this.quote = props.quote; + this.static = props.static; + this.is_generator = props.is_generator; + this.async = props.async; + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A private class method inside a class", +}, AST_ConciseMethod); + +var AST_Class = DEFNODE("Class", "name extends properties", function AST_Class(props) { + if (props) { + this.name = props.name; + this.extends = props.extends; + this.properties = props.properties; + this.variables = props.variables; + this.uses_with = props.uses_with; + this.uses_eval = props.uses_eval; + this.parent_scope = props.parent_scope; + this.enclosed = props.enclosed; + this.cname = props.cname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $propdoc: { + name: "[AST_SymbolClass|AST_SymbolDefClass?] optional class name.", + extends: "[AST_Node]? optional parent class", + properties: "[AST_ObjectProperty*] array of properties" + }, + $documentation: "An ES6 class", + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.name) { + this.name._walk(visitor); + } + if (this.extends) { + this.extends._walk(visitor); + } + this.properties.forEach((prop) => prop._walk(visitor)); + }); + }, + _children_backwards(push) { + let i = this.properties.length; + while (i--) push(this.properties[i]); + if (this.extends) push(this.extends); + if (this.name) push(this.name); + }, + /** go through the bits that are executed instantly, not when the class is `new`'d. Doesn't walk the name. */ + visit_nondeferred_class_parts(visitor) { + if (this.extends) { + this.extends._walk(visitor); + } + this.properties.forEach((prop) => { + if (prop instanceof AST_ClassStaticBlock) { + prop._walk(visitor); + return; + } + if (prop.computed_key()) { + visitor.push(prop); + prop.key._walk(visitor); + visitor.pop(); + } + if ((prop instanceof AST_ClassPrivateProperty || prop instanceof AST_ClassProperty) && prop.static && prop.value) { + visitor.push(prop); + prop.value._walk(visitor); + visitor.pop(); + } + }); + }, + /** go through the bits that are executed later, when the class is `new`'d or a static method is called */ + visit_deferred_class_parts(visitor) { + this.properties.forEach((prop) => { + if (prop instanceof AST_ConciseMethod) { + prop.walk(visitor); + } else if (prop instanceof AST_ClassProperty && !prop.static && prop.value) { + visitor.push(prop); + prop.value._walk(visitor); + visitor.pop(); + } + }); + }, + is_self_referential: function() { + const this_id = this.name && this.name.definition().id; + let found = false; + let class_this = true; + this.visit_nondeferred_class_parts(new TreeWalker((node, descend) => { + if (found) return true; + if (node instanceof AST_This) return (found = class_this); + if (node instanceof AST_SymbolRef) return (found = node.definition().id === this_id); + if (node instanceof AST_Lambda && !(node instanceof AST_Arrow)) { + const class_this_save = class_this; + class_this = false; + descend(); + class_this = class_this_save; + return true; + } + })); + return found; + }, +}, AST_Scope /* TODO a class might have a scope but it's not a scope */); + +var AST_ClassProperty = DEFNODE("ClassProperty", "static quote", function AST_ClassProperty(props) { + if (props) { + this.static = props.static; + this.quote = props.quote; + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + this._annotations = props._annotations; + } + + this.flags = 0; +}, { + $documentation: "A class property", + $propdoc: { + static: "[boolean] whether this is a static key", + quote: "[string] which quote is being used" + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + if (this.key instanceof AST_Node) + this.key._walk(visitor); + if (this.value instanceof AST_Node) + this.value._walk(visitor); + }); + }, + _children_backwards(push) { + if (this.value instanceof AST_Node) push(this.value); + if (this.key instanceof AST_Node) push(this.key); + }, + computed_key() { + return !(this.key instanceof AST_SymbolClassProperty); + } +}, AST_ObjectProperty); + +var AST_ClassPrivateProperty = DEFNODE("ClassPrivateProperty", "", function AST_ClassPrivateProperty(props) { + if (props) { + this.static = props.static; + this.quote = props.quote; + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A class property for a private property", +}, AST_ClassProperty); + +var AST_PrivateIn = DEFNODE("PrivateIn", "key value", function AST_PrivateIn(props) { + if (props) { + this.key = props.key; + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "An `in` binop when the key is private, eg #x in this", + _walk: function(visitor) { + return visitor._visit(this, function() { + this.key._walk(visitor); + this.value._walk(visitor); + }); + }, + _children_backwards(push) { + push(this.value); + push(this.key); + }, +}); + +var AST_DefClass = DEFNODE("DefClass", null, function AST_DefClass(props) { + if (props) { + this.name = props.name; + this.extends = props.extends; + this.properties = props.properties; + this.variables = props.variables; + this.uses_with = props.uses_with; + this.uses_eval = props.uses_eval; + this.parent_scope = props.parent_scope; + this.enclosed = props.enclosed; + this.cname = props.cname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A class definition", +}, AST_Class); + +var AST_ClassStaticBlock = DEFNODE("ClassStaticBlock", "body block_scope", function AST_ClassStaticBlock (props) { + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; +}, { + $documentation: "A block containing statements to be executed in the context of the class", + $propdoc: { + body: "[AST_Statement*] an array of statements", + }, + _walk: function(visitor) { + return visitor._visit(this, function() { + walk_body(this, visitor); + }); + }, + _children_backwards(push) { + let i = this.body.length; + while (i--) push(this.body[i]); + }, + clone: clone_block_scope, + computed_key: () => false +}, AST_Scope); + +var AST_ClassExpression = DEFNODE("ClassExpression", null, function AST_ClassExpression(props) { + if (props) { + this.name = props.name; + this.extends = props.extends; + this.properties = props.properties; + this.variables = props.variables; + this.uses_with = props.uses_with; + this.uses_eval = props.uses_eval; + this.parent_scope = props.parent_scope; + this.enclosed = props.enclosed; + this.cname = props.cname; + this.body = props.body; + this.block_scope = props.block_scope; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A class expression." +}, AST_Class); + +var AST_Symbol = DEFNODE("Symbol", "scope name thedef", function AST_Symbol(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $propdoc: { + name: "[string] name of this symbol", + scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)", + thedef: "[SymbolDef/S] the definition of this symbol" + }, + $documentation: "Base class for all symbols" +}); + +var AST_NewTarget = DEFNODE("NewTarget", null, function AST_NewTarget(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A reference to new.target" +}); + +var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", function AST_SymbolDeclaration(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)", +}, AST_Symbol); + +var AST_SymbolVar = DEFNODE("SymbolVar", null, function AST_SymbolVar(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol defining a variable", +}, AST_SymbolDeclaration); + +var AST_SymbolBlockDeclaration = DEFNODE( + "SymbolBlockDeclaration", + null, + function AST_SymbolBlockDeclaration(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; + }, + { + $documentation: "Base class for block-scoped declaration symbols" + }, + AST_SymbolDeclaration +); + +var AST_SymbolConst = DEFNODE("SymbolConst", null, function AST_SymbolConst(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A constant declaration" +}, AST_SymbolBlockDeclaration); + +var AST_SymbolLet = DEFNODE("SymbolLet", null, function AST_SymbolLet(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A block-scoped `let` declaration" +}, AST_SymbolBlockDeclaration); + +var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, function AST_SymbolFunarg(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol naming a function argument", +}, AST_SymbolVar); + +var AST_SymbolDefun = DEFNODE("SymbolDefun", null, function AST_SymbolDefun(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol defining a function", +}, AST_SymbolDeclaration); + +var AST_SymbolMethod = DEFNODE("SymbolMethod", null, function AST_SymbolMethod(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol in an object defining a method", +}, AST_Symbol); + +var AST_SymbolClassProperty = DEFNODE("SymbolClassProperty", null, function AST_SymbolClassProperty(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol for a class property", +}, AST_Symbol); + +var AST_SymbolLambda = DEFNODE("SymbolLambda", null, function AST_SymbolLambda(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol naming a function expression", +}, AST_SymbolDeclaration); + +var AST_SymbolDefClass = DEFNODE("SymbolDefClass", null, function AST_SymbolDefClass(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol naming a class's name in a class declaration. Lexically scoped to its containing scope, and accessible within the class." +}, AST_SymbolBlockDeclaration); + +var AST_SymbolClass = DEFNODE("SymbolClass", null, function AST_SymbolClass(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol naming a class's name. Lexically scoped to the class." +}, AST_SymbolDeclaration); + +var AST_SymbolCatch = DEFNODE("SymbolCatch", null, function AST_SymbolCatch(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol naming the exception in catch", +}, AST_SymbolBlockDeclaration); + +var AST_SymbolImport = DEFNODE("SymbolImport", null, function AST_SymbolImport(props) { + if (props) { + this.init = props.init; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol referring to an imported name", +}, AST_SymbolBlockDeclaration); + +var AST_SymbolImportForeign = DEFNODE("SymbolImportForeign", null, function AST_SymbolImportForeign(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.quote = props.quote; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A symbol imported from a module, but it is defined in the other module, and its real name is irrelevant for this module's purposes", +}, AST_Symbol); + +var AST_Label = DEFNODE("Label", "references", function AST_Label(props) { + if (props) { + this.references = props.references; + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + this.initialize(); + } + + this.flags = 0; +}, { + $documentation: "Symbol naming a label (declaration)", + $propdoc: { + references: "[AST_LoopControl*] a list of nodes referring to this label" + }, + initialize: function() { + this.references = []; + this.thedef = this; + } +}, AST_Symbol); + +var AST_SymbolRef = DEFNODE("SymbolRef", null, function AST_SymbolRef(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Reference to some symbol (not definition/declaration)", +}, AST_Symbol); + +var AST_SymbolExport = DEFNODE("SymbolExport", null, function AST_SymbolExport(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.quote = props.quote; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Symbol referring to a name to export", +}, AST_SymbolRef); + +var AST_SymbolExportForeign = DEFNODE("SymbolExportForeign", null, function AST_SymbolExportForeign(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.quote = props.quote; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A symbol exported from this module, but it is used in the other module, and its real name is irrelevant for this module's purposes", +}, AST_Symbol); + +var AST_LabelRef = DEFNODE("LabelRef", null, function AST_LabelRef(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Reference to a label symbol", +}, AST_Symbol); + +var AST_SymbolPrivateProperty = DEFNODE("SymbolPrivateProperty", null, function AST_SymbolPrivateProperty(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A symbol that refers to a private property", +}, AST_Symbol); + +var AST_This = DEFNODE("This", null, function AST_This(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The `this` symbol", +}, AST_Symbol); + +var AST_Super = DEFNODE("Super", null, function AST_Super(props) { + if (props) { + this.scope = props.scope; + this.name = props.name; + this.thedef = props.thedef; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The `super` symbol", +}, AST_This); + +var AST_Constant = DEFNODE("Constant", null, function AST_Constant(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for all constants", + getValue: function() { + return this.value; + } +}); + +var AST_String = DEFNODE("String", "value quote", function AST_String(props) { + if (props) { + this.value = props.value; + this.quote = props.quote; + this.start = props.start; + this.end = props.end; + this._annotations = props._annotations; + } + + this.flags = 0; +}, { + $documentation: "A string literal", + $propdoc: { + value: "[string] the contents of this string", + quote: "[string] the original quote character" + } +}, AST_Constant); + +var AST_Number = DEFNODE("Number", "value raw", function AST_Number(props) { + if (props) { + this.value = props.value; + this.raw = props.raw; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A number literal", + $propdoc: { + value: "[number] the numeric value", + raw: "[string] numeric value as string" + } +}, AST_Constant); + +var AST_BigInt = DEFNODE("BigInt", "value", function AST_BigInt(props) { + if (props) { + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A big int literal", + $propdoc: { + value: "[string] big int value" + } +}, AST_Constant); + +var AST_RegExp = DEFNODE("RegExp", "value", function AST_RegExp(props) { + if (props) { + this.value = props.value; + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A regexp literal", + $propdoc: { + value: "[RegExp] the actual regexp", + } +}, AST_Constant); + +var AST_Atom = DEFNODE("Atom", null, function AST_Atom(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for atoms", +}, AST_Constant); + +var AST_Null = DEFNODE("Null", null, function AST_Null(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The `null` atom", + value: null +}, AST_Atom); + +var AST_NaN = DEFNODE("NaN", null, function AST_NaN(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The impossible value", + value: 0/0 +}, AST_Atom); + +var AST_Undefined = DEFNODE("Undefined", null, function AST_Undefined(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The `undefined` value", + value: (function() {}()) +}, AST_Atom); + +var AST_Hole = DEFNODE("Hole", null, function AST_Hole(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "A hole in an array", + value: (function() {}()) +}, AST_Atom); + +var AST_Infinity = DEFNODE("Infinity", null, function AST_Infinity(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The `Infinity` value", + value: 1/0 +}, AST_Atom); + +var AST_Boolean = DEFNODE("Boolean", null, function AST_Boolean(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "Base class for booleans", +}, AST_Atom); + +var AST_False = DEFNODE("False", null, function AST_False(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The `false` atom", + value: false +}, AST_Boolean); + +var AST_True = DEFNODE("True", null, function AST_True(props) { + if (props) { + this.start = props.start; + this.end = props.end; + } + + this.flags = 0; +}, { + $documentation: "The `true` atom", + value: true +}, AST_Boolean); + +/* -----[ Walk function ]---- */ + +/** + * Walk nodes in depth-first search fashion. + * Callback can return `walk_abort` symbol to stop iteration. + * It can also return `true` to stop iteration just for child nodes. + * Iteration can be stopped and continued by passing the `to_visit` argument, + * which is given to the callback in the second argument. + **/ +function walk(node, cb, to_visit = [node]) { + const push = to_visit.push.bind(to_visit); + while (to_visit.length) { + const node = to_visit.pop(); + const ret = cb(node, to_visit); + + if (ret) { + if (ret === walk_abort) return true; + continue; + } + + node._children_backwards(push); + } + return false; +} + +/** + * Walks an AST node and its children. + * + * {cb} can return `walk_abort` to interrupt the walk. + * + * @param node + * @param cb {(node, info: { parent: (nth) => any }) => (boolean | undefined)} + * + * @returns {boolean} whether the walk was aborted + * + * @example + * const found_some_cond = walk_parent(my_ast_node, (node, { parent }) => { + * if (some_cond(node, parent())) return walk_abort + * }); + */ +function walk_parent(node, cb, initial_stack) { + const to_visit = [node]; + const push = to_visit.push.bind(to_visit); + const stack = initial_stack ? initial_stack.slice() : []; + const parent_pop_indices = []; + + let current; + + const info = { + parent: (n = 0) => { + if (n === -1) { + return current; + } + + // [ p1 p0 ] [ 1 0 ] + if (initial_stack && n >= stack.length) { + n -= stack.length; + return initial_stack[ + initial_stack.length - (n + 1) + ]; + } + + return stack[stack.length - (1 + n)]; + }, + }; + + while (to_visit.length) { + current = to_visit.pop(); + + while ( + parent_pop_indices.length && + to_visit.length == parent_pop_indices[parent_pop_indices.length - 1] + ) { + stack.pop(); + parent_pop_indices.pop(); + } + + const ret = cb(current, info); + + if (ret) { + if (ret === walk_abort) return true; + continue; + } + + const visit_length = to_visit.length; + + current._children_backwards(push); + + // Push only if we're going to traverse the children + if (to_visit.length > visit_length) { + stack.push(current); + parent_pop_indices.push(visit_length - 1); + } + } + + return false; +} + +const walk_abort = Symbol("abort walk"); + +/* -----[ TreeWalker ]----- */ + +class TreeWalker { + constructor(callback) { + this.visit = callback; + this.stack = []; + this.directives = Object.create(null); + } + + _visit(node, descend) { + this.push(node); + var ret = this.visit(node, descend ? function() { + descend.call(node); + } : noop); + if (!ret && descend) { + descend.call(node); + } + this.pop(); + return ret; + } + + parent(n) { + return this.stack[this.stack.length - 2 - (n || 0)]; + } + + push(node) { + if (node instanceof AST_Lambda) { + this.directives = Object.create(this.directives); + } else if (node instanceof AST_Directive && !this.directives[node.value]) { + this.directives[node.value] = node; + } else if (node instanceof AST_Class) { + this.directives = Object.create(this.directives); + if (!this.directives["use strict"]) { + this.directives["use strict"] = node; + } + } + this.stack.push(node); + } + + pop() { + var node = this.stack.pop(); + if (node instanceof AST_Lambda || node instanceof AST_Class) { + this.directives = Object.getPrototypeOf(this.directives); + } + } + + self() { + return this.stack[this.stack.length - 1]; + } + + find_parent(type) { + var stack = this.stack; + for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof type) return x; + } + } + + find_scope() { + var stack = this.stack; + for (var i = stack.length; --i >= 0;) { + const p = stack[i]; + if (p instanceof AST_Toplevel) return p; + if (p instanceof AST_Lambda) return p; + if (p.block_scope) return p.block_scope; + } + } + + has_directive(type) { + var dir = this.directives[type]; + if (dir) return dir; + var node = this.stack[this.stack.length - 1]; + if (node instanceof AST_Scope && node.body) { + for (var i = 0; i < node.body.length; ++i) { + var st = node.body[i]; + if (!(st instanceof AST_Directive)) break; + if (st.value == type) return st; + } + } + } + + loopcontrol_target(node) { + var stack = this.stack; + if (node.label) for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof AST_LabeledStatement && x.label.name == node.label.name) + return x.body; + } else for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof AST_IterationStatement + || node instanceof AST_Break && x instanceof AST_Switch) + return x; + } + } +} + +// Tree transformer helpers. +class TreeTransformer extends TreeWalker { + constructor(before, after) { + super(); + this.before = before; + this.after = after; + } +} + +const _PURE = 0b00000001; +const _INLINE = 0b00000010; +const _NOINLINE = 0b00000100; +const _KEY = 0b00001000; +const _MANGLEPROP = 0b00010000; + +export { + AST_Accessor, + AST_Array, + AST_Arrow, + AST_Assign, + AST_Atom, + AST_Await, + AST_BigInt, + AST_Binary, + AST_Block, + AST_BlockStatement, + AST_Boolean, + AST_Break, + AST_Call, + AST_Case, + AST_Catch, + AST_Chain, + AST_Class, + AST_ClassExpression, + AST_ClassPrivateProperty, + AST_PrivateIn, + AST_ClassProperty, + AST_ClassStaticBlock, + AST_ConciseMethod, + AST_Conditional, + AST_Const, + AST_Constant, + AST_Continue, + AST_Debugger, + AST_Default, + AST_DefaultAssign, + AST_DefClass, + AST_Definitions, + AST_Defun, + AST_Destructuring, + AST_Directive, + AST_Do, + AST_Dot, + AST_DotHash, + AST_DWLoop, + AST_EmptyStatement, + AST_Exit, + AST_Expansion, + AST_Export, + AST_False, + AST_Finally, + AST_For, + AST_ForIn, + AST_ForOf, + AST_Function, + AST_Hole, + AST_If, + AST_Import, + AST_ImportMeta, + AST_Infinity, + AST_IterationStatement, + AST_Jump, + AST_Label, + AST_LabeledStatement, + AST_LabelRef, + AST_Lambda, + AST_Let, + AST_LoopControl, + AST_NameMapping, + AST_NaN, + AST_New, + AST_NewTarget, + AST_Node, + AST_Null, + AST_Number, + AST_Object, + AST_ObjectGetter, + AST_ObjectKeyVal, + AST_ObjectProperty, + AST_ObjectSetter, + AST_PrefixedTemplateString, + AST_PrivateGetter, + AST_PrivateMethod, + AST_PrivateSetter, + AST_PropAccess, + AST_RegExp, + AST_Return, + AST_Scope, + AST_Sequence, + AST_SimpleStatement, + AST_Statement, + AST_StatementWithBody, + AST_String, + AST_Sub, + AST_Super, + AST_Switch, + AST_SwitchBranch, + AST_Symbol, + AST_SymbolBlockDeclaration, + AST_SymbolCatch, + AST_SymbolClass, + AST_SymbolClassProperty, + AST_SymbolConst, + AST_SymbolDeclaration, + AST_SymbolDefClass, + AST_SymbolDefun, + AST_SymbolExport, + AST_SymbolExportForeign, + AST_SymbolFunarg, + AST_SymbolImport, + AST_SymbolImportForeign, + AST_SymbolLambda, + AST_SymbolLet, + AST_SymbolMethod, + AST_SymbolRef, + AST_SymbolVar, + AST_TemplateSegment, + AST_TemplateString, + AST_SymbolPrivateProperty, + AST_This, + AST_Throw, + AST_Token, + AST_Toplevel, + AST_True, + AST_Try, + AST_TryBlock, + AST_Unary, + AST_UnaryPostfix, + AST_UnaryPrefix, + AST_Undefined, + AST_Var, + AST_VarDef, + AST_While, + AST_With, + AST_Yield, + + // Walkers + TreeTransformer, + TreeWalker, + walk, + walk_abort, + walk_body, + walk_parent, + + // annotations + _INLINE, + _NOINLINE, + _PURE, + _KEY, + _MANGLEPROP, +}; diff --git a/node_modules/terser/lib/cli.js b/node_modules/terser/lib/cli.js new file mode 100644 index 0000000..1ec2cc4 --- /dev/null +++ b/node_modules/terser/lib/cli.js @@ -0,0 +1,481 @@ +import { minify, _default_options } from "../main.js"; +import { parse } from "./parse.js"; +import { + AST_Assign, + AST_Array, + AST_Constant, + AST_Node, + AST_PropAccess, + AST_RegExp, + AST_Sequence, + AST_Symbol, + AST_Token, + walk +} from "./ast.js"; +import { OutputStream } from "./output.js"; + +export async function run_cli({ program, packageJson, fs, path }) { + const skip_keys = new Set([ "cname", "parent_scope", "scope", "uses_eval", "uses_with" ]); + var files = {}; + var options = { + compress: false, + mangle: false + }; + const default_options = await _default_options(); + program.version(packageJson.name + " " + packageJson.version); + program.parseArgv = program.parse; + program.parse = undefined; + + if (process.argv.includes("ast")) program.helpInformation = describe_ast; + else if (process.argv.includes("options")) program.helpInformation = function() { + var text = []; + for (var option in default_options) { + text.push("--" + (option === "sourceMap" ? "source-map" : option) + " options:"); + text.push(format_object(default_options[option])); + text.push(""); + } + return text.join("\n"); + }; + + program.option("-p, --parse ", "Specify parser options.", parse_js()); + program.option("-c, --compress [options]", "Enable compressor/specify compressor options.", parse_js()); + program.option("-m, --mangle [options]", "Mangle names/specify mangler options.", parse_js()); + program.option("--mangle-props [options]", "Mangle properties/specify mangler options.", parse_js()); + program.option("-f, --format [options]", "Format options.", parse_js()); + program.option("-b, --beautify [options]", "Alias for --format.", parse_js()); + program.option("-o, --output ", "Output file (default STDOUT)."); + program.option("--comments [filter]", "Preserve copyright comments in the output."); + program.option("--config-file ", "Read minify() options from JSON file."); + program.option("-d, --define [=value]", "Global definitions.", parse_js("define")); + program.option("--ecma ", "Specify ECMAScript release: 5, 2015, 2016 or 2017..."); + program.option("-e, --enclose [arg[,...][:value[,...]]]", "Embed output in a big function with configurable arguments and values."); + program.option("--ie8", "Support non-standard Internet Explorer 8."); + program.option("--keep-classnames", "Do not mangle/drop class names."); + program.option("--keep-fnames", "Do not mangle/drop function names. Useful for code relying on Function.prototype.name."); + program.option("--module", "Input is an ES6 module"); + program.option("--name-cache ", "File to hold mangled name mappings."); + program.option("--rename", "Force symbol expansion."); + program.option("--no-rename", "Disable symbol expansion."); + program.option("--safari10", "Support non-standard Safari 10."); + program.option("--source-map [options]", "Enable source map/specify source map options.", parse_js()); + program.option("--timings", "Display operations run time on STDERR."); + program.option("--toplevel", "Compress and/or mangle variables in toplevel scope."); + program.option("--wrap ", "Embed everything as a function with “exports” corresponding to “name” globally."); + program.arguments("[files...]").parseArgv(process.argv); + if (program.configFile) { + options = JSON.parse(read_file(program.configFile)); + } + if (!program.output && program.sourceMap && program.sourceMap.url != "inline") { + fatal("ERROR: cannot write source map to STDOUT"); + } + + [ + "compress", + "enclose", + "ie8", + "mangle", + "module", + "safari10", + "sourceMap", + "toplevel", + "wrap" + ].forEach(function(name) { + if (name in program) { + options[name] = program[name]; + } + }); + + if ("ecma" in program) { + if (program.ecma != (program.ecma | 0)) fatal("ERROR: ecma must be an integer"); + const ecma = program.ecma | 0; + if (ecma > 5 && ecma < 2015) + options.ecma = ecma + 2009; + else + options.ecma = ecma; + } + if (program.format || program.beautify) { + const chosenOption = program.format || program.beautify; + options.format = typeof chosenOption === "object" ? chosenOption : {}; + } + if (program.comments) { + if (typeof options.format != "object") options.format = {}; + options.format.comments = typeof program.comments == "string" ? (program.comments == "false" ? false : program.comments) : "some"; + } + if (program.define) { + if (typeof options.compress != "object") options.compress = {}; + if (typeof options.compress.global_defs != "object") options.compress.global_defs = {}; + for (var expr in program.define) { + options.compress.global_defs[expr] = program.define[expr]; + } + } + if (program.keepClassnames) { + options.keep_classnames = true; + } + if (program.keepFnames) { + options.keep_fnames = true; + } + if (program.mangleProps) { + if (program.mangleProps.domprops) { + delete program.mangleProps.domprops; + } else { + if (typeof program.mangleProps != "object") program.mangleProps = {}; + if (!Array.isArray(program.mangleProps.reserved)) program.mangleProps.reserved = []; + } + if (typeof options.mangle != "object") options.mangle = {}; + options.mangle.properties = program.mangleProps; + } + if (program.nameCache) { + options.nameCache = JSON.parse(read_file(program.nameCache, "{}")); + } + if (program.output == "ast") { + options.format = { + ast: true, + code: false + }; + } + if (program.parse) { + if (!program.parse.acorn && !program.parse.spidermonkey) { + options.parse = program.parse; + } else if (program.sourceMap && program.sourceMap.content == "inline") { + fatal("ERROR: inline source map only works with built-in parser"); + } + } + if (~program.rawArgs.indexOf("--rename")) { + options.rename = true; + } else if (!program.rename) { + options.rename = false; + } + + let convert_path = name => name; + if (typeof program.sourceMap == "object" && "base" in program.sourceMap) { + convert_path = function() { + var base = program.sourceMap.base; + delete options.sourceMap.base; + return function(name) { + return path.relative(base, name); + }; + }(); + } + + let filesList; + if (options.files && options.files.length) { + filesList = options.files; + + delete options.files; + } else if (program.args.length) { + filesList = program.args; + } + + if (filesList) { + simple_glob(filesList).forEach(function(name) { + files[convert_path(name)] = read_file(name); + }); + } else { + await new Promise((resolve) => { + var chunks = []; + process.stdin.setEncoding("utf8"); + process.stdin.on("data", function(chunk) { + chunks.push(chunk); + }).on("end", function() { + files = [ chunks.join("") ]; + resolve(); + }); + process.stdin.resume(); + }); + } + + await run_cli(); + + function convert_ast(fn) { + return AST_Node.from_mozilla_ast(Object.keys(files).reduce(fn, null)); + } + + async function run_cli() { + var content = program.sourceMap && program.sourceMap.content; + if (content && content !== "inline") { + options.sourceMap.content = read_file(content, content); + } + if (program.timings) options.timings = true; + + try { + if (program.parse) { + if (program.parse.acorn) { + files = convert_ast(function(toplevel, name) { + return require("acorn").parse(files[name], { + ecmaVersion: 2018, + locations: true, + program: toplevel, + sourceFile: name, + sourceType: options.module || program.parse.module ? "module" : "script" + }); + }); + } else if (program.parse.spidermonkey) { + files = convert_ast(function(toplevel, name) { + var obj = JSON.parse(files[name]); + if (!toplevel) return obj; + toplevel.body = toplevel.body.concat(obj.body); + return toplevel; + }); + } + } + } catch (ex) { + fatal(ex); + } + + let result; + try { + result = await minify(files, options, fs); + } catch (ex) { + if (ex.name == "SyntaxError") { + print_error("Parse error at " + ex.filename + ":" + ex.line + "," + ex.col); + var col = ex.col; + var lines = files[ex.filename].split(/\r?\n/); + var line = lines[ex.line - 1]; + if (!line && !col) { + line = lines[ex.line - 2]; + col = line.length; + } + if (line) { + var limit = 70; + if (col > limit) { + line = line.slice(col - limit); + col = limit; + } + print_error(line.slice(0, 80)); + print_error(line.slice(0, col).replace(/\S/g, " ") + "^"); + } + } + if (ex.defs) { + print_error("Supported options:"); + print_error(format_object(ex.defs)); + } + fatal(ex); + return; + } + + if (program.output == "ast") { + if (!options.compress && !options.mangle) { + result.ast.figure_out_scope({}); + } + console.log(JSON.stringify(result.ast, function(key, value) { + if (value) switch (key) { + case "thedef": + return symdef(value); + case "enclosed": + return value.length ? value.map(symdef) : undefined; + case "variables": + case "globals": + return value.size ? collect_from_map(value, symdef) : undefined; + } + if (skip_keys.has(key)) return; + if (value instanceof AST_Token) return; + if (value instanceof Map) return; + if (value instanceof AST_Node) { + var result = { + _class: "AST_" + value.TYPE + }; + if (value.block_scope) { + result.variables = value.block_scope.variables; + result.enclosed = value.block_scope.enclosed; + } + value.CTOR.PROPS.forEach(function(prop) { + if (prop !== "block_scope") { + result[prop] = value[prop]; + } + }); + return result; + } + return value; + }, 2)); + } else if (program.output == "spidermonkey") { + try { + const minified = await minify( + result.code, + { + compress: false, + mangle: false, + format: { + ast: true, + code: false + } + }, + fs + ); + console.log(JSON.stringify(minified.ast.to_mozilla_ast(), null, 2)); + } catch (ex) { + fatal(ex); + return; + } + } else if (program.output) { + fs.writeFileSync(program.output, result.code); + if (options.sourceMap && options.sourceMap.url !== "inline" && result.map) { + fs.writeFileSync(program.output + ".map", result.map); + } + } else { + console.log(result.code); + } + if (program.nameCache) { + fs.writeFileSync(program.nameCache, JSON.stringify(options.nameCache)); + } + if (result.timings) for (var phase in result.timings) { + print_error("- " + phase + ": " + result.timings[phase].toFixed(3) + "s"); + } + } + + function fatal(message) { + if (message instanceof Error) message = message.stack.replace(/^\S*?Error:/, "ERROR:"); + print_error(message); + process.exit(1); + } + + // A file glob function that only supports "*" and "?" wildcards in the basename. + // Example: "foo/bar/*baz??.*.js" + // Argument `glob` may be a string or an array of strings. + // Returns an array of strings. Garbage in, garbage out. + function simple_glob(glob) { + if (Array.isArray(glob)) { + return [].concat.apply([], glob.map(simple_glob)); + } + if (glob && glob.match(/[*?]/)) { + var dir = path.dirname(glob); + try { + var entries = fs.readdirSync(dir); + } catch (ex) {} + if (entries) { + var pattern = "^" + path.basename(glob) + .replace(/[.+^$[\]\\(){}]/g, "\\$&") + .replace(/\*/g, "[^/\\\\]*") + .replace(/\?/g, "[^/\\\\]") + "$"; + var mod = process.platform === "win32" ? "i" : ""; + var rx = new RegExp(pattern, mod); + var results = entries.filter(function(name) { + return rx.test(name); + }).map(function(name) { + return path.join(dir, name); + }); + if (results.length) return results; + } + } + return [ glob ]; + } + + function read_file(path, default_value) { + try { + return fs.readFileSync(path, "utf8"); + } catch (ex) { + if ((ex.code == "ENOENT" || ex.code == "ENAMETOOLONG") && default_value != null) return default_value; + fatal(ex); + } + } + + function parse_js(flag) { + return function(value, options) { + options = options || {}; + try { + walk(parse(value, { expression: true }), node => { + if (node instanceof AST_Assign) { + var name = node.left.print_to_string(); + var value = node.right; + if (flag) { + options[name] = value; + } else if (value instanceof AST_Array) { + options[name] = value.elements.map(to_string); + } else if (value instanceof AST_RegExp) { + value = value.value; + options[name] = new RegExp(value.source, value.flags); + } else { + options[name] = to_string(value); + } + return true; + } + if (node instanceof AST_Symbol || node instanceof AST_PropAccess) { + var name = node.print_to_string(); + options[name] = true; + return true; + } + if (!(node instanceof AST_Sequence)) throw node; + + function to_string(value) { + return value instanceof AST_Constant ? value.getValue() : value.print_to_string({ + quote_keys: true + }); + } + }); + } catch(ex) { + if (flag) { + fatal("Error parsing arguments for '" + flag + "': " + value); + } else { + options[value] = null; + } + } + return options; + }; + } + + function symdef(def) { + var ret = (1e6 + def.id) + " " + def.name; + if (def.mangled_name) ret += " " + def.mangled_name; + return ret; + } + + function collect_from_map(map, callback) { + var result = []; + map.forEach(function (def) { + result.push(callback(def)); + }); + return result; + } + + function format_object(obj) { + var lines = []; + var padding = ""; + Object.keys(obj).map(function(name) { + if (padding.length < name.length) padding = Array(name.length + 1).join(" "); + return [ name, JSON.stringify(obj[name]) ]; + }).forEach(function(tokens) { + lines.push(" " + tokens[0] + padding.slice(tokens[0].length - 2) + tokens[1]); + }); + return lines.join("\n"); + } + + function print_error(msg) { + process.stderr.write(msg); + process.stderr.write("\n"); + } + + function describe_ast() { + var out = OutputStream({ beautify: true }); + function doitem(ctor) { + out.print("AST_" + ctor.TYPE); + const props = ctor.SELF_PROPS.filter(prop => !/^\$/.test(prop)); + + if (props.length > 0) { + out.space(); + out.with_parens(function() { + props.forEach(function(prop, i) { + if (i) out.space(); + out.print(prop); + }); + }); + } + + if (ctor.documentation) { + out.space(); + out.print_string(ctor.documentation); + } + + if (ctor.SUBCLASSES.length > 0) { + out.space(); + out.with_block(function() { + ctor.SUBCLASSES.forEach(function(ctor) { + out.indent(); + doitem(ctor); + out.newline(); + }); + }); + } + } + doitem(AST_Node); + return out + "\n"; + } +} diff --git a/node_modules/terser/lib/compress/common.js b/node_modules/terser/lib/compress/common.js new file mode 100644 index 0000000..0ef9018 --- /dev/null +++ b/node_modules/terser/lib/compress/common.js @@ -0,0 +1,356 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { + AST_Array, + AST_Arrow, + AST_BigInt, + AST_BlockStatement, + AST_Call, + AST_Chain, + AST_Class, + AST_Const, + AST_Constant, + AST_DefClass, + AST_Defun, + AST_EmptyStatement, + AST_Export, + AST_False, + AST_Function, + AST_Import, + AST_Infinity, + AST_LabeledStatement, + AST_Lambda, + AST_Let, + AST_LoopControl, + AST_NaN, + AST_Node, + AST_Null, + AST_Number, + AST_Object, + AST_ObjectKeyVal, + AST_PropAccess, + AST_RegExp, + AST_Scope, + AST_Sequence, + AST_SimpleStatement, + AST_Statement, + AST_String, + AST_SymbolRef, + AST_True, + AST_UnaryPrefix, + AST_Undefined, + + TreeWalker, + walk, + walk_abort, + walk_parent, +} from "../ast.js"; +import { make_node, regexp_source_fix, string_template, makePredicate } from "../utils/index.js"; +import { first_in_statement } from "../utils/first_in_statement.js"; +import { has_flag, TOP } from "./compressor-flags.js"; + +export function merge_sequence(array, node) { + if (node instanceof AST_Sequence) { + array.push(...node.expressions); + } else { + array.push(node); + } + return array; +} + +export function make_sequence(orig, expressions) { + if (expressions.length == 1) return expressions[0]; + if (expressions.length == 0) throw new Error("trying to create a sequence with length zero!"); + return make_node(AST_Sequence, orig, { + expressions: expressions.reduce(merge_sequence, []) + }); +} + +export function make_node_from_constant(val, orig) { + switch (typeof val) { + case "string": + return make_node(AST_String, orig, { + value: val + }); + case "number": + if (isNaN(val)) return make_node(AST_NaN, orig); + if (isFinite(val)) { + return 1 / val < 0 ? make_node(AST_UnaryPrefix, orig, { + operator: "-", + expression: make_node(AST_Number, orig, { value: -val }) + }) : make_node(AST_Number, orig, { value: val }); + } + return val < 0 ? make_node(AST_UnaryPrefix, orig, { + operator: "-", + expression: make_node(AST_Infinity, orig) + }) : make_node(AST_Infinity, orig); + case "bigint": + return make_node(AST_BigInt, orig, { value: val.toString() }); + case "boolean": + return make_node(val ? AST_True : AST_False, orig); + case "undefined": + return make_node(AST_Undefined, orig); + default: + if (val === null) { + return make_node(AST_Null, orig, { value: null }); + } + if (val instanceof RegExp) { + return make_node(AST_RegExp, orig, { + value: { + source: regexp_source_fix(val.source), + flags: val.flags + } + }); + } + throw new Error(string_template("Can't handle constant of type: {type}", { + type: typeof val + })); + } +} + +export function best_of_expression(ast1, ast2) { + return ast1.size() > ast2.size() ? ast2 : ast1; +} + +export function best_of_statement(ast1, ast2) { + return best_of_expression( + make_node(AST_SimpleStatement, ast1, { + body: ast1 + }), + make_node(AST_SimpleStatement, ast2, { + body: ast2 + }) + ).body; +} + +/** Find which node is smaller, and return that */ +export function best_of(compressor, ast1, ast2) { + if (first_in_statement(compressor)) { + return best_of_statement(ast1, ast2); + } else { + return best_of_expression(ast1, ast2); + } +} + +/** Simplify an object property's key, if possible */ +export function get_simple_key(key) { + if (key instanceof AST_Constant) { + return key.getValue(); + } + if (key instanceof AST_UnaryPrefix + && key.operator == "void" + && key.expression instanceof AST_Constant) { + return; + } + return key; +} + +export function read_property(obj, key) { + key = get_simple_key(key); + if (key instanceof AST_Node) return; + + var value; + if (obj instanceof AST_Array) { + var elements = obj.elements; + if (key == "length") return make_node_from_constant(elements.length, obj); + if (typeof key == "number" && key in elements) value = elements[key]; + } else if (obj instanceof AST_Object) { + key = "" + key; + var props = obj.properties; + for (var i = props.length; --i >= 0;) { + var prop = props[i]; + if (!(prop instanceof AST_ObjectKeyVal)) return; + if (!value && props[i].key === key) value = props[i].value; + } + } + + return value instanceof AST_SymbolRef && value.fixed_value() || value; +} + +export function has_break_or_continue(loop, parent) { + var found = false; + var tw = new TreeWalker(function(node) { + if (found || node instanceof AST_Scope) return true; + if (node instanceof AST_LoopControl && tw.loopcontrol_target(node) === loop) { + return found = true; + } + }); + if (parent instanceof AST_LabeledStatement) tw.push(parent); + tw.push(loop); + loop.body.walk(tw); + return found; +} + +// we shouldn't compress (1,func)(something) to +// func(something) because that changes the meaning of +// the func (becomes lexical instead of global). +export function maintain_this_binding(parent, orig, val) { + if (requires_sequence_to_maintain_binding(parent, orig, val)) { + const zero = make_node(AST_Number, orig, { value: 0 }); + return make_sequence(orig, [ zero, val ]); + } else { + return val; + } +} + +/** Detect (1, x.noThis)(), (0, eval)(), which need sequences */ +export function requires_sequence_to_maintain_binding(parent, orig, val) { + return ( + parent instanceof AST_UnaryPrefix && parent.operator == "delete" + || parent instanceof AST_Call && parent.expression === orig + && ( + val instanceof AST_Chain + || val instanceof AST_PropAccess + || val instanceof AST_SymbolRef && val.name == "eval" + ) + ); +} + +export function is_func_expr(node) { + return node instanceof AST_Arrow || node instanceof AST_Function; +} + +/** + * Used to determine whether the node can benefit from negation. + * Not the case with arrow functions (you need an extra set of parens). */ +export function is_iife_call(node) { + if (node.TYPE != "Call") return false; + return node.expression instanceof AST_Function || is_iife_call(node.expression); +} + +export function is_empty(thing) { + if (thing === null) return true; + if (thing instanceof AST_EmptyStatement) return true; + if (thing instanceof AST_BlockStatement) return thing.body.length == 0; + return false; +} + +export const identifier_atom = makePredicate("Infinity NaN undefined"); +export function is_identifier_atom(node) { + return node instanceof AST_Infinity + || node instanceof AST_NaN + || node instanceof AST_Undefined; +} + +/** Check if this is a SymbolRef node which has one def of a certain AST type */ +export function is_ref_of(ref, type) { + if (!(ref instanceof AST_SymbolRef)) return false; + var orig = ref.definition().orig; + for (var i = orig.length; --i >= 0;) { + if (orig[i] instanceof type) return true; + } +} + +/**Can we turn { block contents... } into just the block contents ? + * Not if one of these is inside. + **/ +export function can_be_evicted_from_block(node) { + return !( + node instanceof AST_DefClass || + node instanceof AST_Defun || + node instanceof AST_Let || + node instanceof AST_Const || + node instanceof AST_Export || + node instanceof AST_Import + ); +} + +export function as_statement_array(thing) { + if (thing === null) return []; + if (thing instanceof AST_BlockStatement) return thing.body; + if (thing instanceof AST_EmptyStatement) return []; + if (thing instanceof AST_Statement) return [ thing ]; + throw new Error("Can't convert thing to statement array"); +} + +export function is_reachable(scope_node, defs) { + const find_ref = node => { + if (node instanceof AST_SymbolRef && defs.includes(node.definition())) { + return walk_abort; + } + }; + + return walk_parent(scope_node, (node, info) => { + if (node instanceof AST_Scope && node !== scope_node) { + var parent = info.parent(); + + if ( + parent instanceof AST_Call + && parent.expression === node + // Async/Generators aren't guaranteed to sync evaluate all of + // their body steps, so it's possible they close over the variable. + && !(node.async || node.is_generator) + ) { + return; + } + + if (walk(node, find_ref)) return walk_abort; + + return true; + } + }); +} + +/** Check if a ref refers to the name of a function/class it's defined within */ +export function is_recursive_ref(tw, def) { + var node; + for (var i = 0; node = tw.parent(i); i++) { + if (node instanceof AST_Lambda || node instanceof AST_Class) { + var name = node.name; + if (name && name.definition() === def) { + return true; + } + } + } + return false; +} + +// TODO this only works with AST_Defun, shouldn't it work for other ways of defining functions? +export function retain_top_func(fn, compressor) { + return compressor.top_retain + && fn instanceof AST_Defun + && has_flag(fn, TOP) + && fn.name + && compressor.top_retain(fn.name.definition()); +} diff --git a/node_modules/terser/lib/compress/compressor-flags.js b/node_modules/terser/lib/compress/compressor-flags.js new file mode 100644 index 0000000..1341658 --- /dev/null +++ b/node_modules/terser/lib/compress/compressor-flags.js @@ -0,0 +1,63 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +// bitfield flags to be stored in node.flags. +// These are set and unset during compression, and store information in the node without requiring multiple fields. +export const UNUSED = 0b00000001; +export const TRUTHY = 0b00000010; +export const FALSY = 0b00000100; +export const UNDEFINED = 0b00001000; +export const INLINED = 0b00010000; + +// Nodes to which values are ever written. Used when keep_assign is part of the unused option string. +export const WRITE_ONLY = 0b00100000; + +// information specific to a single compression pass +export const SQUEEZED = 0b0000000100000000; +export const OPTIMIZED = 0b0000001000000000; +export const TOP = 0b0000010000000000; +export const CLEAR_BETWEEN_PASSES = SQUEEZED | OPTIMIZED | TOP; + +export const has_flag = (node, flag) => node.flags & flag; +export const set_flag = (node, flag) => { node.flags |= flag; }; +export const clear_flag = (node, flag) => { node.flags &= ~flag; }; diff --git a/node_modules/terser/lib/compress/drop-side-effect-free.js b/node_modules/terser/lib/compress/drop-side-effect-free.js new file mode 100644 index 0000000..75b0bfc --- /dev/null +++ b/node_modules/terser/lib/compress/drop-side-effect-free.js @@ -0,0 +1,375 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { + AST_Accessor, + AST_Array, + AST_Arrow, + AST_Assign, + AST_Binary, + AST_Call, + AST_Chain, + AST_Class, + AST_ClassStaticBlock, + AST_ClassProperty, + AST_ConciseMethod, + AST_Conditional, + AST_Constant, + AST_DefClass, + AST_Dot, + AST_Expansion, + AST_Function, + AST_Node, + AST_Number, + AST_Object, + AST_ObjectGetter, + AST_ObjectKeyVal, + AST_ObjectProperty, + AST_ObjectSetter, + AST_PropAccess, + AST_Scope, + AST_Sequence, + AST_SimpleStatement, + AST_Sub, + AST_SymbolRef, + AST_TemplateSegment, + AST_TemplateString, + AST_This, + AST_Unary, +} from "../ast.js"; +import { make_node, return_null, return_this } from "../utils/index.js"; +import { first_in_statement } from "../utils/first_in_statement.js"; + +import { pure_prop_access_globals } from "./native-objects.js"; +import { lazy_op, unary_side_effects, is_nullish_shortcircuited } from "./inference.js"; +import { WRITE_ONLY, set_flag, clear_flag } from "./compressor-flags.js"; +import { make_sequence, is_func_expr, is_iife_call } from "./common.js"; + +// AST_Node#drop_side_effect_free() gets called when we don't care about the value, +// only about side effects. We'll be defining this method for each node type in this module +// +// Examples: +// foo++ -> foo++ +// 1 + func() -> func() +// 10 -> (nothing) +// knownPureFunc(foo++) -> foo++ + +function def_drop_side_effect_free(node, func) { + node.DEFMETHOD("drop_side_effect_free", func); +} + +// Drop side-effect-free elements from an array of expressions. +// Returns an array of expressions with side-effects or null +// if all elements were dropped. Note: original array may be +// returned if nothing changed. +function trim(nodes, compressor, first_in_statement) { + var len = nodes.length; + if (!len) return null; + + var ret = [], changed = false; + for (var i = 0; i < len; i++) { + var node = nodes[i].drop_side_effect_free(compressor, first_in_statement); + changed |= node !== nodes[i]; + if (node) { + ret.push(node); + first_in_statement = false; + } + } + return changed ? ret.length ? ret : null : nodes; +} + +def_drop_side_effect_free(AST_Node, return_this); +def_drop_side_effect_free(AST_Constant, return_null); +def_drop_side_effect_free(AST_This, return_null); + +def_drop_side_effect_free(AST_Call, function (compressor, first_in_statement) { + if (is_nullish_shortcircuited(this, compressor)) { + return this.expression.drop_side_effect_free(compressor, first_in_statement); + } + + if (!this.is_callee_pure(compressor)) { + if (this.expression.is_call_pure(compressor)) { + var exprs = this.args.slice(); + exprs.unshift(this.expression.expression); + exprs = trim(exprs, compressor, first_in_statement); + return exprs && make_sequence(this, exprs); + } + if (is_func_expr(this.expression) + && (!this.expression.name || !this.expression.name.definition().references.length)) { + var node = this.clone(); + node.expression.process_expression(false, compressor); + return node; + } + return this; + } + + var args = trim(this.args, compressor, first_in_statement); + return args && make_sequence(this, args); +}); + +def_drop_side_effect_free(AST_Accessor, return_null); + +def_drop_side_effect_free(AST_Function, return_null); + +def_drop_side_effect_free(AST_Arrow, return_null); + +def_drop_side_effect_free(AST_Class, function (compressor) { + const with_effects = []; + + if (this.is_self_referential() && this.has_side_effects(compressor)) { + return this; + } + + const trimmed_extends = this.extends && this.extends.drop_side_effect_free(compressor); + if (trimmed_extends) with_effects.push(trimmed_extends); + + for (const prop of this.properties) { + if (prop instanceof AST_ClassStaticBlock) { + if (prop.has_side_effects(compressor)) { + return this; // Be cautious about these + } + } else { + const trimmed_prop = prop.drop_side_effect_free(compressor); + if (trimmed_prop) with_effects.push(trimmed_prop); + } + } + + if (!with_effects.length) + return null; + + const exprs = make_sequence(this, with_effects); + if (this instanceof AST_DefClass) { + // We want a statement + return make_node(AST_SimpleStatement, this, { body: exprs }); + } else { + return exprs; + } +}); + +def_drop_side_effect_free(AST_ClassProperty, function (compressor) { + const key = this.computed_key() && this.key.drop_side_effect_free(compressor); + + const value = this.static && this.value + && this.value.drop_side_effect_free(compressor); + + if (key && value) + return make_sequence(this, [key, value]); + return key || value || null; +}); + +def_drop_side_effect_free(AST_Binary, function (compressor, first_in_statement) { + var right = this.right.drop_side_effect_free(compressor); + if (!right) + return this.left.drop_side_effect_free(compressor, first_in_statement); + if (lazy_op.has(this.operator)) { + if (right === this.right) + return this; + var node = this.clone(); + node.right = right; + return node; + } else { + var left = this.left.drop_side_effect_free(compressor, first_in_statement); + if (!left) + return this.right.drop_side_effect_free(compressor, first_in_statement); + return make_sequence(this, [left, right]); + } +}); + +def_drop_side_effect_free(AST_Assign, function (compressor) { + if (this.logical) + return this; + + var left = this.left; + if (left.has_side_effects(compressor) + || compressor.has_directive("use strict") + && left instanceof AST_PropAccess + && left.expression.is_constant()) { + return this; + } + set_flag(this, WRITE_ONLY); + while (left instanceof AST_PropAccess) { + left = left.expression; + } + if (left.is_constant_expression(compressor.find_parent(AST_Scope))) { + return this.right.drop_side_effect_free(compressor); + } + return this; +}); + +def_drop_side_effect_free(AST_Conditional, function (compressor) { + var consequent = this.consequent.drop_side_effect_free(compressor); + var alternative = this.alternative.drop_side_effect_free(compressor); + if (consequent === this.consequent && alternative === this.alternative) + return this; + if (!consequent) + return alternative ? make_node(AST_Binary, this, { + operator: "||", + left: this.condition, + right: alternative + }) : this.condition.drop_side_effect_free(compressor); + if (!alternative) + return make_node(AST_Binary, this, { + operator: "&&", + left: this.condition, + right: consequent + }); + var node = this.clone(); + node.consequent = consequent; + node.alternative = alternative; + return node; +}); + +def_drop_side_effect_free(AST_Unary, function (compressor, first_in_statement) { + if (unary_side_effects.has(this.operator)) { + if (!this.expression.has_side_effects(compressor)) { + set_flag(this, WRITE_ONLY); + } else { + clear_flag(this, WRITE_ONLY); + } + return this; + } + if (this.operator == "typeof" && this.expression instanceof AST_SymbolRef) + return null; + var expression = this.expression.drop_side_effect_free(compressor, first_in_statement); + if (first_in_statement && expression && is_iife_call(expression)) { + if (expression === this.expression && this.operator == "!") + return this; + return expression.negate(compressor, first_in_statement); + } + return expression; +}); + +def_drop_side_effect_free(AST_SymbolRef, function (compressor) { + const safe_access = this.is_declared(compressor) + || pure_prop_access_globals.has(this.name); + return safe_access ? null : this; +}); + +def_drop_side_effect_free(AST_Object, function (compressor, first_in_statement) { + var values = trim(this.properties, compressor, first_in_statement); + return values && make_sequence(this, values); +}); + +def_drop_side_effect_free(AST_ObjectProperty, function (compressor, first_in_statement) { + const computed_key = this instanceof AST_ObjectKeyVal && this.key instanceof AST_Node; + const key = computed_key && this.key.drop_side_effect_free(compressor, first_in_statement); + const value = this.value && this.value.drop_side_effect_free(compressor, first_in_statement); + if (key && value) { + return make_sequence(this, [key, value]); + } + return key || value; +}); + +def_drop_side_effect_free(AST_ConciseMethod, function () { + return this.computed_key() ? this.key : null; +}); + +def_drop_side_effect_free(AST_ObjectGetter, function () { + return this.computed_key() ? this.key : null; +}); + +def_drop_side_effect_free(AST_ObjectSetter, function () { + return this.computed_key() ? this.key : null; +}); + +def_drop_side_effect_free(AST_Array, function (compressor, first_in_statement) { + var values = trim(this.elements, compressor, first_in_statement); + return values && make_sequence(this, values); +}); + +def_drop_side_effect_free(AST_Dot, function (compressor, first_in_statement) { + if (is_nullish_shortcircuited(this, compressor)) { + return this.expression.drop_side_effect_free(compressor, first_in_statement); + } + if (!this.optional && this.expression.may_throw_on_access(compressor)) { + return this; + } + + return this.expression.drop_side_effect_free(compressor, first_in_statement); +}); + +def_drop_side_effect_free(AST_Sub, function (compressor, first_in_statement) { + if (is_nullish_shortcircuited(this, compressor)) { + return this.expression.drop_side_effect_free(compressor, first_in_statement); + } + if (!this.optional && this.expression.may_throw_on_access(compressor)) { + return this; + } + + var property = this.property.drop_side_effect_free(compressor); + if (property && this.optional) return this; + + var expression = this.expression.drop_side_effect_free(compressor, first_in_statement); + + if (expression && property) return make_sequence(this, [expression, property]); + return expression || property; +}); + +def_drop_side_effect_free(AST_Chain, function (compressor, first_in_statement) { + return this.expression.drop_side_effect_free(compressor, first_in_statement); +}); + +def_drop_side_effect_free(AST_Sequence, function (compressor) { + var last = this.tail_node(); + var expr = last.drop_side_effect_free(compressor); + if (expr === last) + return this; + var expressions = this.expressions.slice(0, -1); + if (expr) + expressions.push(expr); + if (!expressions.length) { + return make_node(AST_Number, this, { value: 0 }); + } + return make_sequence(this, expressions); +}); + +def_drop_side_effect_free(AST_Expansion, function (compressor, first_in_statement) { + return this.expression.drop_side_effect_free(compressor, first_in_statement); +}); + +def_drop_side_effect_free(AST_TemplateSegment, return_null); + +def_drop_side_effect_free(AST_TemplateString, function (compressor) { + var values = trim(this.segments, compressor, first_in_statement); + return values && make_sequence(this, values); +}); diff --git a/node_modules/terser/lib/compress/drop-unused.js b/node_modules/terser/lib/compress/drop-unused.js new file mode 100644 index 0000000..9d9555d --- /dev/null +++ b/node_modules/terser/lib/compress/drop-unused.js @@ -0,0 +1,544 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { + AST_Accessor, + AST_Assign, + AST_BlockStatement, + AST_Call, + AST_Class, + AST_ClassExpression, + AST_ClassStaticBlock, + AST_DefaultAssign, + AST_DefClass, + AST_Definitions, + AST_Defun, + AST_Destructuring, + AST_EmptyStatement, + AST_Expansion, + AST_Export, + AST_For, + AST_ForIn, + AST_Function, + AST_LabeledStatement, + AST_Lambda, + AST_Number, + AST_Scope, + AST_Sequence, + AST_SimpleStatement, + AST_SymbolBlockDeclaration, + AST_SymbolCatch, + AST_SymbolDeclaration, + AST_SymbolFunarg, + AST_SymbolRef, + AST_SymbolVar, + AST_Toplevel, + AST_Unary, + AST_Var, + + TreeTransformer, + TreeWalker, + walk, +} from "../ast.js"; +import { + keep_name, + make_node, + map_add, + MAP, + remove, + return_false, +} from "../utils/index.js"; +import { SymbolDef } from "../scope.js"; + +import { + WRITE_ONLY, + UNUSED, + + has_flag, + set_flag, +} from "./compressor-flags.js"; +import { + make_sequence, + maintain_this_binding, + is_empty, + is_ref_of, + can_be_evicted_from_block, + requires_sequence_to_maintain_binding, +} from "./common.js"; + +const r_keep_assign = /keep_assign/; + +/** Drop unused variables from this scope */ +AST_Scope.DEFMETHOD("drop_unused", function(compressor) { + if (!compressor.option("unused")) return; + if (compressor.has_directive("use asm")) return; + if (!this.variables) return; // not really a scope (eg: AST_Class) + + var self = this; + if (self.pinned()) return; + var drop_funcs = !(self instanceof AST_Toplevel) || compressor.toplevel.funcs; + var drop_vars = !(self instanceof AST_Toplevel) || compressor.toplevel.vars; + const assign_as_unused = r_keep_assign.test(compressor.option("unused")) ? return_false : function(node) { + if (node instanceof AST_Assign + && !node.logical + && (has_flag(node, WRITE_ONLY) || node.operator == "=") + ) { + return node.left; + } + if (node instanceof AST_Unary && has_flag(node, WRITE_ONLY)) { + return node.expression; + } + }; + var in_use_ids = new Map(); + var fixed_ids = new Map(); + if (self instanceof AST_Toplevel && compressor.top_retain) { + self.variables.forEach(function(def) { + if (compressor.top_retain(def)) { + in_use_ids.set(def.id, def); + } + }); + } + var var_defs_by_id = new Map(); + var initializations = new Map(); + + // pass 1: find out which symbols are directly used in + // this scope (not in nested scopes). + var scope = this; + var tw = new TreeWalker(function(node, descend) { + if (node instanceof AST_Lambda && node.uses_arguments && !tw.has_directive("use strict")) { + node.argnames.forEach(function(argname) { + if (!(argname instanceof AST_SymbolDeclaration)) return; + var def = argname.definition(); + in_use_ids.set(def.id, def); + }); + } + if (node === self) return; + if (node instanceof AST_Class && node.has_side_effects(compressor)) { + if (node.is_self_referential()) { + descend(); + } else { + node.visit_nondeferred_class_parts(tw); + } + } + if (node instanceof AST_Defun || node instanceof AST_DefClass) { + var node_def = node.name.definition(); + const in_export = tw.parent() instanceof AST_Export; + if (in_export || !drop_funcs && scope === self) { + if (node_def.global) { + in_use_ids.set(node_def.id, node_def); + } + } + + map_add(initializations, node_def.id, node); + return true; // don't go in nested scopes + } + // In the root scope, we drop things. In inner scopes, we just check for uses. + const in_root_scope = scope === self; + if (node instanceof AST_SymbolFunarg && in_root_scope) { + map_add(var_defs_by_id, node.definition().id, node); + } + if (node instanceof AST_Definitions && in_root_scope) { + const in_export = tw.parent() instanceof AST_Export; + node.definitions.forEach(function(def) { + if (def.name instanceof AST_SymbolVar) { + map_add(var_defs_by_id, def.name.definition().id, def); + } + if (in_export || !drop_vars) { + walk(def.name, node => { + if (node instanceof AST_SymbolDeclaration) { + const def = node.definition(); + if (def.global) { + in_use_ids.set(def.id, def); + } + } + }); + } + if (def.name instanceof AST_Destructuring) { + def.walk(tw); + } + if (def.name instanceof AST_SymbolDeclaration && def.value) { + var node_def = def.name.definition(); + map_add(initializations, node_def.id, def.value); + if (!node_def.chained && def.name.fixed_value() === def.value) { + fixed_ids.set(node_def.id, def); + } + if (def.value.has_side_effects(compressor)) { + def.value.walk(tw); + } + } + }); + return true; + } + return scan_ref_scoped(node, descend); + }); + self.walk(tw); + // pass 2: for every used symbol we need to walk its + // initialization code to figure out if it uses other + // symbols (that may not be in_use). + tw = new TreeWalker(scan_ref_scoped); + in_use_ids.forEach(function (def) { + var init = initializations.get(def.id); + if (init) init.forEach(function(init) { + init.walk(tw); + }); + }); + // pass 3: we should drop declarations not in_use + var tt = new TreeTransformer( + function before(node, descend, in_list) { + var parent = tt.parent(); + if (drop_vars) { + const sym = assign_as_unused(node); + if (sym instanceof AST_SymbolRef) { + var def = sym.definition(); + var in_use = in_use_ids.has(def.id); + if (node instanceof AST_Assign) { + if (!in_use || fixed_ids.has(def.id) && fixed_ids.get(def.id) !== node) { + const assignee = node.right.transform(tt); + if (!in_use && !assignee.has_side_effects(compressor) && !is_used_in_expression(tt)) { + return in_list ? MAP.skip : make_node(AST_Number, node, { value: 0 }); + } + return maintain_this_binding(parent, node, assignee); + } + } else if (!in_use) { + return in_list ? MAP.skip : make_node(AST_Number, node, { value: 0 }); + } + } + } + if (scope !== self) return; + var def; + if (node.name + && (node instanceof AST_ClassExpression + && !keep_name(compressor.option("keep_classnames"), (def = node.name.definition()).name) + || node instanceof AST_Function + && !keep_name(compressor.option("keep_fnames"), (def = node.name.definition()).name))) { + // any declarations with same name will overshadow + // name of this anonymous function and can therefore + // never be used anywhere + if (!in_use_ids.has(def.id) || def.orig.length > 1) node.name = null; + } + if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) { + var trim = + !compressor.option("keep_fargs") + // Is this an IIFE that won't refer to its name? + || parent instanceof AST_Call + && parent.expression === node + && !node.pinned() + && (!node.name || node.name.unreferenced()); + for (var a = node.argnames, i = a.length; --i >= 0;) { + var sym = a[i]; + if (sym instanceof AST_Expansion) { + sym = sym.expression; + } + if (sym instanceof AST_DefaultAssign) { + sym = sym.left; + } + // Do not drop destructuring arguments. + // They constitute a type assertion of sorts + if ( + !(sym instanceof AST_Destructuring) + && !in_use_ids.has(sym.definition().id) + ) { + set_flag(sym, UNUSED); + if (trim) { + a.pop(); + } + } else { + trim = false; + } + } + } + if (node instanceof AST_DefClass && node !== self) { + const def = node.name.definition(); + descend(node, this); + const keep_class = def.global && !drop_funcs || in_use_ids.has(def.id); + if (!keep_class) { + const kept = node.drop_side_effect_free(compressor); + if (kept == null) { + def.eliminated++; + return in_list ? MAP.skip : make_node(AST_EmptyStatement, node); + } + return kept; + } + return node; + } + if (node instanceof AST_Defun && node !== self) { + const def = node.name.definition(); + const keep = def.global && !drop_funcs || in_use_ids.has(def.id); + if (!keep) { + def.eliminated++; + return in_list ? MAP.skip : make_node(AST_EmptyStatement, node); + } + } + if (node instanceof AST_Definitions && !(parent instanceof AST_ForIn && parent.init === node)) { + var drop_block = !(parent instanceof AST_Toplevel) && !(node instanceof AST_Var); + // place uninitialized names at the start + var body = [], head = [], tail = []; + // for unused names whose initialization has + // side effects, we can cascade the init. code + // into the next one, or next statement. + var side_effects = []; + node.definitions.forEach(function(def) { + if (def.value) def.value = def.value.transform(tt); + var is_destructure = def.name instanceof AST_Destructuring; + var sym = is_destructure + ? new SymbolDef(null, { name: "" }) /* fake SymbolDef */ + : def.name.definition(); + if (drop_block && sym.global) return tail.push(def); + if (!(drop_vars || drop_block) + || is_destructure + && (def.name.names.length + || def.name.is_array + || compressor.option("pure_getters") != true) + || in_use_ids.has(sym.id) + ) { + if (def.value && fixed_ids.has(sym.id) && fixed_ids.get(sym.id) !== def) { + def.value = def.value.drop_side_effect_free(compressor); + } + if (def.name instanceof AST_SymbolVar) { + var var_defs = var_defs_by_id.get(sym.id); + if (var_defs.length > 1 && (!def.value || sym.orig.indexOf(def.name) > sym.eliminated)) { + if (def.value) { + var ref = make_node(AST_SymbolRef, def.name, def.name); + sym.references.push(ref); + var assign = make_node(AST_Assign, def, { + operator: "=", + logical: false, + left: ref, + right: def.value + }); + if (fixed_ids.get(sym.id) === def) { + fixed_ids.set(sym.id, assign); + } + side_effects.push(assign.transform(tt)); + } + remove(var_defs, def); + sym.eliminated++; + return; + } + } + if (def.value) { + if (side_effects.length > 0) { + if (tail.length > 0) { + side_effects.push(def.value); + def.value = make_sequence(def.value, side_effects); + } else { + body.push(make_node(AST_SimpleStatement, node, { + body: make_sequence(node, side_effects) + })); + } + side_effects = []; + } + tail.push(def); + } else { + head.push(def); + } + } else if (sym.orig[0] instanceof AST_SymbolCatch) { + var value = def.value && def.value.drop_side_effect_free(compressor); + if (value) side_effects.push(value); + def.value = null; + head.push(def); + } else { + var value = def.value && def.value.drop_side_effect_free(compressor); + if (value) { + side_effects.push(value); + } + sym.eliminated++; + } + }); + if (head.length > 0 || tail.length > 0) { + node.definitions = head.concat(tail); + body.push(node); + } + if (side_effects.length > 0) { + body.push(make_node(AST_SimpleStatement, node, { + body: make_sequence(node, side_effects) + })); + } + switch (body.length) { + case 0: + return in_list ? MAP.skip : make_node(AST_EmptyStatement, node); + case 1: + return body[0]; + default: + return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, { body }); + } + } + // certain combination of unused name + side effect leads to: + // https://github.com/mishoo/UglifyJS2/issues/44 + // https://github.com/mishoo/UglifyJS2/issues/1830 + // https://github.com/mishoo/UglifyJS2/issues/1838 + // that's an invalid AST. + // We fix it at this stage by moving the `var` outside the `for`. + if (node instanceof AST_For) { + descend(node, this); + var block; + if (node.init instanceof AST_BlockStatement) { + block = node.init; + node.init = block.body.pop(); + block.body.push(node); + } + if (node.init instanceof AST_SimpleStatement) { + node.init = node.init.body; + } else if (is_empty(node.init)) { + node.init = null; + } + return !block ? node : in_list ? MAP.splice(block.body) : block; + } + if (node instanceof AST_LabeledStatement + && node.body instanceof AST_For + ) { + descend(node, this); + if (node.body instanceof AST_BlockStatement) { + var block = node.body; + node.body = block.body.pop(); + block.body.push(node); + return in_list ? MAP.splice(block.body) : block; + } + return node; + } + if (node instanceof AST_BlockStatement) { + descend(node, this); + if (in_list && node.body.every(can_be_evicted_from_block)) { + return MAP.splice(node.body); + } + return node; + } + if (node instanceof AST_Scope && !(node instanceof AST_ClassStaticBlock)) { + const save_scope = scope; + scope = node; + descend(node, this); + scope = save_scope; + return node; + } + }, + function after(node, in_list) { + if (node instanceof AST_Sequence) { + switch (node.expressions.length) { + case 0: return in_list ? MAP.skip : make_node(AST_Number, node, { value: 0 }); + case 1: return node.expressions[0]; + } + } + } + ); + + self.transform(tt); + + function scan_ref_scoped(node, descend) { + var node_def; + const sym = assign_as_unused(node); + if (sym instanceof AST_SymbolRef + && !is_ref_of(node.left, AST_SymbolBlockDeclaration) + && self.variables.get(sym.name) === (node_def = sym.definition()) + ) { + if (node instanceof AST_Assign) { + node.right.walk(tw); + if (!node_def.chained && node.left.fixed_value() === node.right) { + fixed_ids.set(node_def.id, node); + } + } + return true; + } + if (node instanceof AST_SymbolRef) { + node_def = node.definition(); + if (!in_use_ids.has(node_def.id)) { + in_use_ids.set(node_def.id, node_def); + if (node_def.orig[0] instanceof AST_SymbolCatch) { + const redef = node_def.scope.is_block_scope() + && node_def.scope.get_defun_scope().variables.get(node_def.name); + if (redef) in_use_ids.set(redef.id, redef); + } + } + return true; + } + if (node instanceof AST_Class) { + descend(); + return true; + } + if (node instanceof AST_Scope && !(node instanceof AST_ClassStaticBlock)) { + var save_scope = scope; + scope = node; + descend(); + scope = save_scope; + return true; + } + } +}); + +/** + * Check if a node may be used by the expression it's in + * void (0, 1, {node}, 2) -> false + * console.log(0, {node}) -> true + */ +function is_used_in_expression(tw) { + for (let p = -1, node, parent; node = tw.parent(p), parent = tw.parent(p + 1); p++) { + if (parent instanceof AST_Sequence) { + const nth_expression = parent.expressions.indexOf(node); + if (nth_expression !== parent.expressions.length - 1) { + // Detect (0, x.noThis)() constructs + const grandparent = tw.parent(p + 2); + if ( + parent.expressions.length > 2 + || parent.expressions.length === 1 + || !requires_sequence_to_maintain_binding(grandparent, parent, parent.expressions[1]) + ) { + return false; + } + return true; + } else { + continue; + } + } + if (parent instanceof AST_Unary) { + const op = parent.operator; + if (op === "void") { + return false; + } + if (op === "typeof" || op === "+" || op === "-" || op === "!" || op === "~") { + continue; + } + } + return true; + } + + return true; +} diff --git a/node_modules/terser/lib/compress/evaluate.js b/node_modules/terser/lib/compress/evaluate.js new file mode 100644 index 0000000..dcadce4 --- /dev/null +++ b/node_modules/terser/lib/compress/evaluate.js @@ -0,0 +1,516 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { + HOP, + makePredicate, + return_this, + string_template, + regexp_source_fix, + regexp_is_safe, +} from "../utils/index.js"; +import { + AST_Array, + AST_BigInt, + AST_Binary, + AST_Call, + AST_Chain, + AST_Class, + AST_Conditional, + AST_Constant, + AST_Dot, + AST_Expansion, + AST_Function, + AST_Lambda, + AST_New, + AST_Node, + AST_Object, + AST_PropAccess, + AST_RegExp, + AST_Statement, + AST_Symbol, + AST_SymbolRef, + AST_TemplateString, + AST_UnaryPrefix, + AST_With, +} from "../ast.js"; +import { is_undeclared_ref} from "./inference.js"; +import { is_pure_native_value, is_pure_native_fn, is_pure_native_method } from "./native-objects.js"; + +// methods to evaluate a constant expression + +function def_eval(node, func) { + node.DEFMETHOD("_eval", func); +} + +// Used to propagate a nullish short-circuit signal upwards through the chain. +export const nullish = Symbol("This AST_Chain is nullish"); + +// If the node has been successfully reduced to a constant, +// then its value is returned; otherwise the element itself +// is returned. +// They can be distinguished as constant value is never a +// descendant of AST_Node. +AST_Node.DEFMETHOD("evaluate", function (compressor) { + if (!compressor.option("evaluate")) + return this; + var val = this._eval(compressor, 1); + if (!val || val instanceof RegExp) + return val; + if (typeof val == "function" || typeof val == "object" || val == nullish) + return this; + + // Evaluated strings can be larger than the original expression + if (typeof val === "string") { + const unevaluated_size = this.size(compressor); + if (val.length + 2 > unevaluated_size) return this; + } + + return val; +}); + +var unaryPrefix = makePredicate("! ~ - + void"); +AST_Node.DEFMETHOD("is_constant", function () { + // Accomodate when compress option evaluate=false + // as well as the common constant expressions !0 and -1 + if (this instanceof AST_Constant) { + return !(this instanceof AST_RegExp); + } else { + return this instanceof AST_UnaryPrefix + && this.expression instanceof AST_Constant + && unaryPrefix.has(this.operator); + } +}); + +def_eval(AST_Statement, function () { + throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start)); +}); + +def_eval(AST_Lambda, return_this); +def_eval(AST_Class, return_this); +def_eval(AST_Node, return_this); +def_eval(AST_Constant, function () { + return this.getValue(); +}); + +const supports_bigint = typeof BigInt === "function"; +def_eval(AST_BigInt, function () { + if (supports_bigint) { + return BigInt(this.value); + } else { + return this; + } +}); + +def_eval(AST_RegExp, function (compressor) { + let evaluated = compressor.evaluated_regexps.get(this.value); + if (evaluated === undefined && regexp_is_safe(this.value.source)) { + try { + const { source, flags } = this.value; + evaluated = new RegExp(source, flags); + } catch (e) { + evaluated = null; + } + compressor.evaluated_regexps.set(this.value, evaluated); + } + return evaluated || this; +}); + +def_eval(AST_TemplateString, function () { + if (this.segments.length !== 1) return this; + return this.segments[0].value; +}); + +def_eval(AST_Function, function (compressor) { + if (compressor.option("unsafe")) { + var fn = function () { }; + fn.node = this; + fn.toString = () => this.print_to_string(); + return fn; + } + return this; +}); + +def_eval(AST_Array, function (compressor, depth) { + if (compressor.option("unsafe")) { + var elements = []; + for (var i = 0, len = this.elements.length; i < len; i++) { + var element = this.elements[i]; + var value = element._eval(compressor, depth); + if (element === value) + return this; + elements.push(value); + } + return elements; + } + return this; +}); + +def_eval(AST_Object, function (compressor, depth) { + if (compressor.option("unsafe")) { + var val = {}; + for (var i = 0, len = this.properties.length; i < len; i++) { + var prop = this.properties[i]; + if (prop instanceof AST_Expansion) + return this; + var key = prop.key; + if (key instanceof AST_Symbol) { + key = key.name; + } else if (key instanceof AST_Node) { + key = key._eval(compressor, depth); + if (key === prop.key) + return this; + } + if (typeof Object.prototype[key] === "function") { + return this; + } + if (prop.value instanceof AST_Function) + continue; + val[key] = prop.value._eval(compressor, depth); + if (val[key] === prop.value) + return this; + } + return val; + } + return this; +}); + +var non_converting_unary = makePredicate("! typeof void"); +def_eval(AST_UnaryPrefix, function (compressor, depth) { + var e = this.expression; + if (compressor.option("typeofs") + && this.operator == "typeof") { + // Function would be evaluated to an array and so typeof would + // incorrectly return 'object'. Hence making is a special case. + if (e instanceof AST_Lambda + || e instanceof AST_SymbolRef + && e.fixed_value() instanceof AST_Lambda) { + return typeof function () { }; + } + if ( + (e instanceof AST_Object + || e instanceof AST_Array + || (e instanceof AST_SymbolRef + && (e.fixed_value() instanceof AST_Object + || e.fixed_value() instanceof AST_Array))) + && !e.has_side_effects(compressor) + ) { + return typeof {}; + } + } + if (!non_converting_unary.has(this.operator)) + depth++; + e = e._eval(compressor, depth); + if (e === this.expression) + return this; + switch (this.operator) { + case "!": return !e; + case "typeof": + // typeof returns "object" or "function" on different platforms + // so cannot evaluate reliably + if (e instanceof RegExp) + return this; + return typeof e; + case "void": return void e; + case "~": return ~e; + case "-": return -e; + case "+": return +e; + } + return this; +}); + +var non_converting_binary = makePredicate("&& || ?? === !=="); +const identity_comparison = makePredicate("== != === !=="); +const has_identity = value => typeof value === "object" + || typeof value === "function" + || typeof value === "symbol"; + +def_eval(AST_Binary, function (compressor, depth) { + if (!non_converting_binary.has(this.operator)) + depth++; + + var left = this.left._eval(compressor, depth); + if (left === this.left) + return this; + var right = this.right._eval(compressor, depth); + if (right === this.right) + return this; + + if (left != null + && right != null + && identity_comparison.has(this.operator) + && has_identity(left) + && has_identity(right) + && typeof left === typeof right) { + // Do not compare by reference + return this; + } + + // Do not mix BigInt and Number; Don't use `>>>` on BigInt or `/ 0n` + if ( + (typeof left === "bigint") !== (typeof right === "bigint") + || typeof left === "bigint" + && (this.operator === ">>>" + || this.operator === "/" && Number(right) === 0) + ) { + return this; + } + + var result; + switch (this.operator) { + case "&&": result = left && right; break; + case "||": result = left || right; break; + case "??": result = left != null ? left : right; break; + case "|": result = left | right; break; + case "&": result = left & right; break; + case "^": result = left ^ right; break; + case "+": result = left + right; break; + case "*": result = left * right; break; + case "**": result = left ** right; break; + case "/": result = left / right; break; + case "%": result = left % right; break; + case "-": result = left - right; break; + case "<<": result = left << right; break; + case ">>": result = left >> right; break; + case ">>>": result = left >>> right; break; + case "==": result = left == right; break; + case "===": result = left === right; break; + case "!=": result = left != right; break; + case "!==": result = left !== right; break; + case "<": result = left < right; break; + case "<=": result = left <= right; break; + case ">": result = left > right; break; + case ">=": result = left >= right; break; + default: + return this; + } + if (typeof result === "number" && isNaN(result) && compressor.find_parent(AST_With)) { + // leave original expression as is + return this; + } + return result; +}); + +def_eval(AST_Conditional, function (compressor, depth) { + var condition = this.condition._eval(compressor, depth); + if (condition === this.condition) + return this; + var node = condition ? this.consequent : this.alternative; + var value = node._eval(compressor, depth); + return value === node ? this : value; +}); + +// Set of AST_SymbolRef which are currently being evaluated. +// Avoids infinite recursion of ._eval() +const reentrant_ref_eval = new Set(); +def_eval(AST_SymbolRef, function (compressor, depth) { + if (reentrant_ref_eval.has(this)) + return this; + + var fixed = this.fixed_value(); + if (!fixed) + return this; + + reentrant_ref_eval.add(this); + const value = fixed._eval(compressor, depth); + reentrant_ref_eval.delete(this); + + if (value === fixed) + return this; + + if (value && typeof value == "object") { + var escaped = this.definition().escaped; + if (escaped && depth > escaped) + return this; + } + return value; +}); + +const global_objs = { Array, Math, Number, Object, String }; + +const regexp_flags = new Set([ + "dotAll", + "global", + "ignoreCase", + "multiline", + "sticky", + "unicode", +]); + +def_eval(AST_PropAccess, function (compressor, depth) { + let obj = this.expression._eval(compressor, depth + 1); + if (obj === nullish || (this.optional && obj == null)) return nullish; + + // `.length` of strings and arrays is always safe + if (this.property === "length") { + if (typeof obj === "string") { + return obj.length; + } + + const is_spreadless_array = + obj instanceof AST_Array + && obj.elements.every(el => !(el instanceof AST_Expansion)); + + if ( + is_spreadless_array + && obj.elements.every(el => !el.has_side_effects(compressor)) + ) { + return obj.elements.length; + } + } + + if (compressor.option("unsafe")) { + var key = this.property; + if (key instanceof AST_Node) { + key = key._eval(compressor, depth); + if (key === this.property) + return this; + } + + var exp = this.expression; + if (is_undeclared_ref(exp)) { + var aa; + var first_arg = exp.name === "hasOwnProperty" + && key === "call" + && (aa = compressor.parent() && compressor.parent().args) + && (aa && aa[0] + && aa[0].evaluate(compressor)); + + first_arg = first_arg instanceof AST_Dot ? first_arg.expression : first_arg; + + if (first_arg == null || first_arg.thedef && first_arg.thedef.undeclared) { + return this.clone(); + } + if (!is_pure_native_value(exp.name, key)) + return this; + obj = global_objs[exp.name]; + } else { + if (obj instanceof RegExp) { + if (key == "source") { + return regexp_source_fix(obj.source); + } else if (key == "flags" || regexp_flags.has(key)) { + return obj[key]; + } + } + if (!obj || obj === exp || !HOP(obj, key)) + return this; + + if (typeof obj == "function") + switch (key) { + case "name": + return obj.node.name ? obj.node.name.name : ""; + case "length": + return obj.node.length_property(); + default: + return this; + } + } + return obj[key]; + } + return this; +}); + +def_eval(AST_Chain, function (compressor, depth) { + const evaluated = this.expression._eval(compressor, depth); + return evaluated === nullish + ? undefined + : evaluated === this.expression + ? this + : evaluated; +}); + +def_eval(AST_Call, function (compressor, depth) { + var exp = this.expression; + + const callee = exp._eval(compressor, depth); + if (callee === nullish || (this.optional && callee == null)) return nullish; + + if (compressor.option("unsafe") && exp instanceof AST_PropAccess) { + var key = exp.property; + if (key instanceof AST_Node) { + key = key._eval(compressor, depth); + if (key === exp.property) + return this; + } + var val; + var e = exp.expression; + if (is_undeclared_ref(e)) { + var first_arg = e.name === "hasOwnProperty" && + key === "call" && + (this.args[0] && this.args[0].evaluate(compressor)); + + first_arg = first_arg instanceof AST_Dot ? first_arg.expression : first_arg; + + if ((first_arg == null || first_arg.thedef && first_arg.thedef.undeclared)) { + return this.clone(); + } + if (!is_pure_native_fn(e.name, key)) return this; + val = global_objs[e.name]; + } else { + val = e._eval(compressor, depth + 1); + if (val === e || !val) + return this; + if (!is_pure_native_method(val.constructor.name, key)) + return this; + } + var args = []; + for (var i = 0, len = this.args.length; i < len; i++) { + var arg = this.args[i]; + var value = arg._eval(compressor, depth); + if (arg === value) + return this; + if (arg instanceof AST_Lambda) + return this; + args.push(value); + } + try { + return val[key].apply(val, args); + } catch (ex) { + // We don't really care + } + } + return this; +}); + +// Also a subclass of AST_Call +def_eval(AST_New, return_this); diff --git a/node_modules/terser/lib/compress/global-defs.js b/node_modules/terser/lib/compress/global-defs.js new file mode 100644 index 0000000..e9eb7f5 --- /dev/null +++ b/node_modules/terser/lib/compress/global-defs.js @@ -0,0 +1,92 @@ +import { + AST_Array, + AST_Chain, + AST_Constant, + AST_Dot, + AST_ImportMeta, + AST_Node, + AST_Object, + AST_ObjectKeyVal, + AST_PropAccess, + AST_SymbolDeclaration, + AST_SymbolRef, + AST_Toplevel, + TreeTransformer, +} from "../ast.js"; +import { make_node, noop, HOP } from "../utils/index.js"; +import { make_node_from_constant } from "./common.js"; +import { is_lhs } from "./inference.js"; + +(function(def_find_defs) { + function to_node(value, orig) { + if (value instanceof AST_Node) { + if (!(value instanceof AST_Constant)) { + // Value may be a function, an array including functions and even a complex assign / block expression, + // so it should never be shared in different places. + // Otherwise wrong information may be used in the compression phase + value = value.clone(true); + } + return make_node(value.CTOR, orig, value); + } + if (Array.isArray(value)) return make_node(AST_Array, orig, { + elements: value.map(function(value) { + return to_node(value, orig); + }) + }); + if (value && typeof value == "object") { + var props = []; + for (var key in value) if (HOP(value, key)) { + props.push(make_node(AST_ObjectKeyVal, orig, { + key: key, + value: to_node(value[key], orig) + })); + } + return make_node(AST_Object, orig, { + properties: props + }); + } + return make_node_from_constant(value, orig); + } + + AST_Toplevel.DEFMETHOD("resolve_defines", function(compressor) { + if (!compressor.option("global_defs")) return this; + this.figure_out_scope({ ie8: compressor.option("ie8") }); + return this.transform(new TreeTransformer(function(node) { + var def = node._find_defs(compressor, ""); + if (!def) return; + var level = 0, child = node, parent; + while (parent = this.parent(level++)) { + if (!(parent instanceof AST_PropAccess)) break; + if (parent.expression !== child) break; + child = parent; + } + if (is_lhs(child, parent)) { + return; + } + return def; + })); + }); + def_find_defs(AST_Node, noop); + def_find_defs(AST_Chain, function(compressor, suffix) { + return this.expression._find_defs(compressor, suffix); + }); + def_find_defs(AST_Dot, function(compressor, suffix) { + return this.expression._find_defs(compressor, "." + this.property + suffix); + }); + def_find_defs(AST_SymbolDeclaration, function() { + if (!this.global()) return; + }); + def_find_defs(AST_SymbolRef, function(compressor, suffix) { + if (!this.global()) return; + var defines = compressor.option("global_defs"); + var name = this.name + suffix; + if (HOP(defines, name)) return to_node(defines[name], this); + }); + def_find_defs(AST_ImportMeta, function(compressor, suffix) { + var defines = compressor.option("global_defs"); + var name = "import.meta" + suffix; + if (HOP(defines, name)) return to_node(defines[name], this); + }); +})(function(node, func) { + node.DEFMETHOD("_find_defs", func); +}); diff --git a/node_modules/terser/lib/compress/index.js b/node_modules/terser/lib/compress/index.js new file mode 100644 index 0000000..60a7c19 --- /dev/null +++ b/node_modules/terser/lib/compress/index.js @@ -0,0 +1,4068 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { + AST_Accessor, + AST_Array, + AST_Arrow, + AST_Assign, + AST_BigInt, + AST_Binary, + AST_Block, + AST_BlockStatement, + AST_Boolean, + AST_Break, + AST_Call, + AST_Catch, + AST_Chain, + AST_Class, + AST_ClassProperty, + AST_ClassStaticBlock, + AST_ConciseMethod, + AST_Conditional, + AST_Const, + AST_Constant, + AST_Debugger, + AST_Default, + AST_DefaultAssign, + AST_Definitions, + AST_Defun, + AST_Destructuring, + AST_Directive, + AST_Do, + AST_Dot, + AST_DWLoop, + AST_EmptyStatement, + AST_Exit, + AST_Expansion, + AST_Export, + AST_False, + AST_For, + AST_ForIn, + AST_Function, + AST_Hole, + AST_If, + AST_Import, + AST_Infinity, + AST_LabeledStatement, + AST_Lambda, + AST_Let, + AST_NaN, + AST_New, + AST_Node, + AST_Null, + AST_Number, + AST_Object, + AST_ObjectKeyVal, + AST_ObjectProperty, + AST_PrefixedTemplateString, + AST_PropAccess, + AST_RegExp, + AST_Return, + AST_Scope, + AST_Sequence, + AST_SimpleStatement, + AST_Statement, + AST_String, + AST_Sub, + AST_Switch, + AST_SwitchBranch, + AST_Symbol, + AST_SymbolClassProperty, + AST_SymbolDeclaration, + AST_SymbolDefun, + AST_SymbolExport, + AST_SymbolFunarg, + AST_SymbolLambda, + AST_SymbolLet, + AST_SymbolMethod, + AST_SymbolRef, + AST_TemplateString, + AST_This, + AST_Toplevel, + AST_True, + AST_Try, + AST_Unary, + AST_UnaryPostfix, + AST_UnaryPrefix, + AST_Undefined, + AST_Var, + AST_VarDef, + AST_While, + AST_With, + AST_Yield, + + TreeTransformer, + TreeWalker, + walk, + walk_abort, + + _NOINLINE, +} from "../ast.js"; +import { + defaults, + HOP, + make_node, + makePredicate, + MAP, + remove, + return_false, + return_true, + regexp_source_fix, + has_annotation, + regexp_is_safe, +} from "../utils/index.js"; +import { first_in_statement } from "../utils/first_in_statement.js"; +import { equivalent_to } from "../equivalent-to.js"; +import { + is_basic_identifier_string, + JS_Parse_Error, + parse, + PRECEDENCE, +} from "../parse.js"; +import { OutputStream } from "../output.js"; +import { base54, format_mangler_options } from "../scope.js"; +import "../size.js"; + +import "./evaluate.js"; +import "./drop-side-effect-free.js"; +import "./drop-unused.js"; +import "./reduce-vars.js"; +import { + is_undeclared_ref, + bitwise_binop, + lazy_op, + is_nullish, + is_undefined, + is_lhs, + aborts, +} from "./inference.js"; +import { + SQUEEZED, + OPTIMIZED, + CLEAR_BETWEEN_PASSES, + TOP, + UNDEFINED, + UNUSED, + TRUTHY, + FALSY, + + has_flag, + set_flag, + clear_flag, +} from "./compressor-flags.js"; +import { + make_sequence, + best_of, + best_of_expression, + make_node_from_constant, + merge_sequence, + get_simple_key, + has_break_or_continue, + maintain_this_binding, + is_empty, + is_identifier_atom, + is_reachable, + can_be_evicted_from_block, + as_statement_array, + is_func_expr, +} from "./common.js"; +import { tighten_body, trim_unreachable_code } from "./tighten-body.js"; +import { inline_into_symbolref, inline_into_call } from "./inline.js"; +import "./global-defs.js"; + +class Compressor extends TreeWalker { + constructor(options, { false_by_default = false, mangle_options = false }) { + super(); + if (options.defaults !== undefined && !options.defaults) false_by_default = true; + this.options = defaults(options, { + arguments : false, + arrows : !false_by_default, + booleans : !false_by_default, + booleans_as_integers : false, + collapse_vars : !false_by_default, + comparisons : !false_by_default, + computed_props: !false_by_default, + conditionals : !false_by_default, + dead_code : !false_by_default, + defaults : true, + directives : !false_by_default, + drop_console : false, + drop_debugger : !false_by_default, + ecma : 5, + evaluate : !false_by_default, + expression : false, + global_defs : false, + hoist_funs : false, + hoist_props : !false_by_default, + hoist_vars : false, + ie8 : false, + if_return : !false_by_default, + inline : !false_by_default, + join_vars : !false_by_default, + keep_classnames: false, + keep_fargs : true, + keep_fnames : false, + keep_infinity : false, + lhs_constants : !false_by_default, + loops : !false_by_default, + module : false, + negate_iife : !false_by_default, + passes : 1, + properties : !false_by_default, + pure_getters : !false_by_default && "strict", + pure_funcs : null, + pure_new : false, + reduce_funcs : !false_by_default, + reduce_vars : !false_by_default, + sequences : !false_by_default, + side_effects : !false_by_default, + switches : !false_by_default, + top_retain : null, + toplevel : !!(options && options["top_retain"]), + typeofs : !false_by_default, + unsafe : false, + unsafe_arrows : false, + unsafe_comps : false, + unsafe_Function: false, + unsafe_math : false, + unsafe_symbols: false, + unsafe_methods: false, + unsafe_proto : false, + unsafe_regexp : false, + unsafe_undefined: false, + unused : !false_by_default, + warnings : false // legacy + }, true); + var global_defs = this.options["global_defs"]; + if (typeof global_defs == "object") for (var key in global_defs) { + if (key[0] === "@" && HOP(global_defs, key)) { + global_defs[key.slice(1)] = parse(global_defs[key], { + expression: true + }); + } + } + if (this.options["inline"] === true) this.options["inline"] = 3; + var pure_funcs = this.options["pure_funcs"]; + if (typeof pure_funcs == "function") { + this.pure_funcs = pure_funcs; + } else { + this.pure_funcs = pure_funcs ? function(node) { + return !pure_funcs.includes(node.expression.print_to_string()); + } : return_true; + } + var top_retain = this.options["top_retain"]; + if (top_retain instanceof RegExp) { + this.top_retain = function(def) { + return top_retain.test(def.name); + }; + } else if (typeof top_retain == "function") { + this.top_retain = top_retain; + } else if (top_retain) { + if (typeof top_retain == "string") { + top_retain = top_retain.split(/,/); + } + this.top_retain = function(def) { + return top_retain.includes(def.name); + }; + } + if (this.options["module"]) { + this.directives["use strict"] = true; + this.options["toplevel"] = true; + } + var toplevel = this.options["toplevel"]; + this.toplevel = typeof toplevel == "string" ? { + funcs: /funcs/.test(toplevel), + vars: /vars/.test(toplevel) + } : { + funcs: toplevel, + vars: toplevel + }; + var sequences = this.options["sequences"]; + this.sequences_limit = sequences == 1 ? 800 : sequences | 0; + this.evaluated_regexps = new Map(); + this._toplevel = undefined; + this._mangle_options = mangle_options + ? format_mangler_options(mangle_options) + : mangle_options; + } + + mangle_options() { + var nth_identifier = this._mangle_options && this._mangle_options.nth_identifier || base54; + var module = this._mangle_options && this._mangle_options.module || this.option("module"); + return { ie8: this.option("ie8"), nth_identifier, module }; + } + + option(key) { + return this.options[key]; + } + + exposed(def) { + if (def.export) return true; + if (def.global) for (var i = 0, len = def.orig.length; i < len; i++) + if (!this.toplevel[def.orig[i] instanceof AST_SymbolDefun ? "funcs" : "vars"]) + return true; + return false; + } + + in_boolean_context() { + if (!this.option("booleans")) return false; + var self = this.self(); + for (var i = 0, p; p = this.parent(i); i++) { + if (p instanceof AST_SimpleStatement + || p instanceof AST_Conditional && p.condition === self + || p instanceof AST_DWLoop && p.condition === self + || p instanceof AST_For && p.condition === self + || p instanceof AST_If && p.condition === self + || p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self) { + return true; + } + if ( + p instanceof AST_Binary + && ( + p.operator == "&&" + || p.operator == "||" + || p.operator == "??" + ) + || p instanceof AST_Conditional + || p.tail_node() === self + ) { + self = p; + } else { + return false; + } + } + } + + in_32_bit_context() { + if (!this.option("evaluate")) return false; + var self = this.self(); + for (var i = 0, p; p = this.parent(i); i++) { + if (p instanceof AST_Binary && bitwise_binop.has(p.operator)) { + return true; + } + if (p instanceof AST_UnaryPrefix) { + return p.operator === "~"; + } + if ( + p instanceof AST_Binary + && ( + p.operator == "&&" + || p.operator == "||" + || p.operator == "??" + ) + || p instanceof AST_Conditional && p.condition !== self + || p.tail_node() === self + ) { + self = p; + } else { + return false; + } + } + } + + in_computed_key() { + if (!this.option("evaluate")) return false; + var self = this.self(); + for (var i = 0, p; p = this.parent(i); i++) { + if (p instanceof AST_ObjectProperty && p.key === self) { + return true; + } + } + return false; + } + + get_toplevel() { + return this._toplevel; + } + + compress(toplevel) { + toplevel = toplevel.resolve_defines(this); + this._toplevel = toplevel; + if (this.option("expression")) { + this._toplevel.process_expression(true); + } + var passes = +this.options.passes || 1; + var min_count = 1 / 0; + var stopping = false; + var mangle = this.mangle_options(); + for (var pass = 0; pass < passes; pass++) { + this._toplevel.figure_out_scope(mangle); + if (pass === 0 && this.option("drop_console")) { + // must be run before reduce_vars and compress pass + this._toplevel = this._toplevel.drop_console(this.option("drop_console")); + } + if (pass > 0 || this.option("reduce_vars")) { + this._toplevel.reset_opt_flags(this); + } + this._toplevel = this._toplevel.transform(this); + if (passes > 1) { + let count = 0; + walk(this._toplevel, () => { count++; }); + if (count < min_count) { + min_count = count; + stopping = false; + } else if (stopping) { + break; + } else { + stopping = true; + } + } + } + if (this.option("expression")) { + this._toplevel.process_expression(false); + } + toplevel = this._toplevel; + this._toplevel = undefined; + return toplevel; + } + + before(node, descend) { + if (has_flag(node, SQUEEZED)) return node; + var was_scope = false; + if (node instanceof AST_Scope) { + node = node.hoist_properties(this); + node = node.hoist_declarations(this); + was_scope = true; + } + // Before https://github.com/mishoo/UglifyJS2/pull/1602 AST_Node.optimize() + // would call AST_Node.transform() if a different instance of AST_Node is + // produced after def_optimize(). + // This corrupts TreeWalker.stack, which cause AST look-ups to malfunction. + // Migrate and defer all children's AST_Node.transform() to below, which + // will now happen after this parent AST_Node has been properly substituted + // thus gives a consistent AST snapshot. + descend(node, this); + // Existing code relies on how AST_Node.optimize() worked, and omitting the + // following replacement call would result in degraded efficiency of both + // output and performance. + descend(node, this); + var opt = node.optimize(this); + if (was_scope && opt instanceof AST_Scope) { + opt.drop_unused(this); + descend(opt, this); + } + if (opt === node) set_flag(opt, SQUEEZED); + return opt; + } + + /** Alternative to plain is_lhs() which doesn't work within .optimize() */ + is_lhs() { + const self = this.stack[this.stack.length - 1]; + const parent = this.stack[this.stack.length - 2]; + return is_lhs(self, parent); + } +} + +function def_optimize(node, optimizer) { + node.DEFMETHOD("optimize", function(compressor) { + var self = this; + if (has_flag(self, OPTIMIZED)) return self; + if (compressor.has_directive("use asm")) return self; + var opt = optimizer(self, compressor); + set_flag(opt, OPTIMIZED); + return opt; + }); +} + +def_optimize(AST_Node, function(self) { + return self; +}); + +AST_Toplevel.DEFMETHOD("drop_console", function(options) { + var isArray = Array.isArray(options); + + return this.transform(new TreeTransformer(function(self) { + if (self.TYPE !== "Call") { + return; + } + + var exp = self.expression; + + if (!(exp instanceof AST_PropAccess)) { + return; + } + + if (isArray && options.indexOf(exp.property) === -1) { + return; + } + + var name = exp.expression; + while (name.expression) { + name = name.expression; + } + if (is_undeclared_ref(name) && name.name == "console") { + return make_node(AST_Undefined, self); + } + })); +}); + +AST_Node.DEFMETHOD("equivalent_to", function(node) { + return equivalent_to(this, node); +}); + +AST_Scope.DEFMETHOD("process_expression", function(insert, compressor) { + var self = this; + var tt = new TreeTransformer(function(node) { + if (insert && node instanceof AST_SimpleStatement) { + return make_node(AST_Return, node, { + value: node.body + }); + } + if (!insert && node instanceof AST_Return) { + if (compressor) { + var value = node.value && node.value.drop_side_effect_free(compressor, true); + return value + ? make_node(AST_SimpleStatement, node, { body: value }) + : make_node(AST_EmptyStatement, node); + } + return make_node(AST_SimpleStatement, node, { + body: node.value || make_node(AST_UnaryPrefix, node, { + operator: "void", + expression: make_node(AST_Number, node, { + value: 0 + }) + }) + }); + } + if (node instanceof AST_Class || node instanceof AST_Lambda && node !== self) { + return node; + } + if (node instanceof AST_Block) { + var index = node.body.length - 1; + if (index >= 0) { + node.body[index] = node.body[index].transform(tt); + } + } else if (node instanceof AST_If) { + node.body = node.body.transform(tt); + if (node.alternative) { + node.alternative = node.alternative.transform(tt); + } + } else if (node instanceof AST_With) { + node.body = node.body.transform(tt); + } + return node; + }); + self.transform(tt); +}); + +AST_Toplevel.DEFMETHOD("reset_opt_flags", function(compressor) { + const self = this; + const reduce_vars = compressor.option("reduce_vars"); + + const preparation = new TreeWalker(function(node, descend) { + clear_flag(node, CLEAR_BETWEEN_PASSES); + if (reduce_vars) { + if (compressor.top_retain + && node instanceof AST_Defun // Only functions are retained + && preparation.parent() === self + ) { + set_flag(node, TOP); + } + return node.reduce_vars(preparation, descend, compressor); + } + }); + // Stack of look-up tables to keep track of whether a `SymbolDef` has been + // properly assigned before use: + // - `push()` & `pop()` when visiting conditional branches + preparation.safe_ids = Object.create(null); + preparation.in_loop = null; + preparation.loop_ids = new Map(); + preparation.defs_to_safe_ids = new Map(); + self.walk(preparation); +}); + +AST_Symbol.DEFMETHOD("fixed_value", function() { + var fixed = this.thedef.fixed; + if (!fixed || fixed instanceof AST_Node) return fixed; + return fixed(); +}); + +AST_SymbolRef.DEFMETHOD("is_immutable", function() { + var orig = this.definition().orig; + return orig.length == 1 && orig[0] instanceof AST_SymbolLambda; +}); + +function find_variable(compressor, name) { + var scope, i = 0; + while (scope = compressor.parent(i++)) { + if (scope instanceof AST_Scope) break; + if (scope instanceof AST_Catch && scope.argname) { + scope = scope.argname.definition().scope; + break; + } + } + return scope.find_variable(name); +} + +var global_names = makePredicate("Array Boolean clearInterval clearTimeout console Date decodeURI decodeURIComponent encodeURI encodeURIComponent Error escape eval EvalError Function isFinite isNaN JSON Math Number parseFloat parseInt RangeError ReferenceError RegExp Object setInterval setTimeout String SyntaxError TypeError unescape URIError"); +AST_SymbolRef.DEFMETHOD("is_declared", function(compressor) { + return !this.definition().undeclared + || compressor.option("unsafe") && global_names.has(this.name); +}); + +/* -----[ optimizers ]----- */ + +var directives = new Set(["use asm", "use strict"]); +def_optimize(AST_Directive, function(self, compressor) { + if (compressor.option("directives") + && (!directives.has(self.value) || compressor.has_directive(self.value) !== self)) { + return make_node(AST_EmptyStatement, self); + } + return self; +}); + +def_optimize(AST_Debugger, function(self, compressor) { + if (compressor.option("drop_debugger")) + return make_node(AST_EmptyStatement, self); + return self; +}); + +def_optimize(AST_LabeledStatement, function(self, compressor) { + if (self.body instanceof AST_Break + && compressor.loopcontrol_target(self.body) === self.body) { + return make_node(AST_EmptyStatement, self); + } + return self.label.references.length == 0 ? self.body : self; +}); + +def_optimize(AST_Block, function(self, compressor) { + tighten_body(self.body, compressor); + return self; +}); + +function can_be_extracted_from_if_block(node) { + return !( + node instanceof AST_Const + || node instanceof AST_Let + || node instanceof AST_Class + ); +} + +def_optimize(AST_BlockStatement, function(self, compressor) { + tighten_body(self.body, compressor); + switch (self.body.length) { + case 1: + if (!compressor.has_directive("use strict") + && compressor.parent() instanceof AST_If + && can_be_extracted_from_if_block(self.body[0]) + || can_be_evicted_from_block(self.body[0])) { + return self.body[0]; + } + break; + case 0: return make_node(AST_EmptyStatement, self); + } + return self; +}); + +function opt_AST_Lambda(self, compressor) { + tighten_body(self.body, compressor); + if (compressor.option("side_effects") + && self.body.length == 1 + && self.body[0] === compressor.has_directive("use strict")) { + self.body.length = 0; + } + return self; +} +def_optimize(AST_Lambda, opt_AST_Lambda); + +AST_Scope.DEFMETHOD("hoist_declarations", function(compressor) { + var self = this; + if (compressor.has_directive("use asm")) return self; + + var hoist_funs = compressor.option("hoist_funs"); + var hoist_vars = compressor.option("hoist_vars"); + + if (hoist_funs || hoist_vars) { + var dirs = []; + var hoisted = []; + var vars = new Map(), vars_found = 0, var_decl = 0; + // let's count var_decl first, we seem to waste a lot of + // space if we hoist `var` when there's only one. + walk(self, node => { + if (node instanceof AST_Scope && node !== self) + return true; + if (node instanceof AST_Var) { + ++var_decl; + return true; + } + }); + hoist_vars = hoist_vars && var_decl > 1; + var tt = new TreeTransformer( + function before(node) { + if (node !== self) { + if (node instanceof AST_Directive) { + dirs.push(node); + return make_node(AST_EmptyStatement, node); + } + if (hoist_funs && node instanceof AST_Defun + && !(tt.parent() instanceof AST_Export) + && tt.parent() === self) { + hoisted.push(node); + return make_node(AST_EmptyStatement, node); + } + if ( + hoist_vars + && node instanceof AST_Var + && !node.definitions.some(def => def.name instanceof AST_Destructuring) + ) { + node.definitions.forEach(function(def) { + vars.set(def.name.name, def); + ++vars_found; + }); + var seq = node.to_assignments(compressor); + var p = tt.parent(); + if (p instanceof AST_ForIn && p.init === node) { + if (seq == null) { + var def = node.definitions[0].name; + return make_node(AST_SymbolRef, def, def); + } + return seq; + } + if (p instanceof AST_For && p.init === node) { + return seq; + } + if (!seq) return make_node(AST_EmptyStatement, node); + return make_node(AST_SimpleStatement, node, { + body: seq + }); + } + if (node instanceof AST_Scope) + return node; // to avoid descending in nested scopes + } + } + ); + self = self.transform(tt); + if (vars_found > 0) { + // collect only vars which don't show up in self's arguments list + var defs = []; + const is_lambda = self instanceof AST_Lambda; + const args_as_names = is_lambda ? self.args_as_names() : null; + vars.forEach((def, name) => { + if (is_lambda && args_as_names.some((x) => x.name === def.name.name)) { + vars.delete(name); + } else { + def = def.clone(); + def.value = null; + defs.push(def); + vars.set(name, def); + } + }); + if (defs.length > 0) { + // try to merge in assignments + for (var i = 0; i < self.body.length;) { + if (self.body[i] instanceof AST_SimpleStatement) { + var expr = self.body[i].body, sym, assign; + if (expr instanceof AST_Assign + && expr.operator == "=" + && (sym = expr.left) instanceof AST_Symbol + && vars.has(sym.name) + ) { + var def = vars.get(sym.name); + if (def.value) break; + def.value = expr.right; + remove(defs, def); + defs.push(def); + self.body.splice(i, 1); + continue; + } + if (expr instanceof AST_Sequence + && (assign = expr.expressions[0]) instanceof AST_Assign + && assign.operator == "=" + && (sym = assign.left) instanceof AST_Symbol + && vars.has(sym.name) + ) { + var def = vars.get(sym.name); + if (def.value) break; + def.value = assign.right; + remove(defs, def); + defs.push(def); + self.body[i].body = make_sequence(expr, expr.expressions.slice(1)); + continue; + } + } + if (self.body[i] instanceof AST_EmptyStatement) { + self.body.splice(i, 1); + continue; + } + if (self.body[i] instanceof AST_BlockStatement) { + self.body.splice(i, 1, ...self.body[i].body); + continue; + } + break; + } + defs = make_node(AST_Var, self, { + definitions: defs + }); + hoisted.push(defs); + } + } + self.body = dirs.concat(hoisted, self.body); + } + return self; +}); + +AST_Scope.DEFMETHOD("hoist_properties", function(compressor) { + var self = this; + if (!compressor.option("hoist_props") || compressor.has_directive("use asm")) return self; + var top_retain = self instanceof AST_Toplevel && compressor.top_retain || return_false; + var defs_by_id = new Map(); + var hoister = new TreeTransformer(function(node, descend) { + if (node instanceof AST_VarDef) { + const sym = node.name; + let def; + let value; + if (sym.scope === self + && (def = sym.definition()).escaped != 1 + && !def.assignments + && !def.direct_access + && !def.single_use + && !compressor.exposed(def) + && !top_retain(def) + && (value = sym.fixed_value()) === node.value + && value instanceof AST_Object + && !value.properties.some(prop => + prop instanceof AST_Expansion || prop.computed_key() + ) + ) { + descend(node, this); + const defs = new Map(); + const assignments = []; + value.properties.forEach(({ key, value }) => { + const scope = hoister.find_scope(); + const symbol = self.create_symbol(sym.CTOR, { + source: sym, + scope, + conflict_scopes: new Set([ + scope, + ...sym.definition().references.map(ref => ref.scope) + ]), + tentative_name: sym.name + "_" + key + }); + + defs.set(String(key), symbol.definition()); + + assignments.push(make_node(AST_VarDef, node, { + name: symbol, + value + })); + }); + defs_by_id.set(def.id, defs); + return MAP.splice(assignments); + } + } else if (node instanceof AST_PropAccess + && node.expression instanceof AST_SymbolRef + ) { + const defs = defs_by_id.get(node.expression.definition().id); + if (defs) { + const def = defs.get(String(get_simple_key(node.property))); + const sym = make_node(AST_SymbolRef, node, { + name: def.name, + scope: node.expression.scope, + thedef: def + }); + sym.reference({}); + return sym; + } + } + }); + return self.transform(hoister); +}); + +def_optimize(AST_SimpleStatement, function(self, compressor) { + if (compressor.option("side_effects")) { + var body = self.body; + var node = body.drop_side_effect_free(compressor, true); + if (!node) { + return make_node(AST_EmptyStatement, self); + } + if (node !== body) { + return make_node(AST_SimpleStatement, self, { body: node }); + } + } + return self; +}); + +def_optimize(AST_While, function(self, compressor) { + return compressor.option("loops") ? make_node(AST_For, self, self).optimize(compressor) : self; +}); + +def_optimize(AST_Do, function(self, compressor) { + if (!compressor.option("loops")) return self; + var cond = self.condition.tail_node().evaluate(compressor); + if (!(cond instanceof AST_Node)) { + if (cond) return make_node(AST_For, self, { + body: make_node(AST_BlockStatement, self.body, { + body: [ + self.body, + make_node(AST_SimpleStatement, self.condition, { + body: self.condition + }) + ] + }) + }).optimize(compressor); + if (!has_break_or_continue(self, compressor.parent())) { + return make_node(AST_BlockStatement, self.body, { + body: [ + self.body, + make_node(AST_SimpleStatement, self.condition, { + body: self.condition + }) + ] + }).optimize(compressor); + } + } + return self; +}); + +function if_break_in_loop(self, compressor) { + var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body; + if (compressor.option("dead_code") && is_break(first)) { + var body = []; + if (self.init instanceof AST_Statement) { + body.push(self.init); + } else if (self.init) { + body.push(make_node(AST_SimpleStatement, self.init, { + body: self.init + })); + } + if (self.condition) { + body.push(make_node(AST_SimpleStatement, self.condition, { + body: self.condition + })); + } + trim_unreachable_code(compressor, self.body, body); + return make_node(AST_BlockStatement, self, { + body: body + }); + } + if (first instanceof AST_If) { + if (is_break(first.body)) { + if (self.condition) { + self.condition = make_node(AST_Binary, self.condition, { + left: self.condition, + operator: "&&", + right: first.condition.negate(compressor), + }); + } else { + self.condition = first.condition.negate(compressor); + } + drop_it(first.alternative); + } else if (is_break(first.alternative)) { + if (self.condition) { + self.condition = make_node(AST_Binary, self.condition, { + left: self.condition, + operator: "&&", + right: first.condition, + }); + } else { + self.condition = first.condition; + } + drop_it(first.body); + } + } + return self; + + function is_break(node) { + return node instanceof AST_Break + && compressor.loopcontrol_target(node) === compressor.self(); + } + + function drop_it(rest) { + rest = as_statement_array(rest); + if (self.body instanceof AST_BlockStatement) { + self.body = self.body.clone(); + self.body.body = rest.concat(self.body.body.slice(1)); + self.body = self.body.transform(compressor); + } else { + self.body = make_node(AST_BlockStatement, self.body, { + body: rest + }).transform(compressor); + } + self = if_break_in_loop(self, compressor); + } +} + +def_optimize(AST_For, function(self, compressor) { + if (!compressor.option("loops")) return self; + if (compressor.option("side_effects") && self.init) { + self.init = self.init.drop_side_effect_free(compressor); + } + if (self.condition) { + var cond = self.condition.evaluate(compressor); + if (!(cond instanceof AST_Node)) { + if (cond) self.condition = null; + else if (!compressor.option("dead_code")) { + var orig = self.condition; + self.condition = make_node_from_constant(cond, self.condition); + self.condition = best_of_expression(self.condition.transform(compressor), orig); + } + } + if (compressor.option("dead_code")) { + if (cond instanceof AST_Node) cond = self.condition.tail_node().evaluate(compressor); + if (!cond) { + var body = []; + trim_unreachable_code(compressor, self.body, body); + if (self.init instanceof AST_Statement) { + body.push(self.init); + } else if (self.init) { + body.push(make_node(AST_SimpleStatement, self.init, { + body: self.init + })); + } + body.push(make_node(AST_SimpleStatement, self.condition, { + body: self.condition + })); + return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor); + } + } + } + return if_break_in_loop(self, compressor); +}); + +def_optimize(AST_If, function(self, compressor) { + if (is_empty(self.alternative)) self.alternative = null; + + if (!compressor.option("conditionals")) return self; + // if condition can be statically determined, drop + // one of the blocks. note, statically determined implies + // “has no side effects”; also it doesn't work for cases like + // `x && true`, though it probably should. + var cond = self.condition.evaluate(compressor); + if (!compressor.option("dead_code") && !(cond instanceof AST_Node)) { + var orig = self.condition; + self.condition = make_node_from_constant(cond, orig); + self.condition = best_of_expression(self.condition.transform(compressor), orig); + } + if (compressor.option("dead_code")) { + if (cond instanceof AST_Node) cond = self.condition.tail_node().evaluate(compressor); + if (!cond) { + var body = []; + trim_unreachable_code(compressor, self.body, body); + body.push(make_node(AST_SimpleStatement, self.condition, { + body: self.condition + })); + if (self.alternative) body.push(self.alternative); + return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor); + } else if (!(cond instanceof AST_Node)) { + var body = []; + body.push(make_node(AST_SimpleStatement, self.condition, { + body: self.condition + })); + body.push(self.body); + if (self.alternative) { + trim_unreachable_code(compressor, self.alternative, body); + } + return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor); + } + } + var negated = self.condition.negate(compressor); + var self_condition_length = self.condition.size(); + var negated_length = negated.size(); + var negated_is_best = negated_length < self_condition_length; + if (self.alternative && negated_is_best) { + negated_is_best = false; // because we already do the switch here. + // no need to swap values of self_condition_length and negated_length + // here because they are only used in an equality comparison later on. + self.condition = negated; + var tmp = self.body; + self.body = self.alternative || make_node(AST_EmptyStatement, self); + self.alternative = tmp; + } + if (is_empty(self.body) && is_empty(self.alternative)) { + return make_node(AST_SimpleStatement, self.condition, { + body: self.condition.clone() + }).optimize(compressor); + } + if (self.body instanceof AST_SimpleStatement + && self.alternative instanceof AST_SimpleStatement) { + return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Conditional, self, { + condition : self.condition, + consequent : self.body.body, + alternative : self.alternative.body + }) + }).optimize(compressor); + } + if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) { + if (self_condition_length === negated_length && !negated_is_best + && self.condition instanceof AST_Binary && self.condition.operator == "||") { + // although the code length of self.condition and negated are the same, + // negated does not require additional surrounding parentheses. + // see https://github.com/mishoo/UglifyJS2/issues/979 + negated_is_best = true; + } + if (negated_is_best) return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Binary, self, { + operator : "||", + left : negated, + right : self.body.body + }) + }).optimize(compressor); + return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Binary, self, { + operator : "&&", + left : self.condition, + right : self.body.body + }) + }).optimize(compressor); + } + if (self.body instanceof AST_EmptyStatement + && self.alternative instanceof AST_SimpleStatement) { + return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Binary, self, { + operator : "||", + left : self.condition, + right : self.alternative.body + }) + }).optimize(compressor); + } + if (self.body instanceof AST_Exit + && self.alternative instanceof AST_Exit + && self.body.TYPE == self.alternative.TYPE) { + return make_node(self.body.CTOR, self, { + value: make_node(AST_Conditional, self, { + condition : self.condition, + consequent : self.body.value || make_node(AST_Undefined, self.body), + alternative : self.alternative.value || make_node(AST_Undefined, self.alternative) + }).transform(compressor) + }).optimize(compressor); + } + if (self.body instanceof AST_If + && !self.body.alternative + && !self.alternative) { + self = make_node(AST_If, self, { + condition: make_node(AST_Binary, self.condition, { + operator: "&&", + left: self.condition, + right: self.body.condition + }), + body: self.body.body, + alternative: null + }); + } + if (aborts(self.body)) { + if (self.alternative) { + var alt = self.alternative; + self.alternative = null; + return make_node(AST_BlockStatement, self, { + body: [ self, alt ] + }).optimize(compressor); + } + } + if (aborts(self.alternative)) { + var body = self.body; + self.body = self.alternative; + self.condition = negated_is_best ? negated : self.condition.negate(compressor); + self.alternative = null; + return make_node(AST_BlockStatement, self, { + body: [ self, body ] + }).optimize(compressor); + } + return self; +}); + +def_optimize(AST_Switch, function(self, compressor) { + if (!compressor.option("switches")) return self; + var branch; + var value = self.expression.evaluate(compressor); + if (!(value instanceof AST_Node)) { + var orig = self.expression; + self.expression = make_node_from_constant(value, orig); + self.expression = best_of_expression(self.expression.transform(compressor), orig); + } + if (!compressor.option("dead_code")) return self; + if (value instanceof AST_Node) { + value = self.expression.tail_node().evaluate(compressor); + } + var decl = []; + var body = []; + var default_branch; + var exact_match; + for (var i = 0, len = self.body.length; i < len && !exact_match; i++) { + branch = self.body[i]; + if (branch instanceof AST_Default) { + if (!default_branch) { + default_branch = branch; + } else { + eliminate_branch(branch, body[body.length - 1]); + } + } else if (!(value instanceof AST_Node)) { + var exp = branch.expression.evaluate(compressor); + if (!(exp instanceof AST_Node) && exp !== value) { + eliminate_branch(branch, body[body.length - 1]); + continue; + } + if (exp instanceof AST_Node && !exp.has_side_effects(compressor)) { + exp = branch.expression.tail_node().evaluate(compressor); + } + if (exp === value) { + exact_match = branch; + if (default_branch) { + var default_index = body.indexOf(default_branch); + body.splice(default_index, 1); + eliminate_branch(default_branch, body[default_index - 1]); + default_branch = null; + } + } + } + body.push(branch); + } + while (i < len) eliminate_branch(self.body[i++], body[body.length - 1]); + self.body = body; + + let default_or_exact = default_branch || exact_match; + default_branch = null; + exact_match = null; + + // group equivalent branches so they will be located next to each other, + // that way the next micro-optimization will merge them. + // ** bail micro-optimization if not a simple switch case with breaks + if (body.every((branch, i) => + (branch === default_or_exact || branch.expression instanceof AST_Constant) + && (branch.body.length === 0 || aborts(branch) || body.length - 1 === i)) + ) { + for (let i = 0; i < body.length; i++) { + const branch = body[i]; + for (let j = i + 1; j < body.length; j++) { + const next = body[j]; + if (next.body.length === 0) continue; + const last_branch = j === (body.length - 1); + const equivalentBranch = branches_equivalent(next, branch, false); + if (equivalentBranch || (last_branch && branches_equivalent(next, branch, true))) { + if (!equivalentBranch && last_branch) { + next.body.push(make_node(AST_Break)); + } + + // let's find previous siblings with inert fallthrough... + let x = j - 1; + let fallthroughDepth = 0; + while (x > i) { + if (is_inert_body(body[x--])) { + fallthroughDepth++; + } else { + break; + } + } + + const plucked = body.splice(j - fallthroughDepth, 1 + fallthroughDepth); + body.splice(i + 1, 0, ...plucked); + i += plucked.length; + } + } + } + } + + // merge equivalent branches in a row + for (let i = 0; i < body.length; i++) { + let branch = body[i]; + if (branch.body.length === 0) continue; + if (!aborts(branch)) continue; + + for (let j = i + 1; j < body.length; i++, j++) { + let next = body[j]; + if (next.body.length === 0) continue; + if ( + branches_equivalent(next, branch, false) + || (j === body.length - 1 && branches_equivalent(next, branch, true)) + ) { + branch.body = []; + branch = next; + continue; + } + break; + } + } + + // Prune any empty branches at the end of the switch statement. + { + let i = body.length - 1; + for (; i >= 0; i--) { + let bbody = body[i].body; + if (is_break(bbody[bbody.length - 1], compressor)) bbody.pop(); + if (!is_inert_body(body[i])) break; + } + // i now points to the index of a branch that contains a body. By incrementing, it's + // pointing to the first branch that's empty. + i++; + if (!default_or_exact || body.indexOf(default_or_exact) >= i) { + // The default behavior is to do nothing. We can take advantage of that to + // remove all case expressions that are side-effect free that also do + // nothing, since they'll default to doing nothing. But we can't remove any + // case expressions before one that would side-effect, since they may cause + // the side-effect to be skipped. + for (let j = body.length - 1; j >= i; j--) { + let branch = body[j]; + if (branch === default_or_exact) { + default_or_exact = null; + body.pop(); + } else if (!branch.expression.has_side_effects(compressor)) { + body.pop(); + } else { + break; + } + } + } + } + + + // Prune side-effect free branches that fall into default. + DEFAULT: if (default_or_exact) { + let default_index = body.indexOf(default_or_exact); + let default_body_index = default_index; + for (; default_body_index < body.length - 1; default_body_index++) { + if (!is_inert_body(body[default_body_index])) break; + } + if (default_body_index < body.length - 1) { + break DEFAULT; + } + + let side_effect_index = body.length - 1; + for (; side_effect_index >= 0; side_effect_index--) { + let branch = body[side_effect_index]; + if (branch === default_or_exact) continue; + if (branch.expression.has_side_effects(compressor)) break; + } + // If the default behavior comes after any side-effect case expressions, + // then we can fold all side-effect free cases into the default branch. + // If the side-effect case is after the default, then any side-effect + // free cases could prevent the side-effect from occurring. + if (default_body_index > side_effect_index) { + let prev_body_index = default_index - 1; + for (; prev_body_index >= 0; prev_body_index--) { + if (!is_inert_body(body[prev_body_index])) break; + } + let before = Math.max(side_effect_index, prev_body_index) + 1; + let after = default_index; + if (side_effect_index > default_index) { + // If the default falls into the same body as a side-effect + // case, then we need preserve that case and only prune the + // cases after it. + after = side_effect_index; + body[side_effect_index].body = body[default_body_index].body; + } else { + // The default will be the last branch. + default_or_exact.body = body[default_body_index].body; + } + + // Prune everything after the default (or last side-effect case) + // until the next case with a body. + body.splice(after + 1, default_body_index - after); + // Prune everything before the default that falls into it. + body.splice(before, default_index - before); + } + } + + // See if we can remove the switch entirely if all cases (the default) fall into the same case body. + DEFAULT: if (default_or_exact) { + let i = body.findIndex(branch => !is_inert_body(branch)); + let caseBody; + // `i` is equal to one of the following: + // - `-1`, there is no body in the switch statement. + // - `body.length - 1`, all cases fall into the same body. + // - anything else, there are multiple bodies in the switch. + if (i === body.length - 1) { + // All cases fall into the case body. + let branch = body[i]; + if (has_nested_break(self)) break DEFAULT; + + // This is the last case body, and we've already pruned any breaks, so it's + // safe to hoist. + caseBody = make_node(AST_BlockStatement, branch, { + body: branch.body + }); + branch.body = []; + } else if (i !== -1) { + // If there are multiple bodies, then we cannot optimize anything. + break DEFAULT; + } + + let sideEffect = body.find( + branch => branch !== default_or_exact && branch.expression.has_side_effects(compressor) + ); + // If no cases cause a side-effect, we can eliminate the switch entirely. + if (!sideEffect) { + return make_node(AST_BlockStatement, self, { + body: decl.concat( + statement(self.expression), + default_or_exact.expression ? statement(default_or_exact.expression) : [], + caseBody || [] + ) + }).optimize(compressor); + } + + // If we're this far, either there was no body or all cases fell into the same body. + // If there was no body, then we don't need a default branch (because the default is + // do nothing). If there was a body, we'll extract it to after the switch, so the + // switch's new default is to do nothing and we can still prune it. + const default_index = body.indexOf(default_or_exact); + body.splice(default_index, 1); + default_or_exact = null; + + if (caseBody) { + // Recurse into switch statement one more time so that we can append the case body + // outside of the switch. This recursion will only happen once since we've pruned + // the default case. + return make_node(AST_BlockStatement, self, { + body: decl.concat(self, caseBody) + }).optimize(compressor); + } + // If we fall here, there is a default branch somewhere, there are no case bodies, + // and there's a side-effect somewhere. Just let the below paths take care of it. + } + + if (body.length > 0) { + body[0].body = decl.concat(body[0].body); + } + + if (body.length == 0) { + return make_node(AST_BlockStatement, self, { + body: decl.concat(statement(self.expression)) + }).optimize(compressor); + } + if (body.length == 1 && !has_nested_break(self)) { + // This is the last case body, and we've already pruned any breaks, so it's + // safe to hoist. + let branch = body[0]; + return make_node(AST_If, self, { + condition: make_node(AST_Binary, self, { + operator: "===", + left: self.expression, + right: branch.expression, + }), + body: make_node(AST_BlockStatement, branch, { + body: branch.body + }), + alternative: null + }).optimize(compressor); + } + if (body.length === 2 && default_or_exact && !has_nested_break(self)) { + let branch = body[0] === default_or_exact ? body[1] : body[0]; + let exact_exp = default_or_exact.expression && statement(default_or_exact.expression); + if (aborts(body[0])) { + // Only the first branch body could have a break (at the last statement) + let first = body[0]; + if (is_break(first.body[first.body.length - 1], compressor)) { + first.body.pop(); + } + return make_node(AST_If, self, { + condition: make_node(AST_Binary, self, { + operator: "===", + left: self.expression, + right: branch.expression, + }), + body: make_node(AST_BlockStatement, branch, { + body: branch.body + }), + alternative: make_node(AST_BlockStatement, default_or_exact, { + body: [].concat( + exact_exp || [], + default_or_exact.body + ) + }) + }).optimize(compressor); + } + let operator = "==="; + let consequent = make_node(AST_BlockStatement, branch, { + body: branch.body, + }); + let always = make_node(AST_BlockStatement, default_or_exact, { + body: [].concat( + exact_exp || [], + default_or_exact.body + ) + }); + if (body[0] === default_or_exact) { + operator = "!=="; + let tmp = always; + always = consequent; + consequent = tmp; + } + return make_node(AST_BlockStatement, self, { + body: [ + make_node(AST_If, self, { + condition: make_node(AST_Binary, self, { + operator: operator, + left: self.expression, + right: branch.expression, + }), + body: consequent, + alternative: null, + }), + always, + ], + }).optimize(compressor); + } + return self; + + function eliminate_branch(branch, prev) { + if (prev && !aborts(prev)) { + prev.body = prev.body.concat(branch.body); + } else { + trim_unreachable_code(compressor, branch, decl); + } + } + function branches_equivalent(branch, prev, insertBreak) { + let bbody = branch.body; + let pbody = prev.body; + if (insertBreak) { + bbody = bbody.concat(make_node(AST_Break)); + } + if (bbody.length !== pbody.length) return false; + let bblock = make_node(AST_BlockStatement, branch, { body: bbody }); + let pblock = make_node(AST_BlockStatement, prev, { body: pbody }); + return bblock.equivalent_to(pblock); + } + function statement(body) { + return make_node(AST_SimpleStatement, body, { body }); + } + function has_nested_break(root) { + let has_break = false; + + let tw = new TreeWalker(node => { + if (has_break) return true; + if (node instanceof AST_Lambda) return true; + if (node instanceof AST_SimpleStatement) return true; + if (!is_break(node, tw)) return; + let parent = tw.parent(); + if ( + parent instanceof AST_SwitchBranch + && parent.body[parent.body.length - 1] === node + ) { + return; + } + has_break = true; + }); + root.walk(tw); + return has_break; + } + function is_break(node, stack) { + return node instanceof AST_Break + && stack.loopcontrol_target(node) === self; + } + function is_inert_body(branch) { + return !aborts(branch) && !make_node(AST_BlockStatement, branch, { + body: branch.body + }).has_side_effects(compressor); + } +}); + +def_optimize(AST_Try, function(self, compressor) { + if (self.bcatch && self.bfinally && self.bfinally.body.every(is_empty)) self.bfinally = null; + + if (compressor.option("dead_code") && self.body.body.every(is_empty)) { + var body = []; + if (self.bcatch) { + trim_unreachable_code(compressor, self.bcatch, body); + } + if (self.bfinally) body.push(...self.bfinally.body); + return make_node(AST_BlockStatement, self, { + body: body + }).optimize(compressor); + } + return self; +}); + +AST_Definitions.DEFMETHOD("to_assignments", function(compressor) { + var reduce_vars = compressor.option("reduce_vars"); + var assignments = []; + + for (const def of this.definitions) { + if (def.value) { + var name = make_node(AST_SymbolRef, def.name, def.name); + assignments.push(make_node(AST_Assign, def, { + operator : "=", + logical: false, + left : name, + right : def.value + })); + if (reduce_vars) name.definition().fixed = false; + } + const thedef = def.name.definition(); + thedef.eliminated++; + thedef.replaced--; + } + + if (assignments.length == 0) return null; + return make_sequence(this, assignments); +}); + +def_optimize(AST_Definitions, function(self) { + if (self.definitions.length == 0) { + return make_node(AST_EmptyStatement, self); + } + return self; +}); + +def_optimize(AST_VarDef, function(self, compressor) { + if ( + self.name instanceof AST_SymbolLet + && self.value != null + && is_undefined(self.value, compressor) + ) { + self.value = null; + } + return self; +}); + +def_optimize(AST_Import, function(self) { + return self; +}); + +def_optimize(AST_Call, function(self, compressor) { + var exp = self.expression; + var fn = exp; + inline_array_like_spread(self.args); + var simple_args = self.args.every((arg) => !(arg instanceof AST_Expansion)); + + if (compressor.option("reduce_vars") && fn instanceof AST_SymbolRef) { + fn = fn.fixed_value(); + } + + var is_func = fn instanceof AST_Lambda; + + if (is_func && fn.pinned()) return self; + + if (compressor.option("unused") + && simple_args + && is_func + && !fn.uses_arguments) { + var pos = 0, last = 0; + for (var i = 0, len = self.args.length; i < len; i++) { + if (fn.argnames[i] instanceof AST_Expansion) { + if (has_flag(fn.argnames[i].expression, UNUSED)) while (i < len) { + var node = self.args[i++].drop_side_effect_free(compressor); + if (node) { + self.args[pos++] = node; + } + } else while (i < len) { + self.args[pos++] = self.args[i++]; + } + last = pos; + break; + } + var trim = i >= fn.argnames.length; + if (trim || has_flag(fn.argnames[i], UNUSED)) { + var node = self.args[i].drop_side_effect_free(compressor); + if (node) { + self.args[pos++] = node; + } else if (!trim) { + self.args[pos++] = make_node(AST_Number, self.args[i], { + value: 0 + }); + continue; + } + } else { + self.args[pos++] = self.args[i]; + } + last = pos; + } + self.args.length = last; + } + + if (compressor.option("unsafe") && !exp.contains_optional()) { + if (exp instanceof AST_Dot && exp.start.value === "Array" && exp.property === "from" && self.args.length === 1) { + const [argument] = self.args; + if (argument instanceof AST_Array) { + return make_node(AST_Array, argument, { + elements: argument.elements + }).optimize(compressor); + } + } + if (is_undeclared_ref(exp)) switch (exp.name) { + case "Array": + if (self.args.length != 1) { + return make_node(AST_Array, self, { + elements: self.args + }).optimize(compressor); + } else if (self.args[0] instanceof AST_Number && self.args[0].value <= 11) { + const elements = []; + for (let i = 0; i < self.args[0].value; i++) elements.push(new AST_Hole); + return new AST_Array({ elements }); + } + break; + case "Object": + if (self.args.length == 0) { + return make_node(AST_Object, self, { + properties: [] + }); + } + break; + case "String": + if (self.args.length == 0) return make_node(AST_String, self, { + value: "" + }); + if (self.args.length <= 1) return make_node(AST_Binary, self, { + left: self.args[0], + operator: "+", + right: make_node(AST_String, self, { value: "" }) + }).optimize(compressor); + break; + case "Number": + if (self.args.length == 0) return make_node(AST_Number, self, { + value: 0 + }); + if (self.args.length == 1 && compressor.option("unsafe_math")) { + return make_node(AST_UnaryPrefix, self, { + expression: self.args[0], + operator: "+" + }).optimize(compressor); + } + break; + case "Symbol": + if (self.args.length == 1 && self.args[0] instanceof AST_String && compressor.option("unsafe_symbols")) + self.args.length = 0; + break; + case "Boolean": + if (self.args.length == 0) return make_node(AST_False, self); + if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, { + expression: make_node(AST_UnaryPrefix, self, { + expression: self.args[0], + operator: "!" + }), + operator: "!" + }).optimize(compressor); + break; + case "RegExp": + var params = []; + if (self.args.length >= 1 + && self.args.length <= 2 + && self.args.every((arg) => { + var value = arg.evaluate(compressor); + params.push(value); + return arg !== value; + }) + && regexp_is_safe(params[0]) + ) { + let [ source, flags ] = params; + source = regexp_source_fix(new RegExp(source).source); + const rx = make_node(AST_RegExp, self, { + value: { source, flags } + }); + if (rx._eval(compressor) !== rx) { + return rx; + } + } + break; + } else if (exp instanceof AST_Dot) switch(exp.property) { + case "toString": + if (self.args.length == 0 && !exp.expression.may_throw_on_access(compressor)) { + return make_node(AST_Binary, self, { + left: make_node(AST_String, self, { value: "" }), + operator: "+", + right: exp.expression + }).optimize(compressor); + } + break; + case "join": + if (exp.expression instanceof AST_Array) EXIT: { + var separator; + if (self.args.length > 0) { + separator = self.args[0].evaluate(compressor); + if (separator === self.args[0]) break EXIT; // not a constant + } + var elements = []; + var consts = []; + for (var i = 0, len = exp.expression.elements.length; i < len; i++) { + var el = exp.expression.elements[i]; + if (el instanceof AST_Expansion) break EXIT; + var value = el.evaluate(compressor); + if (value !== el) { + consts.push(value); + } else { + if (consts.length > 0) { + elements.push(make_node(AST_String, self, { + value: consts.join(separator) + })); + consts.length = 0; + } + elements.push(el); + } + } + if (consts.length > 0) { + elements.push(make_node(AST_String, self, { + value: consts.join(separator) + })); + } + if (elements.length == 0) return make_node(AST_String, self, { value: "" }); + if (elements.length == 1) { + if (elements[0].is_string(compressor)) { + return elements[0]; + } + return make_node(AST_Binary, elements[0], { + operator : "+", + left : make_node(AST_String, self, { value: "" }), + right : elements[0] + }); + } + if (separator == "") { + var first; + if (elements[0].is_string(compressor) + || elements[1].is_string(compressor)) { + first = elements.shift(); + } else { + first = make_node(AST_String, self, { value: "" }); + } + return elements.reduce(function(prev, el) { + return make_node(AST_Binary, el, { + operator : "+", + left : prev, + right : el + }); + }, first).optimize(compressor); + } + // need this awkward cloning to not affect original element + // best_of will decide which one to get through. + var node = self.clone(); + node.expression = node.expression.clone(); + node.expression.expression = node.expression.expression.clone(); + node.expression.expression.elements = elements; + return best_of(compressor, self, node); + } + break; + case "charAt": + if (exp.expression.is_string(compressor)) { + var arg = self.args[0]; + var index = arg ? arg.evaluate(compressor) : 0; + if (index !== arg) { + return make_node(AST_Sub, exp, { + expression: exp.expression, + property: make_node_from_constant(index | 0, arg || exp) + }).optimize(compressor); + } + } + break; + case "apply": + if (self.args.length == 2 && self.args[1] instanceof AST_Array) { + var args = self.args[1].elements.slice(); + args.unshift(self.args[0]); + return make_node(AST_Call, self, { + expression: make_node(AST_Dot, exp, { + expression: exp.expression, + optional: false, + property: "call" + }), + args: args + }).optimize(compressor); + } + break; + case "call": + var func = exp.expression; + if (func instanceof AST_SymbolRef) { + func = func.fixed_value(); + } + if (func instanceof AST_Lambda && !func.contains_this()) { + return (self.args.length ? make_sequence(this, [ + self.args[0], + make_node(AST_Call, self, { + expression: exp.expression, + args: self.args.slice(1) + }) + ]) : make_node(AST_Call, self, { + expression: exp.expression, + args: [] + })).optimize(compressor); + } + break; + } + } + + if (compressor.option("unsafe_Function") + && is_undeclared_ref(exp) + && exp.name == "Function") { + // new Function() => function(){} + if (self.args.length == 0) return make_node(AST_Function, self, { + argnames: [], + body: [] + }).optimize(compressor); + if (self.args.every((x) => x instanceof AST_String)) { + // quite a corner-case, but we can handle it: + // https://github.com/mishoo/UglifyJS2/issues/203 + // if the code argument is a constant, then we can minify it. + try { + var code = "n(function(" + self.args.slice(0, -1).map(function(arg) { + return arg.value; + }).join(",") + "){" + self.args[self.args.length - 1].value + "})"; + var ast = parse(code); + var mangle = compressor.mangle_options(); + ast.figure_out_scope(mangle); + var comp = new Compressor(compressor.options, { + mangle_options: compressor._mangle_options + }); + ast = ast.transform(comp); + ast.figure_out_scope(mangle); + ast.compute_char_frequency(mangle); + ast.mangle_names(mangle); + var fun; + walk(ast, node => { + if (is_func_expr(node)) { + fun = node; + return walk_abort; + } + }); + var code = OutputStream(); + AST_BlockStatement.prototype._codegen.call(fun, fun, code); + self.args = [ + make_node(AST_String, self, { + value: fun.argnames.map(function(arg) { + return arg.print_to_string(); + }).join(",") + }), + make_node(AST_String, self.args[self.args.length - 1], { + value: code.get().replace(/^{|}$/g, "") + }) + ]; + return self; + } catch (ex) { + if (!(ex instanceof JS_Parse_Error)) { + throw ex; + } + + // Otherwise, it crashes at runtime. Or maybe it's nonstandard syntax. + } + } + } + + return inline_into_call(self, compressor); +}); + +/** Does this node contain optional property access or optional call? */ +AST_Node.DEFMETHOD("contains_optional", function() { + if ( + this instanceof AST_PropAccess + || this instanceof AST_Call + || this instanceof AST_Chain + ) { + if (this.optional) { + return true; + } else { + return this.expression.contains_optional(); + } + } else { + return false; + } +}); + +def_optimize(AST_New, function(self, compressor) { + if ( + compressor.option("unsafe") && + is_undeclared_ref(self.expression) && + ["Object", "RegExp", "Function", "Error", "Array"].includes(self.expression.name) + ) return make_node(AST_Call, self, self).transform(compressor); + return self; +}); + +def_optimize(AST_Sequence, function(self, compressor) { + if (!compressor.option("side_effects")) return self; + var expressions = []; + filter_for_side_effects(); + var end = expressions.length - 1; + trim_right_for_undefined(); + if (end == 0) { + self = maintain_this_binding(compressor.parent(), compressor.self(), expressions[0]); + if (!(self instanceof AST_Sequence)) self = self.optimize(compressor); + return self; + } + self.expressions = expressions; + return self; + + function filter_for_side_effects() { + var first = first_in_statement(compressor); + var last = self.expressions.length - 1; + self.expressions.forEach(function(expr, index) { + if (index < last) expr = expr.drop_side_effect_free(compressor, first); + if (expr) { + merge_sequence(expressions, expr); + first = false; + } + }); + } + + function trim_right_for_undefined() { + while (end > 0 && is_undefined(expressions[end], compressor)) end--; + if (end < expressions.length - 1) { + expressions[end] = make_node(AST_UnaryPrefix, self, { + operator : "void", + expression : expressions[end] + }); + expressions.length = end + 1; + } + } +}); + +AST_Unary.DEFMETHOD("lift_sequences", function(compressor) { + if (compressor.option("sequences")) { + if (this.expression instanceof AST_Sequence) { + var x = this.expression.expressions.slice(); + var e = this.clone(); + e.expression = x.pop(); + x.push(e); + return make_sequence(this, x).optimize(compressor); + } + } + return this; +}); + +def_optimize(AST_UnaryPostfix, function(self, compressor) { + return self.lift_sequences(compressor); +}); + +def_optimize(AST_UnaryPrefix, function(self, compressor) { + var e = self.expression; + if ( + self.operator == "delete" && + !( + e instanceof AST_SymbolRef || + e instanceof AST_PropAccess || + e instanceof AST_Chain || + is_identifier_atom(e) + ) + ) { + return make_sequence(self, [e, make_node(AST_True, self)]).optimize(compressor); + } + var seq = self.lift_sequences(compressor); + if (seq !== self) { + return seq; + } + if (compressor.option("side_effects") && self.operator == "void") { + e = e.drop_side_effect_free(compressor); + if (e) { + self.expression = e; + return self; + } else { + return make_node(AST_Undefined, self).optimize(compressor); + } + } + if (compressor.in_boolean_context()) { + switch (self.operator) { + case "!": + if (e instanceof AST_UnaryPrefix && e.operator == "!") { + // !!foo ==> foo, if we're in boolean context + return e.expression; + } + if (e instanceof AST_Binary) { + self = best_of(compressor, self, e.negate(compressor, first_in_statement(compressor))); + } + break; + case "typeof": + // typeof always returns a non-empty string, thus it's + // always true in booleans + // And we don't need to check if it's undeclared, because in typeof, that's OK + return (e instanceof AST_SymbolRef ? make_node(AST_True, self) : make_sequence(self, [ + e, + make_node(AST_True, self) + ])).optimize(compressor); + } + } + if (self.operator == "-" && e instanceof AST_Infinity) { + e = e.transform(compressor); + } + if (e instanceof AST_Binary + && (self.operator == "+" || self.operator == "-") + && (e.operator == "*" || e.operator == "/" || e.operator == "%")) { + return make_node(AST_Binary, self, { + operator: e.operator, + left: make_node(AST_UnaryPrefix, e.left, { + operator: self.operator, + expression: e.left + }), + right: e.right + }); + } + + if (compressor.option("evaluate")) { + // ~~x => x (in 32-bit context) + // ~~{32 bit integer} => {32 bit integer} + if ( + self.operator === "~" + && self.expression instanceof AST_UnaryPrefix + && self.expression.operator === "~" + && (compressor.in_32_bit_context() || self.expression.expression.is_32_bit_integer()) + ) { + return self.expression.expression; + } + + // ~(x ^ y) => x ^ ~y + if ( + self.operator === "~" + && e instanceof AST_Binary + && e.operator === "^" + ) { + if (e.left instanceof AST_UnaryPrefix && e.left.operator === "~") { + // ~(~x ^ y) => x ^ y + e.left = e.left.bitwise_negate(true); + } else { + e.right = e.right.bitwise_negate(true); + } + return e; + } + } + + if ( + self.operator != "-" + // avoid infinite recursion of numerals + || !(e instanceof AST_Number || e instanceof AST_Infinity || e instanceof AST_BigInt) + ) { + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + } + return self; +}); + +AST_Binary.DEFMETHOD("lift_sequences", function(compressor) { + if (compressor.option("sequences")) { + if (this.left instanceof AST_Sequence) { + var x = this.left.expressions.slice(); + var e = this.clone(); + e.left = x.pop(); + x.push(e); + return make_sequence(this, x).optimize(compressor); + } + if (this.right instanceof AST_Sequence && !this.left.has_side_effects(compressor)) { + var assign = this.operator == "=" && this.left instanceof AST_SymbolRef; + var x = this.right.expressions; + var last = x.length - 1; + for (var i = 0; i < last; i++) { + if (!assign && x[i].has_side_effects(compressor)) break; + } + if (i == last) { + x = x.slice(); + var e = this.clone(); + e.right = x.pop(); + x.push(e); + return make_sequence(this, x).optimize(compressor); + } else if (i > 0) { + var e = this.clone(); + e.right = make_sequence(this.right, x.slice(i)); + x = x.slice(0, i); + x.push(e); + return make_sequence(this, x).optimize(compressor); + } + } + } + return this; +}); + +var commutativeOperators = makePredicate("== === != !== * & | ^"); +function is_object(node) { + return node instanceof AST_Array + || node instanceof AST_Lambda + || node instanceof AST_Object + || node instanceof AST_Class; +} + +def_optimize(AST_Binary, function(self, compressor) { + function reversible() { + return self.left.is_constant() + || self.right.is_constant() + || !self.left.has_side_effects(compressor) + && !self.right.has_side_effects(compressor); + } + function reverse(op) { + if (reversible()) { + if (op) self.operator = op; + var tmp = self.left; + self.left = self.right; + self.right = tmp; + } + } + if (compressor.option("lhs_constants") && commutativeOperators.has(self.operator)) { + if (self.right.is_constant() + && !self.left.is_constant()) { + // if right is a constant, whatever side effects the + // left side might have could not influence the + // result. hence, force switch. + + if (!(self.left instanceof AST_Binary + && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) { + reverse(); + } + } + } + self = self.lift_sequences(compressor); + if (compressor.option("comparisons")) switch (self.operator) { + case "===": + case "!==": + var is_strict_comparison = true; + if ((self.left.is_string(compressor) && self.right.is_string(compressor)) || + (self.left.is_number(compressor) && self.right.is_number(compressor)) || + (self.left.is_boolean() && self.right.is_boolean()) || + self.left.equivalent_to(self.right)) { + self.operator = self.operator.substr(0, 2); + } + + // XXX: intentionally falling down to the next case + case "==": + case "!=": + // void 0 == x => null == x + if (!is_strict_comparison && is_undefined(self.left, compressor)) { + self.left = make_node(AST_Null, self.left); + // x == void 0 => x == null + } else if (!is_strict_comparison && is_undefined(self.right, compressor)) { + self.right = make_node(AST_Null, self.right); + } else if (compressor.option("typeofs") + // "undefined" == typeof x => undefined === x + && self.left instanceof AST_String + && self.left.value == "undefined" + && self.right instanceof AST_UnaryPrefix + && self.right.operator == "typeof") { + var expr = self.right.expression; + if (expr instanceof AST_SymbolRef ? expr.is_declared(compressor) + : !(expr instanceof AST_PropAccess && compressor.option("ie8"))) { + self.right = expr; + self.left = make_node(AST_Undefined, self.left).optimize(compressor); + if (self.operator.length == 2) self.operator += "="; + } + } else if (compressor.option("typeofs") + // typeof x === "undefined" => x === undefined + && self.left instanceof AST_UnaryPrefix + && self.left.operator == "typeof" + && self.right instanceof AST_String + && self.right.value == "undefined") { + var expr = self.left.expression; + if (expr instanceof AST_SymbolRef ? expr.is_declared(compressor) + : !(expr instanceof AST_PropAccess && compressor.option("ie8"))) { + self.left = expr; + self.right = make_node(AST_Undefined, self.right).optimize(compressor); + if (self.operator.length == 2) self.operator += "="; + } + } else if (self.left instanceof AST_SymbolRef + // obj !== obj => false + && self.right instanceof AST_SymbolRef + && self.left.definition() === self.right.definition() + && is_object(self.left.fixed_value())) { + return make_node(self.operator[0] == "=" ? AST_True : AST_False, self); + } else if (self.left.is_32_bit_integer() && self.right.is_32_bit_integer()) { + const not = node => make_node(AST_UnaryPrefix, node, { + operator: "!", + expression: node + }); + const booleanify = (node, truthy) => { + if (truthy) { + return compressor.in_boolean_context() + ? node + : not(not(node)); + } else { + return not(node); + } + }; + + // The only falsy 32-bit integer is 0 + if (self.left instanceof AST_Number && self.left.value === 0) { + return booleanify(self.right, self.operator[0] === "!"); + } + if (self.right instanceof AST_Number && self.right.value === 0) { + return booleanify(self.left, self.operator[0] === "!"); + } + + // Mask all-bits check + // (x & 0xFF) != 0xFF => !(~x & 0xFF) + let and_op, x, mask; + if ( + (and_op = + self.left instanceof AST_Binary ? self.left + : self.right instanceof AST_Binary ? self.right : null) + && (mask = and_op === self.left ? self.right : self.left) + && and_op.operator === "&" + && mask instanceof AST_Number + && mask.is_32_bit_integer() + && (x = + and_op.left.equivalent_to(mask) ? and_op.right + : and_op.right.equivalent_to(mask) ? and_op.left : null) + ) { + let optimized = booleanify(make_node(AST_Binary, self, { + operator: "&", + left: mask, + right: make_node(AST_UnaryPrefix, self, { + operator: "~", + expression: x + }) + }), self.operator[0] === "!"); + + return best_of(compressor, optimized, self); + } + } + break; + case "&&": + case "||": + var lhs = self.left; + if (lhs.operator == self.operator) { + lhs = lhs.right; + } + if (lhs instanceof AST_Binary + && lhs.operator == (self.operator == "&&" ? "!==" : "===") + && self.right instanceof AST_Binary + && lhs.operator == self.right.operator + && (is_undefined(lhs.left, compressor) && self.right.left instanceof AST_Null + || lhs.left instanceof AST_Null && is_undefined(self.right.left, compressor)) + && !lhs.right.has_side_effects(compressor) + && lhs.right.equivalent_to(self.right.right)) { + var combined = make_node(AST_Binary, self, { + operator: lhs.operator.slice(0, -1), + left: make_node(AST_Null, self), + right: lhs.right + }); + if (lhs !== self.left) { + combined = make_node(AST_Binary, self, { + operator: self.operator, + left: self.left.left, + right: combined + }); + } + return combined; + } + break; + } + if (self.operator == "+" && compressor.in_boolean_context()) { + var ll = self.left.evaluate(compressor); + var rr = self.right.evaluate(compressor); + if (ll && typeof ll == "string") { + return make_sequence(self, [ + self.right, + make_node(AST_True, self) + ]).optimize(compressor); + } + if (rr && typeof rr == "string") { + return make_sequence(self, [ + self.left, + make_node(AST_True, self) + ]).optimize(compressor); + } + } + if (compressor.option("comparisons") && self.is_boolean()) { + if (!(compressor.parent() instanceof AST_Binary) + || compressor.parent() instanceof AST_Assign) { + var negated = make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: self.negate(compressor, first_in_statement(compressor)) + }); + self = best_of(compressor, self, negated); + } + if (compressor.option("unsafe_comps")) { + switch (self.operator) { + case "<": reverse(">"); break; + case "<=": reverse(">="); break; + } + } + } + if (self.operator == "+") { + if (self.right instanceof AST_String + && self.right.getValue() == "" + && self.left.is_string(compressor)) { + return self.left; + } + if (self.left instanceof AST_String + && self.left.getValue() == "" + && self.right.is_string(compressor)) { + return self.right; + } + if (self.left instanceof AST_Binary + && self.left.operator == "+" + && self.left.left instanceof AST_String + && self.left.left.getValue() == "" + && self.right.is_string(compressor)) { + self.left = self.left.right; + return self; + } + } + if (compressor.option("evaluate")) { + switch (self.operator) { + case "&&": + var ll = has_flag(self.left, TRUTHY) + ? true + : has_flag(self.left, FALSY) + ? false + : self.left.evaluate(compressor); + if (!ll) { + return maintain_this_binding(compressor.parent(), compressor.self(), self.left).optimize(compressor); + } else if (!(ll instanceof AST_Node)) { + return make_sequence(self, [ self.left, self.right ]).optimize(compressor); + } + var rr = self.right.evaluate(compressor); + if (!rr) { + if (compressor.in_boolean_context()) { + return make_sequence(self, [ + self.left, + make_node(AST_False, self) + ]).optimize(compressor); + } else { + set_flag(self, FALSY); + } + } else if (!(rr instanceof AST_Node)) { + var parent = compressor.parent(); + if (parent.operator == "&&" && parent.left === compressor.self() || compressor.in_boolean_context()) { + return self.left.optimize(compressor); + } + } + // x || false && y ---> x ? y : false + if (self.left.operator == "||") { + var lr = self.left.right.evaluate(compressor); + if (!lr) return make_node(AST_Conditional, self, { + condition: self.left.left, + consequent: self.right, + alternative: self.left.right + }).optimize(compressor); + } + break; + case "||": + var ll = has_flag(self.left, TRUTHY) + ? true + : has_flag(self.left, FALSY) + ? false + : self.left.evaluate(compressor); + if (!ll) { + return make_sequence(self, [ self.left, self.right ]).optimize(compressor); + } else if (!(ll instanceof AST_Node)) { + return maintain_this_binding(compressor.parent(), compressor.self(), self.left).optimize(compressor); + } + var rr = self.right.evaluate(compressor); + if (!rr) { + var parent = compressor.parent(); + if (parent.operator == "||" && parent.left === compressor.self() || compressor.in_boolean_context()) { + return self.left.optimize(compressor); + } + } else if (!(rr instanceof AST_Node)) { + if (compressor.in_boolean_context()) { + return make_sequence(self, [ + self.left, + make_node(AST_True, self) + ]).optimize(compressor); + } else { + set_flag(self, TRUTHY); + } + } + if (self.left.operator == "&&") { + var lr = self.left.right.evaluate(compressor); + if (lr && !(lr instanceof AST_Node)) return make_node(AST_Conditional, self, { + condition: self.left.left, + consequent: self.left.right, + alternative: self.right + }).optimize(compressor); + } + break; + case "??": + if (is_nullish(self.left, compressor)) { + return self.right; + } + + var ll = self.left.evaluate(compressor); + if (!(ll instanceof AST_Node)) { + // if we know the value for sure we can simply compute right away. + return ll == null ? self.right : self.left; + } + + if (compressor.in_boolean_context()) { + const rr = self.right.evaluate(compressor); + if (!(rr instanceof AST_Node) && !rr) { + return self.left; + } + } + } + var associative = true; + switch (self.operator) { + case "+": + // (x + "foo") + "bar" => x + "foobar" + if (self.right instanceof AST_Constant + && self.left instanceof AST_Binary + && self.left.operator == "+" + && self.left.is_string(compressor)) { + var binary = make_node(AST_Binary, self, { + operator: "+", + left: self.left.right, + right: self.right, + }); + var r = binary.optimize(compressor); + if (binary !== r) { + self = make_node(AST_Binary, self, { + operator: "+", + left: self.left.left, + right: r + }); + } + } + // (x + "foo") + ("bar" + y) => (x + "foobar") + y + if (self.left instanceof AST_Binary + && self.left.operator == "+" + && self.left.is_string(compressor) + && self.right instanceof AST_Binary + && self.right.operator == "+" + && self.right.is_string(compressor)) { + var binary = make_node(AST_Binary, self, { + operator: "+", + left: self.left.right, + right: self.right.left, + }); + var m = binary.optimize(compressor); + if (binary !== m) { + self = make_node(AST_Binary, self, { + operator: "+", + left: make_node(AST_Binary, self.left, { + operator: "+", + left: self.left.left, + right: m + }), + right: self.right.right + }); + } + } + // a + -b => a - b + if (self.right instanceof AST_UnaryPrefix + && self.right.operator == "-" + && self.left.is_number(compressor)) { + self = make_node(AST_Binary, self, { + operator: "-", + left: self.left, + right: self.right.expression + }); + break; + } + // -a + b => b - a + if (self.left instanceof AST_UnaryPrefix + && self.left.operator == "-" + && reversible() + && self.right.is_number(compressor)) { + self = make_node(AST_Binary, self, { + operator: "-", + left: self.right, + right: self.left.expression + }); + break; + } + // `foo${bar}baz` + 1 => `foo${bar}baz1` + if (self.left instanceof AST_TemplateString) { + var l = self.left; + var r = self.right.evaluate(compressor); + if (r != self.right) { + l.segments[l.segments.length - 1].value += String(r); + return l; + } + } + // 1 + `foo${bar}baz` => `1foo${bar}baz` + if (self.right instanceof AST_TemplateString) { + var r = self.right; + var l = self.left.evaluate(compressor); + if (l != self.left) { + r.segments[0].value = String(l) + r.segments[0].value; + return r; + } + } + // `1${bar}2` + `foo${bar}baz` => `1${bar}2foo${bar}baz` + if (self.left instanceof AST_TemplateString + && self.right instanceof AST_TemplateString) { + var l = self.left; + var segments = l.segments; + var r = self.right; + segments[segments.length - 1].value += r.segments[0].value; + for (var i = 1; i < r.segments.length; i++) { + segments.push(r.segments[i]); + } + return l; + } + case "*": + associative = compressor.option("unsafe_math"); + case "&": + case "|": + case "^": + // a + +b => +b + a + if (self.left.is_number(compressor) + && self.right.is_number(compressor) + && reversible() + && !(self.left instanceof AST_Binary + && self.left.operator != self.operator + && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) { + var reversed = make_node(AST_Binary, self, { + operator: self.operator, + left: self.right, + right: self.left + }); + if (self.right instanceof AST_Constant + && !(self.left instanceof AST_Constant)) { + self = best_of(compressor, reversed, self); + } else { + self = best_of(compressor, self, reversed); + } + } + if (associative && self.is_number(compressor)) { + // a + (b + c) => (a + b) + c + if (self.right instanceof AST_Binary + && self.right.operator == self.operator) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: self.left, + right: self.right.left, + start: self.left.start, + end: self.right.left.end + }), + right: self.right.right + }); + } + // (n + 2) + 3 => 5 + n + // (2 * n) * 3 => 6 + n + if (self.right instanceof AST_Constant + && self.left instanceof AST_Binary + && self.left.operator == self.operator) { + if (self.left.left instanceof AST_Constant) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: self.left.left, + right: self.right, + start: self.left.left.start, + end: self.right.end + }), + right: self.left.right + }); + } else if (self.left.right instanceof AST_Constant) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: self.left.right, + right: self.right, + start: self.left.right.start, + end: self.right.end + }), + right: self.left.left + }); + } + } + // (a | 1) | (2 | d) => (3 | a) | b + if (self.left instanceof AST_Binary + && self.left.operator == self.operator + && self.left.right instanceof AST_Constant + && self.right instanceof AST_Binary + && self.right.operator == self.operator + && self.right.left instanceof AST_Constant) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: make_node(AST_Binary, self.left.left, { + operator: self.operator, + left: self.left.right, + right: self.right.left, + start: self.left.right.start, + end: self.right.left.end + }), + right: self.left.left + }), + right: self.right.right + }); + } + } + } + + // bitwise ops + if (bitwise_binop.has(self.operator)) { + // Use De Morgan's laws + // z & (X | y) + // => z & X (given y & z === 0) + // => z & X | {y & z} (given y & z !== 0) + let y, z, x_node, y_node, z_node = self.left; + if ( + self.operator === "&" + && self.right instanceof AST_Binary + && self.right.operator === "|" + && typeof (z = self.left.evaluate(compressor)) === "number" + ) { + if (typeof (y = self.right.right.evaluate(compressor)) === "number") { + // z & (X | y) + x_node = self.right.left; + y_node = self.right.right; + } else if (typeof (y = self.right.left.evaluate(compressor)) === "number") { + // z & (y | X) + x_node = self.right.right; + y_node = self.right.left; + } + + if (x_node && y_node) { + if ((y & z) === 0) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: z_node, + right: x_node + }); + } else { + const reordered_ops = make_node(AST_Binary, self, { + operator: "|", + left: make_node(AST_Binary, self, { + operator: "&", + left: x_node, + right: z_node + }), + right: make_node_from_constant(y & z, y_node), + }); + + self = best_of(compressor, self, reordered_ops); + } + } + } + + // x ^ x => 0 + // x | x => 0 | x + // x & x => 0 | x + const same_operands = self.left.equivalent_to(self.right) && !self.left.has_side_effects(compressor); + if (same_operands) { + if (self.operator === "^") { + return make_node(AST_Number, self, { value: 0 }); + } + if (self.operator === "|" || self.operator === "&") { + self.left = make_node(AST_Number, self, { value: 0 }); + self.operator = "|"; + } + } + + + // Shifts that do nothing + // {anything} >> 0 => {anything} | 0 + // {anything} << 0 => {anything} | 0 + if ( + (self.operator === "<<" || self.operator === ">>") + && self.right instanceof AST_Number && self.right.value === 0 + ) { + self.operator = "|"; + } + + // Find useless to-bitwise conversions + // {32 bit integer} | 0 => {32 bit integer} + // {32 bit integer} ^ 0 => {32 bit integer} + const zero_side = self.right instanceof AST_Number && self.right.value === 0 ? self.right + : self.left instanceof AST_Number && self.left.value === 0 ? self.left + : null; + const non_zero_side = zero_side && (zero_side === self.right ? self.left : self.right); + if ( + zero_side + && (self.operator === "|" || self.operator === "^") + && (non_zero_side.is_32_bit_integer() || compressor.in_32_bit_context()) + ) { + return non_zero_side; + } + + // {anything} & 0 => 0 + if ( + zero_side + && self.operator === "&" + && !non_zero_side.has_side_effects(compressor) + ) { + return zero_side; + } + + const is_full_mask = (node) => + node instanceof AST_Number && node.value === -1 + || + node instanceof AST_UnaryPrefix && ( + node.operator === "-" + && node.expression instanceof AST_Number + && node.expression.value === 1 + || node.operator === "~" + && node.expression instanceof AST_Number + && node.expression.value === 0); + + const full_mask = is_full_mask(self.right) ? self.right + : is_full_mask(self.left) ? self.left + : null; + const non_full_mask_side = full_mask && (full_mask === self.right ? self.left : self.right); + + switch (self.operator) { + case "|": + // {anything} | -1 => -1 + if (full_mask && !non_full_mask_side.has_side_effects(compressor)) { + return full_mask; + } + + break; + case "&": + // {32 bit integer} & -1 => {32 bit integer} + if ( + full_mask + && (non_full_mask_side.is_32_bit_integer() || compressor.in_32_bit_context()) + ) { + return non_full_mask_side; + } + + break; + case "^": + // {anything} ^ -1 => ~{anything} + if (full_mask) { + return non_full_mask_side.bitwise_negate(compressor.in_32_bit_context()); + } + + // ~x ^ ~y => x ^ y + if ( + self.left instanceof AST_UnaryPrefix + && self.left.operator === "~" + && self.right instanceof AST_UnaryPrefix + && self.right.operator === "~" + ) { + self = make_node(AST_Binary, self, { + operator: "^", + left: self.left.expression, + right: self.right.expression + }); + } + + break; + } + } + } + // x && (y && z) ==> x && y && z + // x || (y || z) ==> x || y || z + // x + ("y" + z) ==> x + "y" + z + // "x" + (y + "z")==> "x" + y + "z" + if (self.right instanceof AST_Binary + && self.right.operator == self.operator + && (lazy_op.has(self.operator) + || (self.operator == "+" + && (self.right.left.is_string(compressor) + || (self.left.is_string(compressor) + && self.right.right.is_string(compressor))))) + ) { + self.left = make_node(AST_Binary, self.left, { + operator : self.operator, + left : self.left.transform(compressor), + right : self.right.left.transform(compressor) + }); + self.right = self.right.right.transform(compressor); + return self.transform(compressor); + } + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + return self; +}); + +def_optimize(AST_SymbolExport, function(self) { + return self; +}); + +def_optimize(AST_SymbolRef, function(self, compressor) { + if ( + !compressor.option("ie8") + && is_undeclared_ref(self) + && !compressor.find_parent(AST_With) + ) { + switch (self.name) { + case "undefined": + return make_node(AST_Undefined, self).optimize(compressor); + case "NaN": + return make_node(AST_NaN, self).optimize(compressor); + case "Infinity": + return make_node(AST_Infinity, self).optimize(compressor); + } + } + + if (compressor.option("reduce_vars") && !compressor.is_lhs()) { + return inline_into_symbolref(self, compressor); + } else { + return self; + } +}); + +function is_atomic(lhs, self) { + return lhs instanceof AST_SymbolRef || lhs.TYPE === self.TYPE; +} + +def_optimize(AST_Undefined, function(self, compressor) { + if (compressor.option("unsafe_undefined")) { + var undef = find_variable(compressor, "undefined"); + if (undef) { + var ref = make_node(AST_SymbolRef, self, { + name : "undefined", + scope : undef.scope, + thedef : undef + }); + set_flag(ref, UNDEFINED); + return ref; + } + } + var lhs = compressor.is_lhs(); + if (lhs && is_atomic(lhs, self)) return self; + return make_node(AST_UnaryPrefix, self, { + operator: "void", + expression: make_node(AST_Number, self, { + value: 0 + }) + }); +}); + +def_optimize(AST_Infinity, function(self, compressor) { + var lhs = compressor.is_lhs(); + if (lhs && is_atomic(lhs, self)) return self; + if ( + compressor.option("keep_infinity") + && !(lhs && !is_atomic(lhs, self)) + && !find_variable(compressor, "Infinity") + ) { + return self; + } + return make_node(AST_Binary, self, { + operator: "/", + left: make_node(AST_Number, self, { + value: 1 + }), + right: make_node(AST_Number, self, { + value: 0 + }) + }); +}); + +def_optimize(AST_NaN, function(self, compressor) { + var lhs = compressor.is_lhs(); + if (lhs && !is_atomic(lhs, self) + || find_variable(compressor, "NaN")) { + return make_node(AST_Binary, self, { + operator: "/", + left: make_node(AST_Number, self, { + value: 0 + }), + right: make_node(AST_Number, self, { + value: 0 + }) + }); + } + return self; +}); + +const ASSIGN_OPS = makePredicate("+ - / * % >> << >>> | ^ &"); +const ASSIGN_OPS_COMMUTATIVE = makePredicate("* | ^ &"); +def_optimize(AST_Assign, function(self, compressor) { + if (self.logical) { + return self.lift_sequences(compressor); + } + + var def; + // x = x ---> x + if ( + self.operator === "=" + && self.left instanceof AST_SymbolRef + && self.left.name !== "arguments" + && !(def = self.left.definition()).undeclared + && self.right.equivalent_to(self.left) + ) { + return self.right; + } + + if (compressor.option("dead_code") + && self.left instanceof AST_SymbolRef + && (def = self.left.definition()).scope === compressor.find_parent(AST_Lambda)) { + var level = 0, node, parent = self; + do { + node = parent; + parent = compressor.parent(level++); + if (parent instanceof AST_Exit) { + if (in_try(level, parent)) break; + if (is_reachable(def.scope, [ def ])) break; + if (self.operator == "=") return self.right; + def.fixed = false; + return make_node(AST_Binary, self, { + operator: self.operator.slice(0, -1), + left: self.left, + right: self.right + }).optimize(compressor); + } + } while (parent instanceof AST_Binary && parent.right === node + || parent instanceof AST_Sequence && parent.tail_node() === node); + } + self = self.lift_sequences(compressor); + + if (self.operator == "=" && self.left instanceof AST_SymbolRef && self.right instanceof AST_Binary) { + // x = expr1 OP expr2 + if (self.right.left instanceof AST_SymbolRef + && self.right.left.name == self.left.name + && ASSIGN_OPS.has(self.right.operator)) { + // x = x - 2 ---> x -= 2 + self.operator = self.right.operator + "="; + self.right = self.right.right; + } else if (self.right.right instanceof AST_SymbolRef + && self.right.right.name == self.left.name + && ASSIGN_OPS_COMMUTATIVE.has(self.right.operator) + && !self.right.left.has_side_effects(compressor)) { + // x = 2 & x ---> x &= 2 + self.operator = self.right.operator + "="; + self.right = self.right.left; + } + } + return self; + + function in_try(level, node) { + function may_assignment_throw() { + const right = self.right; + self.right = make_node(AST_Null, right); + const may_throw = node.may_throw(compressor); + self.right = right; + + return may_throw; + } + + var stop_at = self.left.definition().scope.get_defun_scope(); + var parent; + while ((parent = compressor.parent(level++)) !== stop_at) { + if (parent instanceof AST_Try) { + if (parent.bfinally) return true; + if (parent.bcatch && may_assignment_throw()) return true; + } + } + } +}); + +def_optimize(AST_DefaultAssign, function(self, compressor) { + if (!compressor.option("evaluate")) { + return self; + } + var evaluateRight = self.right.evaluate(compressor); + + // `[x = undefined] = foo` ---> `[x] = foo` + // `(arg = undefined) => ...` ---> `(arg) => ...` (unless `keep_fargs`) + // `((arg = undefined) => ...)()` ---> `((arg) => ...)()` + let lambda, iife; + if (evaluateRight === undefined) { + if ( + (lambda = compressor.parent()) instanceof AST_Lambda + ? ( + compressor.option("keep_fargs") === false + || (iife = compressor.parent(1)).TYPE === "Call" + && iife.expression === lambda + ) + : true + ) { + self = self.left; + } + } else if (evaluateRight !== self.right) { + evaluateRight = make_node_from_constant(evaluateRight, self.right); + self.right = best_of_expression(evaluateRight, self.right); + } + + return self; +}); + +function is_nullish_check(check, check_subject, compressor) { + if (check_subject.may_throw(compressor)) return false; + + let nullish_side; + + // foo == null + if ( + check instanceof AST_Binary + && check.operator === "==" + // which side is nullish? + && ( + (nullish_side = is_nullish(check.left, compressor) && check.left) + || (nullish_side = is_nullish(check.right, compressor) && check.right) + ) + // is the other side the same as the check_subject + && ( + nullish_side === check.left + ? check.right + : check.left + ).equivalent_to(check_subject) + ) { + return true; + } + + // foo === null || foo === undefined + if (check instanceof AST_Binary && check.operator === "||") { + let null_cmp; + let undefined_cmp; + + const find_comparison = cmp => { + if (!( + cmp instanceof AST_Binary + && (cmp.operator === "===" || cmp.operator === "==") + )) { + return false; + } + + let found = 0; + let defined_side; + + if (cmp.left instanceof AST_Null) { + found++; + null_cmp = cmp; + defined_side = cmp.right; + } + if (cmp.right instanceof AST_Null) { + found++; + null_cmp = cmp; + defined_side = cmp.left; + } + if (is_undefined(cmp.left, compressor)) { + found++; + undefined_cmp = cmp; + defined_side = cmp.right; + } + if (is_undefined(cmp.right, compressor)) { + found++; + undefined_cmp = cmp; + defined_side = cmp.left; + } + + if (found !== 1) { + return false; + } + + if (!defined_side.equivalent_to(check_subject)) { + return false; + } + + return true; + }; + + if (!find_comparison(check.left)) return false; + if (!find_comparison(check.right)) return false; + + if (null_cmp && undefined_cmp && null_cmp !== undefined_cmp) { + return true; + } + } + + return false; +} + +def_optimize(AST_Conditional, function(self, compressor) { + if (!compressor.option("conditionals")) return self; + // This looks like lift_sequences(), should probably be under "sequences" + if (self.condition instanceof AST_Sequence) { + var expressions = self.condition.expressions.slice(); + self.condition = expressions.pop(); + expressions.push(self); + return make_sequence(self, expressions); + } + var cond = self.condition.evaluate(compressor); + if (cond !== self.condition) { + if (cond) { + return maintain_this_binding(compressor.parent(), compressor.self(), self.consequent); + } else { + return maintain_this_binding(compressor.parent(), compressor.self(), self.alternative); + } + } + var negated = cond.negate(compressor, first_in_statement(compressor)); + if (best_of(compressor, cond, negated) === negated) { + self = make_node(AST_Conditional, self, { + condition: negated, + consequent: self.alternative, + alternative: self.consequent + }); + } + var condition = self.condition; + var consequent = self.consequent; + var alternative = self.alternative; + // x?x:y --> x||y + if (condition instanceof AST_SymbolRef + && consequent instanceof AST_SymbolRef + && condition.definition() === consequent.definition()) { + return make_node(AST_Binary, self, { + operator: "||", + left: condition, + right: alternative + }); + } + // if (foo) exp = something; else exp = something_else; + // | + // v + // exp = foo ? something : something_else; + if ( + consequent instanceof AST_Assign + && alternative instanceof AST_Assign + && consequent.operator === alternative.operator + && consequent.logical === alternative.logical + && consequent.left.equivalent_to(alternative.left) + && (!self.condition.has_side_effects(compressor) + || consequent.operator == "=" + && !consequent.left.has_side_effects(compressor)) + ) { + return make_node(AST_Assign, self, { + operator: consequent.operator, + left: consequent.left, + logical: consequent.logical, + right: make_node(AST_Conditional, self, { + condition: self.condition, + consequent: consequent.right, + alternative: alternative.right + }) + }); + } + // x ? y(a) : y(b) --> y(x ? a : b) + var arg_index; + if (consequent instanceof AST_Call + && alternative.TYPE === consequent.TYPE + && consequent.args.length > 0 + && consequent.args.length == alternative.args.length + && consequent.expression.equivalent_to(alternative.expression) + && !self.condition.has_side_effects(compressor) + && !consequent.expression.has_side_effects(compressor) + && typeof (arg_index = single_arg_diff()) == "number") { + var node = consequent.clone(); + node.args[arg_index] = make_node(AST_Conditional, self, { + condition: self.condition, + consequent: consequent.args[arg_index], + alternative: alternative.args[arg_index] + }); + return node; + } + // a ? b : c ? b : d --> (a || c) ? b : d + if (alternative instanceof AST_Conditional + && consequent.equivalent_to(alternative.consequent)) { + return make_node(AST_Conditional, self, { + condition: make_node(AST_Binary, self, { + operator: "||", + left: condition, + right: alternative.condition + }), + consequent: consequent, + alternative: alternative.alternative + }).optimize(compressor); + } + + // a == null ? b : a -> a ?? b + if ( + compressor.option("ecma") >= 2020 && + is_nullish_check(condition, alternative, compressor) + ) { + return make_node(AST_Binary, self, { + operator: "??", + left: alternative, + right: consequent + }).optimize(compressor); + } + + // a ? b : (c, b) --> (a || c), b + if (alternative instanceof AST_Sequence + && consequent.equivalent_to(alternative.expressions[alternative.expressions.length - 1])) { + return make_sequence(self, [ + make_node(AST_Binary, self, { + operator: "||", + left: condition, + right: make_sequence(self, alternative.expressions.slice(0, -1)) + }), + consequent + ]).optimize(compressor); + } + // a ? b : (c && b) --> (a || c) && b + if (alternative instanceof AST_Binary + && alternative.operator == "&&" + && consequent.equivalent_to(alternative.right)) { + return make_node(AST_Binary, self, { + operator: "&&", + left: make_node(AST_Binary, self, { + operator: "||", + left: condition, + right: alternative.left + }), + right: consequent + }).optimize(compressor); + } + // x?y?z:a:a --> x&&y?z:a + if (consequent instanceof AST_Conditional + && consequent.alternative.equivalent_to(alternative)) { + return make_node(AST_Conditional, self, { + condition: make_node(AST_Binary, self, { + left: self.condition, + operator: "&&", + right: consequent.condition + }), + consequent: consequent.consequent, + alternative: alternative + }); + } + // x ? y : y --> x, y + if (consequent.equivalent_to(alternative)) { + return make_sequence(self, [ + self.condition, + consequent + ]).optimize(compressor); + } + // x ? y || z : z --> x && y || z + if (consequent instanceof AST_Binary + && consequent.operator == "||" + && consequent.right.equivalent_to(alternative)) { + return make_node(AST_Binary, self, { + operator: "||", + left: make_node(AST_Binary, self, { + operator: "&&", + left: self.condition, + right: consequent.left + }), + right: alternative + }).optimize(compressor); + } + + const in_bool = compressor.in_boolean_context(); + if (is_true(self.consequent)) { + if (is_false(self.alternative)) { + // c ? true : false ---> !!c + return booleanize(self.condition); + } + // c ? true : x ---> !!c || x + return make_node(AST_Binary, self, { + operator: "||", + left: booleanize(self.condition), + right: self.alternative + }); + } + if (is_false(self.consequent)) { + if (is_true(self.alternative)) { + // c ? false : true ---> !c + return booleanize(self.condition.negate(compressor)); + } + // c ? false : x ---> !c && x + return make_node(AST_Binary, self, { + operator: "&&", + left: booleanize(self.condition.negate(compressor)), + right: self.alternative + }); + } + if (is_true(self.alternative)) { + // c ? x : true ---> !c || x + return make_node(AST_Binary, self, { + operator: "||", + left: booleanize(self.condition.negate(compressor)), + right: self.consequent + }); + } + if (is_false(self.alternative)) { + // c ? x : false ---> !!c && x + return make_node(AST_Binary, self, { + operator: "&&", + left: booleanize(self.condition), + right: self.consequent + }); + } + + return self; + + function booleanize(node) { + if (node.is_boolean()) return node; + // !!expression + return make_node(AST_UnaryPrefix, node, { + operator: "!", + expression: node.negate(compressor) + }); + } + + // AST_True or !0 + function is_true(node) { + return node instanceof AST_True + || in_bool + && node instanceof AST_Constant + && node.getValue() + || (node instanceof AST_UnaryPrefix + && node.operator == "!" + && node.expression instanceof AST_Constant + && !node.expression.getValue()); + } + // AST_False or !1 + function is_false(node) { + return node instanceof AST_False + || in_bool + && node instanceof AST_Constant + && !node.getValue() + || (node instanceof AST_UnaryPrefix + && node.operator == "!" + && node.expression instanceof AST_Constant + && node.expression.getValue()); + } + + function single_arg_diff() { + var a = consequent.args; + var b = alternative.args; + for (var i = 0, len = a.length; i < len; i++) { + if (a[i] instanceof AST_Expansion) return; + if (!a[i].equivalent_to(b[i])) { + if (b[i] instanceof AST_Expansion) return; + for (var j = i + 1; j < len; j++) { + if (a[j] instanceof AST_Expansion) return; + if (!a[j].equivalent_to(b[j])) return; + } + return i; + } + } + } +}); + +def_optimize(AST_Boolean, function(self, compressor) { + if (compressor.in_boolean_context()) return make_node(AST_Number, self, { + value: +self.value + }); + var p = compressor.parent(); + if (compressor.option("booleans_as_integers")) { + if (p instanceof AST_Binary && (p.operator == "===" || p.operator == "!==")) { + p.operator = p.operator.replace(/=$/, ""); + } + return make_node(AST_Number, self, { + value: +self.value + }); + } + if (compressor.option("booleans")) { + if (p instanceof AST_Binary && (p.operator == "==" + || p.operator == "!=")) { + return make_node(AST_Number, self, { + value: +self.value + }); + } + return make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: make_node(AST_Number, self, { + value: 1 - self.value + }) + }); + } + return self; +}); + +function safe_to_flatten(value, compressor) { + if (value instanceof AST_SymbolRef) { + value = value.fixed_value(); + } + if (!value) return false; + if (!(value instanceof AST_Lambda || value instanceof AST_Class)) return true; + if (!(value instanceof AST_Lambda && value.contains_this())) return true; + return compressor.parent() instanceof AST_New; +} + +AST_PropAccess.DEFMETHOD("flatten_object", function(key, compressor) { + if (!compressor.option("properties")) return; + if (key === "__proto__") return; + + var arrows = compressor.option("unsafe_arrows") && compressor.option("ecma") >= 2015; + var expr = this.expression; + if (expr instanceof AST_Object) { + var props = expr.properties; + + for (var i = props.length; --i >= 0;) { + var prop = props[i]; + + if ("" + (prop instanceof AST_ConciseMethod ? prop.key.name : prop.key) == key) { + const all_props_flattenable = props.every((p) => + (p instanceof AST_ObjectKeyVal + || arrows && p instanceof AST_ConciseMethod && !p.is_generator + ) + && !p.computed_key() + ); + + if (!all_props_flattenable) return; + if (!safe_to_flatten(prop.value, compressor)) return; + + return make_node(AST_Sub, this, { + expression: make_node(AST_Array, expr, { + elements: props.map(function(prop) { + var v = prop.value; + if (v instanceof AST_Accessor) { + v = make_node(AST_Function, v, v); + } + + var k = prop.key; + if (k instanceof AST_Node && !(k instanceof AST_SymbolMethod)) { + return make_sequence(prop, [ k, v ]); + } + + return v; + }) + }), + property: make_node(AST_Number, this, { + value: i + }) + }); + } + } + } +}); + +def_optimize(AST_Sub, function(self, compressor) { + var expr = self.expression; + var prop = self.property; + if (compressor.option("properties")) { + var key = prop.evaluate(compressor); + if (key !== prop) { + if (typeof key == "string") { + if (key == "undefined") { + key = undefined; + } else { + var value = parseFloat(key); + if (value.toString() == key) { + key = value; + } + } + } + prop = self.property = best_of_expression( + prop, + make_node_from_constant(key, prop).transform(compressor) + ); + var property = "" + key; + if (is_basic_identifier_string(property) + && property.length <= prop.size() + 1) { + return make_node(AST_Dot, self, { + expression: expr, + optional: self.optional, + property: property, + quote: prop.quote, + }).optimize(compressor); + } + } + } + var fn; + OPT_ARGUMENTS: if (compressor.option("arguments") + && expr instanceof AST_SymbolRef + && expr.name == "arguments" + && expr.definition().orig.length == 1 + && (fn = expr.scope) instanceof AST_Lambda + && fn.uses_arguments + && !(fn instanceof AST_Arrow) + && prop instanceof AST_Number) { + var index = prop.getValue(); + var params = new Set(); + var argnames = fn.argnames; + for (var n = 0; n < argnames.length; n++) { + if (!(argnames[n] instanceof AST_SymbolFunarg)) { + break OPT_ARGUMENTS; // destructuring parameter - bail + } + var param = argnames[n].name; + if (params.has(param)) { + break OPT_ARGUMENTS; // duplicate parameter - bail + } + params.add(param); + } + var argname = fn.argnames[index]; + if (argname && compressor.has_directive("use strict")) { + var def = argname.definition(); + if (!compressor.option("reduce_vars") || def.assignments || def.orig.length > 1) { + argname = null; + } + } else if (!argname && !compressor.option("keep_fargs") && index < fn.argnames.length + 5) { + while (index >= fn.argnames.length) { + argname = fn.create_symbol(AST_SymbolFunarg, { + source: fn, + scope: fn, + tentative_name: "argument_" + fn.argnames.length, + }); + fn.argnames.push(argname); + } + } + if (argname) { + var sym = make_node(AST_SymbolRef, self, argname); + sym.reference({}); + clear_flag(argname, UNUSED); + return sym; + } + } + if (compressor.is_lhs()) return self; + if (key !== prop) { + var sub = self.flatten_object(property, compressor); + if (sub) { + expr = self.expression = sub.expression; + prop = self.property = sub.property; + } + } + if (compressor.option("properties") && compressor.option("side_effects") + && prop instanceof AST_Number && expr instanceof AST_Array) { + var index = prop.getValue(); + var elements = expr.elements; + var retValue = elements[index]; + FLATTEN: if (safe_to_flatten(retValue, compressor)) { + var flatten = true; + var values = []; + for (var i = elements.length; --i > index;) { + var value = elements[i].drop_side_effect_free(compressor); + if (value) { + values.unshift(value); + if (flatten && value.has_side_effects(compressor)) flatten = false; + } + } + if (retValue instanceof AST_Expansion) break FLATTEN; + retValue = retValue instanceof AST_Hole ? make_node(AST_Undefined, retValue) : retValue; + if (!flatten) values.unshift(retValue); + while (--i >= 0) { + var value = elements[i]; + if (value instanceof AST_Expansion) break FLATTEN; + value = value.drop_side_effect_free(compressor); + if (value) values.unshift(value); + else index--; + } + if (flatten) { + values.push(retValue); + return make_sequence(self, values).optimize(compressor); + } else return make_node(AST_Sub, self, { + expression: make_node(AST_Array, expr, { + elements: values + }), + property: make_node(AST_Number, prop, { + value: index + }) + }); + } + } + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + return self; +}); + +def_optimize(AST_Chain, function (self, compressor) { + if (is_nullish(self.expression, compressor)) { + let parent = compressor.parent(); + // It's valid to delete a nullish optional chain, but if we optimized + // this to `delete undefined` then it would appear to be a syntax error + // when we try to optimize the delete. Thankfully, `delete 0` is fine. + if (parent instanceof AST_UnaryPrefix && parent.operator === "delete") { + return make_node_from_constant(0, self); + } + return make_node(AST_Undefined, self); + } + return self; +}); + +def_optimize(AST_Dot, function(self, compressor) { + const parent = compressor.parent(); + if (compressor.is_lhs()) return self; + if (compressor.option("unsafe_proto") + && self.expression instanceof AST_Dot + && self.expression.property == "prototype") { + var exp = self.expression.expression; + if (is_undeclared_ref(exp)) switch (exp.name) { + case "Array": + self.expression = make_node(AST_Array, self.expression, { + elements: [] + }); + break; + case "Function": + self.expression = make_node(AST_Function, self.expression, { + argnames: [], + body: [] + }); + break; + case "Number": + self.expression = make_node(AST_Number, self.expression, { + value: 0 + }); + break; + case "Object": + self.expression = make_node(AST_Object, self.expression, { + properties: [] + }); + break; + case "RegExp": + self.expression = make_node(AST_RegExp, self.expression, { + value: { source: "t", flags: "" } + }); + break; + case "String": + self.expression = make_node(AST_String, self.expression, { + value: "" + }); + break; + } + } + if (!(parent instanceof AST_Call) || !has_annotation(parent, _NOINLINE)) { + const sub = self.flatten_object(self.property, compressor); + if (sub) return sub.optimize(compressor); + } + + if (self.expression instanceof AST_PropAccess + && parent instanceof AST_PropAccess) { + return self; + } + + let ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + return self; +}); + +function literals_in_boolean_context(self, compressor) { + if (compressor.in_boolean_context()) { + return best_of(compressor, self, make_sequence(self, [ + self, + make_node(AST_True, self) + ]).optimize(compressor)); + } + return self; +} + +function inline_array_like_spread(elements) { + for (var i = 0; i < elements.length; i++) { + var el = elements[i]; + if (el instanceof AST_Expansion) { + var expr = el.expression; + if ( + expr instanceof AST_Array + && !expr.elements.some(elm => elm instanceof AST_Hole) + ) { + elements.splice(i, 1, ...expr.elements); + // Step back one, as the element at i is now new. + i--; + } + // In array-like spread, spreading a non-iterable value is TypeError. + // We therefore can’t optimize anything else, unlike with object spread. + } + } +} + +def_optimize(AST_Array, function(self, compressor) { + var optimized = literals_in_boolean_context(self, compressor); + if (optimized !== self) { + return optimized; + } + inline_array_like_spread(self.elements); + return self; +}); + +function inline_object_prop_spread(props) { + for (var i = 0; i < props.length; i++) { + var prop = props[i]; + if (prop instanceof AST_Expansion) { + const expr = prop.expression; + if ( + expr instanceof AST_Object + && expr.properties.every(prop => prop instanceof AST_ObjectKeyVal) + ) { + props.splice(i, 1, ...expr.properties); + // Step back one, as the property at i is now new. + i--; + } else if (( + // `expr.is_constant()` returns `false` for `AST_RegExp`, so need both. + expr instanceof AST_Constant + || expr.is_constant() + ) && !(expr instanceof AST_String)) { + // Unlike array-like spread, in object spread, spreading a + // non-iterable value silently does nothing; it is thus safe + // to remove. AST_String is the only iterable constant. + props.splice(i, 1); + i--; + } + } + } +} + +def_optimize(AST_Object, function(self, compressor) { + var optimized = literals_in_boolean_context(self, compressor); + if (optimized !== self) { + return optimized; + } + inline_object_prop_spread(self.properties); + return self; +}); + +def_optimize(AST_RegExp, literals_in_boolean_context); + +def_optimize(AST_Return, function(self, compressor) { + if (self.value && is_undefined(self.value, compressor)) { + self.value = null; + } + return self; +}); + +def_optimize(AST_Arrow, opt_AST_Lambda); + +def_optimize(AST_Function, function(self, compressor) { + self = opt_AST_Lambda(self, compressor); + if (compressor.option("unsafe_arrows") + && compressor.option("ecma") >= 2015 + && !self.name + && !self.is_generator + && !self.uses_arguments + && !self.pinned()) { + const uses_this = walk(self, node => { + if (node instanceof AST_This) return walk_abort; + }); + if (!uses_this) return make_node(AST_Arrow, self, self).optimize(compressor); + } + return self; +}); + +def_optimize(AST_Class, function(self) { + for (let i = 0; i < self.properties.length; i++) { + const prop = self.properties[i]; + if (prop instanceof AST_ClassStaticBlock && prop.body.length == 0) { + self.properties.splice(i, 1); + i--; + } + } + + return self; +}); + +def_optimize(AST_ClassStaticBlock, function(self, compressor) { + tighten_body(self.body, compressor); + return self; +}); + +def_optimize(AST_Yield, function(self, compressor) { + if (self.expression && !self.is_star && is_undefined(self.expression, compressor)) { + self.expression = null; + } + return self; +}); + +def_optimize(AST_TemplateString, function(self, compressor) { + if ( + !compressor.option("evaluate") + || compressor.parent() instanceof AST_PrefixedTemplateString + ) { + return self; + } + + var segments = []; + for (var i = 0; i < self.segments.length; i++) { + var segment = self.segments[i]; + if (segment instanceof AST_Node) { + var result = segment.evaluate(compressor); + // Evaluate to constant value + // Constant value shorter than ${segment} + if (result !== segment && (result + "").length <= segment.size() + "${}".length) { + // There should always be a previous and next segment if segment is a node + segments[segments.length - 1].value = segments[segments.length - 1].value + result + self.segments[++i].value; + continue; + } + // `before ${`innerBefore ${any} innerAfter`} after` => `before innerBefore ${any} innerAfter after` + // TODO: + // `before ${'test' + foo} after` => `before innerBefore ${any} innerAfter after` + // `before ${foo + 'test} after` => `before innerBefore ${any} innerAfter after` + if (segment instanceof AST_TemplateString) { + var inners = segment.segments; + segments[segments.length - 1].value += inners[0].value; + for (var j = 1; j < inners.length; j++) { + segment = inners[j]; + segments.push(segment); + } + continue; + } + } + segments.push(segment); + } + self.segments = segments; + + // `foo` => "foo" + if (segments.length == 1) { + return make_node(AST_String, self, segments[0]); + } + + if ( + segments.length === 3 + && segments[1] instanceof AST_Node + && ( + segments[1].is_string(compressor) + || segments[1].is_number(compressor) + || is_nullish(segments[1], compressor) + || compressor.option("unsafe") + ) + ) { + // `foo${bar}` => "foo" + bar + if (segments[2].value === "") { + return make_node(AST_Binary, self, { + operator: "+", + left: make_node(AST_String, self, { + value: segments[0].value, + }), + right: segments[1], + }); + } + // `${bar}baz` => bar + "baz" + if (segments[0].value === "") { + return make_node(AST_Binary, self, { + operator: "+", + left: segments[1], + right: make_node(AST_String, self, { + value: segments[2].value, + }), + }); + } + } + return self; +}); + +def_optimize(AST_PrefixedTemplateString, function(self) { + return self; +}); + +// ["p"]:1 ---> p:1 +// [42]:1 ---> 42:1 +function lift_key(self, compressor) { + if (!compressor.option("computed_props")) return self; + // save a comparison in the typical case + if (!(self.key instanceof AST_Constant)) return self; + // allow certain acceptable props as not all AST_Constants are true constants + if (self.key instanceof AST_String || self.key instanceof AST_Number) { + const key = self.key.value.toString(); + + if (key === "__proto__") return self; + if (key == "constructor" + && compressor.parent() instanceof AST_Class) return self; + if (self instanceof AST_ObjectKeyVal) { + self.quote = self.key.quote; + self.key = key; + } else if (self instanceof AST_ClassProperty) { + self.quote = self.key.quote; + self.key = make_node(AST_SymbolClassProperty, self.key, { + name: key, + }); + } else { + self.quote = self.key.quote; + self.key = make_node(AST_SymbolMethod, self.key, { + name: key, + }); + } + } + return self; +} + +def_optimize(AST_ObjectProperty, lift_key); + +def_optimize(AST_ConciseMethod, function(self, compressor) { + lift_key(self, compressor); + // p(){return x;} ---> p:()=>x + if (compressor.option("arrows") + && compressor.parent() instanceof AST_Object + && !self.is_generator + && !self.value.uses_arguments + && !self.value.pinned() + && self.value.body.length == 1 + && self.value.body[0] instanceof AST_Return + && self.value.body[0].value + && !self.value.contains_this()) { + var arrow = make_node(AST_Arrow, self.value, self.value); + arrow.async = self.async; + arrow.is_generator = self.is_generator; + return make_node(AST_ObjectKeyVal, self, { + key: self.key instanceof AST_SymbolMethod ? self.key.name : self.key, + value: arrow, + quote: self.quote, + }); + } + return self; +}); + +def_optimize(AST_ObjectKeyVal, function(self, compressor) { + lift_key(self, compressor); + // p:function(){} ---> p(){} + // p:function*(){} ---> *p(){} + // p:async function(){} ---> async p(){} + // p:()=>{} ---> p(){} + // p:async()=>{} ---> async p(){} + var unsafe_methods = compressor.option("unsafe_methods"); + if (unsafe_methods + && compressor.option("ecma") >= 2015 + && (!(unsafe_methods instanceof RegExp) || unsafe_methods.test(self.key + ""))) { + var key = self.key; + var value = self.value; + var is_arrow_with_block = value instanceof AST_Arrow + && Array.isArray(value.body) + && !value.contains_this(); + if ((is_arrow_with_block || value instanceof AST_Function) && !value.name) { + return make_node(AST_ConciseMethod, self, { + async: value.async, + is_generator: value.is_generator, + key: key instanceof AST_Node ? key : make_node(AST_SymbolMethod, self, { + name: key, + }), + value: make_node(AST_Accessor, value, value), + quote: self.quote, + }); + } + } + return self; +}); + +def_optimize(AST_Destructuring, function(self, compressor) { + if (compressor.option("pure_getters") == true + && compressor.option("unused") + && !self.is_array + && Array.isArray(self.names) + && !is_destructuring_export_decl(compressor) + && !(self.names[self.names.length - 1] instanceof AST_Expansion)) { + var keep = []; + for (var i = 0; i < self.names.length; i++) { + var elem = self.names[i]; + if (!(elem instanceof AST_ObjectKeyVal + && typeof elem.key == "string" + && elem.value instanceof AST_SymbolDeclaration + && !should_retain(compressor, elem.value.definition()))) { + keep.push(elem); + } + } + if (keep.length != self.names.length) { + self.names = keep; + } + } + return self; + + function is_destructuring_export_decl(compressor) { + var ancestors = [/^VarDef$/, /^(Const|Let|Var)$/, /^Export$/]; + for (var a = 0, p = 0, len = ancestors.length; a < len; p++) { + var parent = compressor.parent(p); + if (!parent) return false; + if (a === 0 && parent.TYPE == "Destructuring") continue; + if (!ancestors[a].test(parent.TYPE)) { + return false; + } + a++; + } + return true; + } + + function should_retain(compressor, def) { + if (def.references.length) return true; + if (!def.global) return false; + if (compressor.toplevel.vars) { + if (compressor.top_retain) { + return compressor.top_retain(def); + } + return false; + } + return true; + } +}); + +export { + Compressor, +}; diff --git a/node_modules/terser/lib/compress/inference.js b/node_modules/terser/lib/compress/inference.js new file mode 100644 index 0000000..b9f4881 --- /dev/null +++ b/node_modules/terser/lib/compress/inference.js @@ -0,0 +1,984 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { + AST_Array, + AST_Arrow, + AST_Assign, + AST_BigInt, + AST_Binary, + AST_Block, + AST_BlockStatement, + AST_Call, + AST_Case, + AST_Chain, + AST_Class, + AST_DefClass, + AST_ClassStaticBlock, + AST_ClassProperty, + AST_ConciseMethod, + AST_Conditional, + AST_Constant, + AST_Definitions, + AST_Dot, + AST_EmptyStatement, + AST_Expansion, + AST_False, + AST_ForIn, + AST_Function, + AST_If, + AST_Import, + AST_ImportMeta, + AST_Jump, + AST_LabeledStatement, + AST_Lambda, + AST_New, + AST_Node, + AST_Null, + AST_Number, + AST_Object, + AST_ObjectGetter, + AST_ObjectKeyVal, + AST_ObjectProperty, + AST_ObjectSetter, + AST_PropAccess, + AST_RegExp, + AST_Return, + AST_Scope, + AST_Sequence, + AST_SimpleStatement, + AST_Statement, + AST_String, + AST_Sub, + AST_Switch, + AST_SwitchBranch, + AST_SymbolClassProperty, + AST_SymbolDeclaration, + AST_SymbolRef, + AST_TemplateSegment, + AST_TemplateString, + AST_This, + AST_True, + AST_Try, + AST_Unary, + AST_UnaryPostfix, + AST_UnaryPrefix, + AST_Undefined, + AST_VarDef, + + walk, + walk_abort, + + _PURE +} from "../ast.js"; +import { + makePredicate, + return_true, + return_false, + return_null, + return_this, + make_node, + member, + has_annotation, +} from "../utils/index.js"; +import { make_sequence, best_of_expression, read_property } from "./common.js"; + +import { INLINED, UNDEFINED, has_flag } from "./compressor-flags.js"; +import { pure_prop_access_globals, is_pure_native_fn, is_pure_native_method } from "./native-objects.js"; + +// Functions and methods to infer certain facts about expressions +// It's not always possible to be 100% sure about something just by static analysis, +// so `true` means yes, and `false` means maybe + +export const is_undeclared_ref = (node) => + node instanceof AST_SymbolRef && node.definition().undeclared; + +export const bitwise_binop = makePredicate("<<< >> << & | ^ ~"); +export const lazy_op = makePredicate("&& || ??"); +export const unary_side_effects = makePredicate("delete ++ --"); + +// methods to determine whether an expression has a boolean result type +(function(def_is_boolean) { + const unary_bool = makePredicate("! delete"); + const binary_bool = makePredicate("in instanceof == != === !== < <= >= >"); + def_is_boolean(AST_Node, return_false); + def_is_boolean(AST_UnaryPrefix, function() { + return unary_bool.has(this.operator); + }); + def_is_boolean(AST_Binary, function() { + return binary_bool.has(this.operator) + || lazy_op.has(this.operator) + && this.left.is_boolean() + && this.right.is_boolean(); + }); + def_is_boolean(AST_Conditional, function() { + return this.consequent.is_boolean() && this.alternative.is_boolean(); + }); + def_is_boolean(AST_Assign, function() { + return this.operator == "=" && this.right.is_boolean(); + }); + def_is_boolean(AST_Sequence, function() { + return this.tail_node().is_boolean(); + }); + def_is_boolean(AST_True, return_true); + def_is_boolean(AST_False, return_true); +})(function(node, func) { + node.DEFMETHOD("is_boolean", func); +}); + +// methods to determine if an expression has a numeric result type +(function(def_is_number) { + def_is_number(AST_Node, return_false); + def_is_number(AST_Number, return_true); + const unary = makePredicate("+ - ~ ++ --"); + def_is_number(AST_Unary, function() { + return unary.has(this.operator) && !(this.expression instanceof AST_BigInt); + }); + const numeric_ops = makePredicate("- * / % & | ^ << >> >>>"); + def_is_number(AST_Binary, function(compressor) { + return numeric_ops.has(this.operator) || this.operator == "+" + && this.left.is_number(compressor) + && this.right.is_number(compressor); + }); + def_is_number(AST_Assign, function(compressor) { + return numeric_ops.has(this.operator.slice(0, -1)) + || this.operator == "=" && this.right.is_number(compressor); + }); + def_is_number(AST_Sequence, function(compressor) { + return this.tail_node().is_number(compressor); + }); + def_is_number(AST_Conditional, function(compressor) { + return this.consequent.is_number(compressor) && this.alternative.is_number(compressor); + }); +})(function(node, func) { + node.DEFMETHOD("is_number", func); +}); + +// methods to determine if an expression is a 32 bit integer (IE results from bitwise ops, or is an integer constant fitting in that size +(function(def_is_32_bit_integer) { + def_is_32_bit_integer(AST_Node, return_false); + def_is_32_bit_integer(AST_Number, function() { + return this.value === (this.value | 0); + }); + def_is_32_bit_integer(AST_UnaryPrefix, function() { + return this.operator == "~" ? this.expression.is_number() + : this.operator === "+" ? this.expression.is_32_bit_integer() + : false; + }); + def_is_32_bit_integer(AST_Binary, function() { + return bitwise_binop.has(this.operator); + }); +}(function (node, func) { + node.DEFMETHOD("is_32_bit_integer", func); +})); + +// methods to determine if an expression has a string result type +(function(def_is_string) { + def_is_string(AST_Node, return_false); + def_is_string(AST_String, return_true); + def_is_string(AST_TemplateString, return_true); + def_is_string(AST_UnaryPrefix, function() { + return this.operator == "typeof"; + }); + def_is_string(AST_Binary, function(compressor) { + return this.operator == "+" && + (this.left.is_string(compressor) || this.right.is_string(compressor)); + }); + def_is_string(AST_Assign, function(compressor) { + return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor); + }); + def_is_string(AST_Sequence, function(compressor) { + return this.tail_node().is_string(compressor); + }); + def_is_string(AST_Conditional, function(compressor) { + return this.consequent.is_string(compressor) && this.alternative.is_string(compressor); + }); +})(function(node, func) { + node.DEFMETHOD("is_string", func); +}); + +export function is_undefined(node, compressor) { + return ( + has_flag(node, UNDEFINED) + || node instanceof AST_Undefined + || node instanceof AST_UnaryPrefix + && node.operator == "void" + && !node.expression.has_side_effects(compressor) + ); +} + +// Is the node explicitly null or undefined. +function is_null_or_undefined(node, compressor) { + let fixed; + return ( + node instanceof AST_Null + || is_undefined(node, compressor) + || ( + node instanceof AST_SymbolRef + && (fixed = node.definition().fixed) instanceof AST_Node + && is_nullish(fixed, compressor) + ) + ); +} + +// Find out if this expression is optionally chained from a base-point that we +// can statically analyze as null or undefined. +export function is_nullish_shortcircuited(node, compressor) { + if (node instanceof AST_PropAccess || node instanceof AST_Call) { + return ( + (node.optional && is_null_or_undefined(node.expression, compressor)) + || is_nullish_shortcircuited(node.expression, compressor) + ); + } + if (node instanceof AST_Chain) return is_nullish_shortcircuited(node.expression, compressor); + return false; +} + +// Find out if something is == null, or can short circuit into nullish. +// Used to optimize ?. and ?? +export function is_nullish(node, compressor) { + if (is_null_or_undefined(node, compressor)) return true; + return is_nullish_shortcircuited(node, compressor); +} + +// Determine if expression might cause side effects +// If there's a possibility that a node may change something when it's executed, this returns true +(function(def_has_side_effects) { + def_has_side_effects(AST_Node, return_true); + + def_has_side_effects(AST_EmptyStatement, return_false); + def_has_side_effects(AST_Constant, return_false); + def_has_side_effects(AST_This, return_false); + + function any(list, compressor) { + for (var i = list.length; --i >= 0;) + if (list[i].has_side_effects(compressor)) + return true; + return false; + } + + def_has_side_effects(AST_Block, function(compressor) { + return any(this.body, compressor); + }); + def_has_side_effects(AST_Call, function(compressor) { + if ( + !this.is_callee_pure(compressor) + && (!this.expression.is_call_pure(compressor) + || this.expression.has_side_effects(compressor)) + ) { + return true; + } + return any(this.args, compressor); + }); + def_has_side_effects(AST_Switch, function(compressor) { + return this.expression.has_side_effects(compressor) + || any(this.body, compressor); + }); + def_has_side_effects(AST_Case, function(compressor) { + return this.expression.has_side_effects(compressor) + || any(this.body, compressor); + }); + def_has_side_effects(AST_Try, function(compressor) { + return this.body.has_side_effects(compressor) + || this.bcatch && this.bcatch.has_side_effects(compressor) + || this.bfinally && this.bfinally.has_side_effects(compressor); + }); + def_has_side_effects(AST_If, function(compressor) { + return this.condition.has_side_effects(compressor) + || this.body && this.body.has_side_effects(compressor) + || this.alternative && this.alternative.has_side_effects(compressor); + }); + def_has_side_effects(AST_ImportMeta, return_false); + def_has_side_effects(AST_LabeledStatement, function(compressor) { + return this.body.has_side_effects(compressor); + }); + def_has_side_effects(AST_SimpleStatement, function(compressor) { + return this.body.has_side_effects(compressor); + }); + def_has_side_effects(AST_Lambda, return_false); + def_has_side_effects(AST_Class, function (compressor) { + if (this.extends && this.extends.has_side_effects(compressor)) { + return true; + } + return any(this.properties, compressor); + }); + def_has_side_effects(AST_ClassStaticBlock, function(compressor) { + return any(this.body, compressor); + }); + def_has_side_effects(AST_Binary, function(compressor) { + return this.left.has_side_effects(compressor) + || this.right.has_side_effects(compressor); + }); + def_has_side_effects(AST_Assign, return_true); + def_has_side_effects(AST_Conditional, function(compressor) { + return this.condition.has_side_effects(compressor) + || this.consequent.has_side_effects(compressor) + || this.alternative.has_side_effects(compressor); + }); + def_has_side_effects(AST_Unary, function(compressor) { + return unary_side_effects.has(this.operator) + || this.expression.has_side_effects(compressor); + }); + def_has_side_effects(AST_SymbolRef, function(compressor) { + return !this.is_declared(compressor) && !pure_prop_access_globals.has(this.name); + }); + def_has_side_effects(AST_SymbolClassProperty, return_false); + def_has_side_effects(AST_SymbolDeclaration, return_false); + def_has_side_effects(AST_Object, function(compressor) { + return any(this.properties, compressor); + }); + def_has_side_effects(AST_ObjectProperty, function(compressor) { + return ( + this.computed_key() && this.key.has_side_effects(compressor) + || this.value && this.value.has_side_effects(compressor) + ); + }); + def_has_side_effects(AST_ClassProperty, function(compressor) { + return ( + this.computed_key() && this.key.has_side_effects(compressor) + || this.static && this.value && this.value.has_side_effects(compressor) + ); + }); + def_has_side_effects(AST_ConciseMethod, function(compressor) { + return this.computed_key() && this.key.has_side_effects(compressor); + }); + def_has_side_effects(AST_ObjectGetter, function(compressor) { + return this.computed_key() && this.key.has_side_effects(compressor); + }); + def_has_side_effects(AST_ObjectSetter, function(compressor) { + return this.computed_key() && this.key.has_side_effects(compressor); + }); + def_has_side_effects(AST_Array, function(compressor) { + return any(this.elements, compressor); + }); + def_has_side_effects(AST_Dot, function(compressor) { + if (is_nullish(this, compressor)) { + return this.expression.has_side_effects(compressor); + } + if (!this.optional && this.expression.may_throw_on_access(compressor)) { + return true; + } + + return this.expression.has_side_effects(compressor); + }); + def_has_side_effects(AST_Sub, function(compressor) { + if (is_nullish(this, compressor)) { + return this.expression.has_side_effects(compressor); + } + if (!this.optional && this.expression.may_throw_on_access(compressor)) { + return true; + } + + var property = this.property.has_side_effects(compressor); + if (property && this.optional) return true; // "?." is a condition + + return property || this.expression.has_side_effects(compressor); + }); + def_has_side_effects(AST_Chain, function (compressor) { + return this.expression.has_side_effects(compressor); + }); + def_has_side_effects(AST_Sequence, function(compressor) { + return any(this.expressions, compressor); + }); + def_has_side_effects(AST_Definitions, function(compressor) { + return any(this.definitions, compressor); + }); + def_has_side_effects(AST_VarDef, function() { + return this.value != null; + }); + def_has_side_effects(AST_TemplateSegment, return_false); + def_has_side_effects(AST_TemplateString, function(compressor) { + return any(this.segments, compressor); + }); +})(function(node, func) { + node.DEFMETHOD("has_side_effects", func); +}); + +// determine if expression may throw +(function(def_may_throw) { + def_may_throw(AST_Node, return_true); + + def_may_throw(AST_Constant, return_false); + def_may_throw(AST_EmptyStatement, return_false); + def_may_throw(AST_Lambda, return_false); + def_may_throw(AST_SymbolDeclaration, return_false); + def_may_throw(AST_This, return_false); + def_may_throw(AST_ImportMeta, return_false); + + function any(list, compressor) { + for (var i = list.length; --i >= 0;) + if (list[i].may_throw(compressor)) + return true; + return false; + } + + def_may_throw(AST_Class, function(compressor) { + if (this.extends && this.extends.may_throw(compressor)) return true; + return any(this.properties, compressor); + }); + def_may_throw(AST_ClassStaticBlock, function (compressor) { + return any(this.body, compressor); + }); + + def_may_throw(AST_Array, function(compressor) { + return any(this.elements, compressor); + }); + def_may_throw(AST_Assign, function(compressor) { + if (this.right.may_throw(compressor)) return true; + if (!compressor.has_directive("use strict") + && this.operator == "=" + && this.left instanceof AST_SymbolRef) { + return false; + } + return this.left.may_throw(compressor); + }); + def_may_throw(AST_Binary, function(compressor) { + return this.left.may_throw(compressor) + || this.right.may_throw(compressor); + }); + def_may_throw(AST_Block, function(compressor) { + return any(this.body, compressor); + }); + def_may_throw(AST_Call, function(compressor) { + if (is_nullish(this, compressor)) return false; + if (any(this.args, compressor)) return true; + if (this.is_callee_pure(compressor)) return false; + if (this.expression.may_throw(compressor)) return true; + return !(this.expression instanceof AST_Lambda) + || any(this.expression.body, compressor); + }); + def_may_throw(AST_Case, function(compressor) { + return this.expression.may_throw(compressor) + || any(this.body, compressor); + }); + def_may_throw(AST_Conditional, function(compressor) { + return this.condition.may_throw(compressor) + || this.consequent.may_throw(compressor) + || this.alternative.may_throw(compressor); + }); + def_may_throw(AST_Definitions, function(compressor) { + return any(this.definitions, compressor); + }); + def_may_throw(AST_If, function(compressor) { + return this.condition.may_throw(compressor) + || this.body && this.body.may_throw(compressor) + || this.alternative && this.alternative.may_throw(compressor); + }); + def_may_throw(AST_LabeledStatement, function(compressor) { + return this.body.may_throw(compressor); + }); + def_may_throw(AST_Object, function(compressor) { + return any(this.properties, compressor); + }); + def_may_throw(AST_ObjectProperty, function(compressor) { + // TODO key may throw too + return this.value ? this.value.may_throw(compressor) : false; + }); + def_may_throw(AST_ClassProperty, function(compressor) { + return ( + this.computed_key() && this.key.may_throw(compressor) + || this.static && this.value && this.value.may_throw(compressor) + ); + }); + def_may_throw(AST_ConciseMethod, function(compressor) { + return this.computed_key() && this.key.may_throw(compressor); + }); + def_may_throw(AST_ObjectGetter, function(compressor) { + return this.computed_key() && this.key.may_throw(compressor); + }); + def_may_throw(AST_ObjectSetter, function(compressor) { + return this.computed_key() && this.key.may_throw(compressor); + }); + def_may_throw(AST_Return, function(compressor) { + return this.value && this.value.may_throw(compressor); + }); + def_may_throw(AST_Sequence, function(compressor) { + return any(this.expressions, compressor); + }); + def_may_throw(AST_SimpleStatement, function(compressor) { + return this.body.may_throw(compressor); + }); + def_may_throw(AST_Dot, function(compressor) { + if (is_nullish(this, compressor)) return false; + return !this.optional && this.expression.may_throw_on_access(compressor) + || this.expression.may_throw(compressor); + }); + def_may_throw(AST_Sub, function(compressor) { + if (is_nullish(this, compressor)) return false; + return !this.optional && this.expression.may_throw_on_access(compressor) + || this.expression.may_throw(compressor) + || this.property.may_throw(compressor); + }); + def_may_throw(AST_Chain, function(compressor) { + return this.expression.may_throw(compressor); + }); + def_may_throw(AST_Switch, function(compressor) { + return this.expression.may_throw(compressor) + || any(this.body, compressor); + }); + def_may_throw(AST_SymbolRef, function(compressor) { + return !this.is_declared(compressor) && !pure_prop_access_globals.has(this.name); + }); + def_may_throw(AST_SymbolClassProperty, return_false); + def_may_throw(AST_Try, function(compressor) { + return this.bcatch ? this.bcatch.may_throw(compressor) : this.body.may_throw(compressor) + || this.bfinally && this.bfinally.may_throw(compressor); + }); + def_may_throw(AST_Unary, function(compressor) { + if (this.operator == "typeof" && this.expression instanceof AST_SymbolRef) + return false; + return this.expression.may_throw(compressor); + }); + def_may_throw(AST_VarDef, function(compressor) { + if (!this.value) return false; + return this.value.may_throw(compressor); + }); +})(function(node, func) { + node.DEFMETHOD("may_throw", func); +}); + +// determine if expression is constant +(function(def_is_constant_expression) { + function all_refs_local(scope) { + let result = true; + walk(this, node => { + if (node instanceof AST_SymbolRef) { + if (has_flag(this, INLINED)) { + result = false; + return walk_abort; + } + var def = node.definition(); + if ( + member(def, this.enclosed) + && !this.variables.has(def.name) + ) { + if (scope) { + var scope_def = scope.find_variable(node); + if (def.undeclared ? !scope_def : scope_def === def) { + result = "f"; + return true; + } + } + result = false; + return walk_abort; + } + return true; + } + if (node instanceof AST_This && this instanceof AST_Arrow) { + result = false; + return walk_abort; + } + }); + return result; + } + + def_is_constant_expression(AST_Node, return_false); + def_is_constant_expression(AST_Constant, return_true); + def_is_constant_expression(AST_Class, function(scope) { + if (this.extends && !this.extends.is_constant_expression(scope)) { + return false; + } + + for (const prop of this.properties) { + if (prop.computed_key() && !prop.key.is_constant_expression(scope)) { + return false; + } + if (prop.static && prop.value && !prop.value.is_constant_expression(scope)) { + return false; + } + if (prop instanceof AST_ClassStaticBlock) { + return false; + } + } + + return all_refs_local.call(this, scope); + }); + def_is_constant_expression(AST_Lambda, all_refs_local); + def_is_constant_expression(AST_Unary, function() { + return this.expression.is_constant_expression(); + }); + def_is_constant_expression(AST_Binary, function() { + return this.left.is_constant_expression() + && this.right.is_constant_expression(); + }); + def_is_constant_expression(AST_Array, function() { + return this.elements.every((l) => l.is_constant_expression()); + }); + def_is_constant_expression(AST_Object, function() { + return this.properties.every((l) => l.is_constant_expression()); + }); + def_is_constant_expression(AST_ObjectProperty, function() { + return !!(!(this.key instanceof AST_Node) && this.value && this.value.is_constant_expression()); + }); +})(function(node, func) { + node.DEFMETHOD("is_constant_expression", func); +}); + + +// may_throw_on_access() +// returns true if this node may be null, undefined or contain `AST_Accessor` +(function(def_may_throw_on_access) { + AST_Node.DEFMETHOD("may_throw_on_access", function(compressor) { + return !compressor.option("pure_getters") + || this._dot_throw(compressor); + }); + + function is_strict(compressor) { + return /strict/.test(compressor.option("pure_getters")); + } + + def_may_throw_on_access(AST_Node, is_strict); + def_may_throw_on_access(AST_Null, return_true); + def_may_throw_on_access(AST_Undefined, return_true); + def_may_throw_on_access(AST_Constant, return_false); + def_may_throw_on_access(AST_Array, return_false); + def_may_throw_on_access(AST_Object, function(compressor) { + if (!is_strict(compressor)) return false; + for (var i = this.properties.length; --i >=0;) + if (this.properties[i]._dot_throw(compressor)) return true; + return false; + }); + // Do not be as strict with classes as we are with objects. + // Hopefully the community is not going to abuse static getters and setters. + // https://github.com/terser/terser/issues/724#issuecomment-643655656 + def_may_throw_on_access(AST_Class, return_false); + def_may_throw_on_access(AST_ObjectProperty, return_false); + def_may_throw_on_access(AST_ObjectGetter, return_true); + def_may_throw_on_access(AST_Expansion, function(compressor) { + return this.expression._dot_throw(compressor); + }); + def_may_throw_on_access(AST_Function, return_false); + def_may_throw_on_access(AST_Arrow, return_false); + def_may_throw_on_access(AST_UnaryPostfix, return_false); + def_may_throw_on_access(AST_UnaryPrefix, function() { + return this.operator == "void"; + }); + def_may_throw_on_access(AST_Binary, function(compressor) { + return (this.operator == "&&" || this.operator == "||" || this.operator == "??") + && (this.left._dot_throw(compressor) || this.right._dot_throw(compressor)); + }); + def_may_throw_on_access(AST_Assign, function(compressor) { + if (this.logical) return true; + + return this.operator == "=" + && this.right._dot_throw(compressor); + }); + def_may_throw_on_access(AST_Conditional, function(compressor) { + return this.consequent._dot_throw(compressor) + || this.alternative._dot_throw(compressor); + }); + def_may_throw_on_access(AST_Dot, function(compressor) { + if (!is_strict(compressor)) return false; + + if (this.property == "prototype") { + return !( + this.expression instanceof AST_Function + || this.expression instanceof AST_Class + ); + } + return true; + }); + def_may_throw_on_access(AST_Chain, function(compressor) { + return this.expression._dot_throw(compressor); + }); + def_may_throw_on_access(AST_Sequence, function(compressor) { + return this.tail_node()._dot_throw(compressor); + }); + def_may_throw_on_access(AST_SymbolRef, function(compressor) { + if (this.name === "arguments" && this.scope instanceof AST_Lambda) return false; + if (has_flag(this, UNDEFINED)) return true; + if (!is_strict(compressor)) return false; + if (is_undeclared_ref(this) && this.is_declared(compressor)) return false; + if (this.is_immutable()) return false; + var fixed = this.fixed_value(); + return !fixed || fixed._dot_throw(compressor); + }); +})(function(node, func) { + node.DEFMETHOD("_dot_throw", func); +}); + +export function is_lhs(node, parent) { + if (parent instanceof AST_Unary && unary_side_effects.has(parent.operator)) return parent.expression; + if (parent instanceof AST_Assign && parent.left === node) return node; + if (parent instanceof AST_ForIn && parent.init === node) return node; +} + +// method to negate an expression +(function(def_negate) { + function basic_negation(exp) { + return make_node(AST_UnaryPrefix, exp, { + operator: "!", + expression: exp + }); + } + function best(orig, alt, first_in_statement) { + var negated = basic_negation(orig); + if (first_in_statement) { + var stat = make_node(AST_SimpleStatement, alt, { + body: alt + }); + return best_of_expression(negated, stat) === stat ? alt : negated; + } + return best_of_expression(negated, alt); + } + def_negate(AST_Node, function() { + return basic_negation(this); + }); + def_negate(AST_Statement, function() { + throw new Error("Cannot negate a statement"); + }); + def_negate(AST_Function, function() { + return basic_negation(this); + }); + def_negate(AST_Class, function() { + return basic_negation(this); + }); + def_negate(AST_Arrow, function() { + return basic_negation(this); + }); + def_negate(AST_UnaryPrefix, function() { + if (this.operator == "!") + return this.expression; + return basic_negation(this); + }); + def_negate(AST_Sequence, function(compressor) { + var expressions = this.expressions.slice(); + expressions.push(expressions.pop().negate(compressor)); + return make_sequence(this, expressions); + }); + def_negate(AST_Conditional, function(compressor, first_in_statement) { + var self = this.clone(); + self.consequent = self.consequent.negate(compressor); + self.alternative = self.alternative.negate(compressor); + return best(this, self, first_in_statement); + }); + def_negate(AST_Binary, function(compressor, first_in_statement) { + var self = this.clone(), op = this.operator; + if (compressor.option("unsafe_comps")) { + switch (op) { + case "<=" : self.operator = ">" ; return self; + case "<" : self.operator = ">=" ; return self; + case ">=" : self.operator = "<" ; return self; + case ">" : self.operator = "<=" ; return self; + } + } + switch (op) { + case "==" : self.operator = "!="; return self; + case "!=" : self.operator = "=="; return self; + case "===": self.operator = "!=="; return self; + case "!==": self.operator = "==="; return self; + case "&&": + self.operator = "||"; + self.left = self.left.negate(compressor, first_in_statement); + self.right = self.right.negate(compressor); + return best(this, self, first_in_statement); + case "||": + self.operator = "&&"; + self.left = self.left.negate(compressor, first_in_statement); + self.right = self.right.negate(compressor); + return best(this, self, first_in_statement); + } + return basic_negation(this); + }); +})(function(node, func) { + node.DEFMETHOD("negate", function(compressor, first_in_statement) { + return func.call(this, compressor, first_in_statement); + }); +}); + +(function (def_bitwise_negate) { + function basic_negation(exp) { + return make_node(AST_UnaryPrefix, exp, { + operator: "~", + expression: exp + }); + } + + def_bitwise_negate(AST_Node, function() { + return basic_negation(this); + }); + + def_bitwise_negate(AST_Number, function() { + const neg = ~this.value; + if (neg.toString().length > this.value.toString().length) { + return basic_negation(this); + } + return make_node(AST_Number, this, { value: neg }); + }); + + def_bitwise_negate(AST_UnaryPrefix, function(in_32_bit_context) { + if (this.operator == "~" && (in_32_bit_context || this.expression.is_32_bit_integer())) { + return this.expression; + } else { + return basic_negation(this); + } + }); +})(function (node, func) { + node.DEFMETHOD("bitwise_negate", func); +}); + +// Is the callee of this function pure? +var global_pure_fns = makePredicate("Boolean decodeURI decodeURIComponent Date encodeURI encodeURIComponent Error escape EvalError isFinite isNaN Number Object parseFloat parseInt RangeError ReferenceError String SyntaxError TypeError unescape URIError"); +AST_Call.DEFMETHOD("is_callee_pure", function(compressor) { + if (compressor.option("unsafe")) { + var expr = this.expression; + var first_arg = (this.args && this.args[0] && this.args[0].evaluate(compressor)); + if ( + expr.expression && expr.expression.name === "hasOwnProperty" && + (first_arg == null || first_arg.thedef && first_arg.thedef.undeclared) + ) { + return false; + } + if (is_undeclared_ref(expr) && global_pure_fns.has(expr.name)) return true; + if ( + expr instanceof AST_Dot + && is_undeclared_ref(expr.expression) + && is_pure_native_fn(expr.expression.name, expr.property) + ) { + return true; + } + } + if ((this instanceof AST_New) && compressor.option("pure_new")) { + return true; + } + if (compressor.option("side_effects") && has_annotation(this, _PURE)) { + return true; + } + return !compressor.pure_funcs(this); +}); + +// If I call this, is it a pure function? +AST_Node.DEFMETHOD("is_call_pure", return_false); +AST_Dot.DEFMETHOD("is_call_pure", function(compressor) { + if (!compressor.option("unsafe")) return; + const expr = this.expression; + + let native_obj; + if (expr instanceof AST_Array) { + native_obj = "Array"; + } else if (expr.is_boolean()) { + native_obj = "Boolean"; + } else if (expr.is_number(compressor)) { + native_obj = "Number"; + } else if (expr instanceof AST_RegExp) { + native_obj = "RegExp"; + } else if (expr.is_string(compressor)) { + native_obj = "String"; + } else if (!this.may_throw_on_access(compressor)) { + native_obj = "Object"; + } + return native_obj != null && is_pure_native_method(native_obj, this.property); +}); + +// tell me if a statement aborts +export const aborts = (thing) => thing && thing.aborts(); + +(function(def_aborts) { + def_aborts(AST_Statement, return_null); + def_aborts(AST_Jump, return_this); + function block_aborts() { + for (var i = 0; i < this.body.length; i++) { + if (aborts(this.body[i])) { + return this.body[i]; + } + } + return null; + } + def_aborts(AST_Import, return_null); + def_aborts(AST_BlockStatement, block_aborts); + def_aborts(AST_SwitchBranch, block_aborts); + def_aborts(AST_DefClass, function () { + for (const prop of this.properties) { + if (prop instanceof AST_ClassStaticBlock) { + if (prop.aborts()) return prop; + } + } + return null; + }); + def_aborts(AST_ClassStaticBlock, block_aborts); + def_aborts(AST_If, function() { + return this.alternative && aborts(this.body) && aborts(this.alternative) && this; + }); +})(function(node, func) { + node.DEFMETHOD("aborts", func); +}); + +AST_Node.DEFMETHOD("contains_this", function() { + return walk(this, node => { + if (node instanceof AST_This) return walk_abort; + if ( + node !== this + && node instanceof AST_Scope + && !(node instanceof AST_Arrow) + ) { + return true; + } + }); +}); + +export function is_modified(compressor, tw, node, value, level, immutable) { + var parent = tw.parent(level); + var lhs = is_lhs(node, parent); + if (lhs) return lhs; + if (!immutable + && parent instanceof AST_Call + && parent.expression === node + && !(value instanceof AST_Arrow) + && !(value instanceof AST_Class) + && !parent.is_callee_pure(compressor) + && (!(value instanceof AST_Function) + || !(parent instanceof AST_New) && value.contains_this())) { + return true; + } + if (parent instanceof AST_Array) { + return is_modified(compressor, tw, parent, parent, level + 1); + } + if (parent instanceof AST_ObjectKeyVal && node === parent.value) { + var obj = tw.parent(level + 1); + return is_modified(compressor, tw, obj, obj, level + 2); + } + if (parent instanceof AST_PropAccess && parent.expression === node) { + var prop = read_property(value, parent.property); + return !immutable && is_modified(compressor, tw, parent, prop, level + 1); + } +} diff --git a/node_modules/terser/lib/compress/inline.js b/node_modules/terser/lib/compress/inline.js new file mode 100644 index 0000000..1dda72b --- /dev/null +++ b/node_modules/terser/lib/compress/inline.js @@ -0,0 +1,669 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { + AST_Array, + AST_Assign, + AST_Block, + AST_Call, + AST_Catch, + AST_Class, + AST_ClassExpression, + AST_DefaultAssign, + AST_DefClass, + AST_Defun, + AST_Destructuring, + AST_EmptyStatement, + AST_Expansion, + AST_Export, + AST_Function, + AST_IterationStatement, + AST_Lambda, + AST_Node, + AST_Number, + AST_Object, + AST_ObjectKeyVal, + AST_PropAccess, + AST_Return, + AST_Scope, + AST_SimpleStatement, + AST_Statement, + AST_SymbolDefun, + AST_SymbolFunarg, + AST_SymbolLambda, + AST_SymbolRef, + AST_SymbolVar, + AST_This, + AST_Toplevel, + AST_UnaryPrefix, + AST_Undefined, + AST_Var, + AST_VarDef, + + walk, + + _INLINE, + _NOINLINE, + _PURE, +} from "../ast.js"; +import { make_node, has_annotation } from "../utils/index.js"; +import "../size.js"; + +import "./evaluate.js"; +import "./drop-side-effect-free.js"; +import "./reduce-vars.js"; +import { + SQUEEZED, + INLINED, + UNUSED, + + has_flag, + set_flag, +} from "./compressor-flags.js"; +import { + make_sequence, + best_of, + make_node_from_constant, + identifier_atom, + is_empty, + is_func_expr, + is_iife_call, + is_reachable, + is_recursive_ref, + retain_top_func, +} from "./common.js"; + +/** + * Module that contains the inlining logic. + * + * @module + * + * The stars of the show are `inline_into_symbolref` and `inline_into_call`. + */ + +function within_array_or_object_literal(compressor) { + var node, level = 0; + while (node = compressor.parent(level++)) { + if (node instanceof AST_Statement) return false; + if (node instanceof AST_Array + || node instanceof AST_ObjectKeyVal + || node instanceof AST_Object) { + return true; + } + } + return false; +} + +function scope_encloses_variables_in_this_scope(scope, pulled_scope) { + for (const enclosed of pulled_scope.enclosed) { + if (pulled_scope.variables.has(enclosed.name)) { + continue; + } + const looked_up = scope.find_variable(enclosed.name); + if (looked_up) { + if (looked_up === enclosed) continue; + return true; + } + } + return false; +} + +/** + * An extra check function for `top_retain` option, compare the length of const identifier + * and init value length and return true if init value is longer than identifier. for example: + * ``` + * // top_retain: ["example"] + * const example = 100 + * ``` + * it will return false because length of "100" is short than identifier "example". + */ +function is_const_symbol_short_than_init_value(def, fixed_value) { + if (def.orig.length === 1 && fixed_value) { + const init_value_length = fixed_value.size(); + const identifer_length = def.name.length; + return init_value_length > identifer_length; + } + return true; +} + +export function inline_into_symbolref(self, compressor) { + if (compressor.in_computed_key()) return self; + + const parent = compressor.parent(); + const def = self.definition(); + const nearest_scope = compressor.find_scope(); + let fixed = self.fixed_value(); + if ( + compressor.top_retain && + def.global && + compressor.top_retain(def) && + // when identifier is in top_retain option dose not mean we can always inline it. + // if identifier name is longer then init value, we can replace it. + is_const_symbol_short_than_init_value(def, fixed) + ) { + // keep it + def.fixed = false; + def.single_use = false; + return self; + } + + let single_use = def.single_use + && !(parent instanceof AST_Call + && (parent.is_callee_pure(compressor)) + || has_annotation(parent, _NOINLINE)) + && !(parent instanceof AST_Export + && fixed instanceof AST_Lambda + && fixed.name); + + if (single_use && fixed instanceof AST_Node) { + single_use = + !fixed.has_side_effects(compressor) + && !fixed.may_throw(compressor); + } + + if (fixed instanceof AST_Class && def.scope !== self.scope) { + return self; + } + + if (single_use && (fixed instanceof AST_Lambda || fixed instanceof AST_Class)) { + if (retain_top_func(fixed, compressor)) { + single_use = false; + } else if (def.scope !== self.scope + && (def.escaped == 1 + || has_flag(fixed, INLINED) + || within_array_or_object_literal(compressor) + || !compressor.option("reduce_funcs"))) { + single_use = false; + } else if (is_recursive_ref(compressor, def)) { + single_use = false; + } else if (def.scope !== self.scope || def.orig[0] instanceof AST_SymbolFunarg) { + single_use = fixed.is_constant_expression(self.scope); + if (single_use == "f") { + var scope = self.scope; + do { + if (scope instanceof AST_Defun || is_func_expr(scope)) { + set_flag(scope, INLINED); + } + } while (scope = scope.parent_scope); + } + } + } + + if (single_use && (fixed instanceof AST_Lambda || fixed instanceof AST_Class)) { + single_use = + def.scope === self.scope + && !scope_encloses_variables_in_this_scope(nearest_scope, fixed) + || parent instanceof AST_Call + && parent.expression === self + && !scope_encloses_variables_in_this_scope(nearest_scope, fixed) + && !(fixed.name && fixed.name.definition().recursive_refs > 0); + } + + if (single_use && fixed) { + if (fixed instanceof AST_DefClass) { + set_flag(fixed, SQUEEZED); + fixed = make_node(AST_ClassExpression, fixed, fixed); + } + if (fixed instanceof AST_Defun) { + set_flag(fixed, SQUEEZED); + fixed = make_node(AST_Function, fixed, fixed); + } + if (def.recursive_refs > 0 && fixed.name instanceof AST_SymbolDefun) { + const defun_def = fixed.name.definition(); + let lambda_def = fixed.variables.get(fixed.name.name); + let name = lambda_def && lambda_def.orig[0]; + if (!(name instanceof AST_SymbolLambda)) { + name = make_node(AST_SymbolLambda, fixed.name, fixed.name); + name.scope = fixed; + fixed.name = name; + lambda_def = fixed.def_function(name); + } + walk(fixed, node => { + if (node instanceof AST_SymbolRef && node.definition() === defun_def) { + node.thedef = lambda_def; + lambda_def.references.push(node); + } + }); + } + if ( + (fixed instanceof AST_Lambda || fixed instanceof AST_Class) + && fixed.parent_scope !== nearest_scope + ) { + fixed = fixed.clone(true, compressor.get_toplevel()); + + nearest_scope.add_child_scope(fixed); + } + return fixed.optimize(compressor); + } + + // multiple uses + if (fixed) { + let replace; + + if (fixed instanceof AST_This) { + if (!(def.orig[0] instanceof AST_SymbolFunarg) + && def.references.every((ref) => + def.scope === ref.scope + )) { + replace = fixed; + } + } else { + var ev = fixed.evaluate(compressor); + if ( + ev !== fixed + && (compressor.option("unsafe_regexp") || !(ev instanceof RegExp)) + ) { + replace = make_node_from_constant(ev, fixed); + } + } + + if (replace) { + const name_length = self.size(compressor); + const replace_size = replace.size(compressor); + + let overhead = 0; + if (compressor.option("unused") && !compressor.exposed(def)) { + overhead = + (name_length + 2 + fixed.size(compressor)) / + (def.references.length - def.assignments); + } + + if (replace_size <= name_length + overhead) { + return replace; + } + } + } + + return self; +} + +export function inline_into_call(self, compressor) { + if (compressor.in_computed_key()) return self; + + var exp = self.expression; + var fn = exp; + var simple_args = self.args.every((arg) => !(arg instanceof AST_Expansion)); + + if (compressor.option("reduce_vars") + && fn instanceof AST_SymbolRef + && !has_annotation(self, _NOINLINE) + ) { + const fixed = fn.fixed_value(); + + if ( + retain_top_func(fixed, compressor) + || !compressor.toplevel.funcs && exp.definition().global + ) { + return self; + } + + fn = fixed; + } + + var is_func = fn instanceof AST_Lambda; + + var stat = is_func && fn.body[0]; + var is_regular_func = is_func && !fn.is_generator && !fn.async; + var can_inline = is_regular_func && compressor.option("inline") && !self.is_callee_pure(compressor); + if (can_inline && stat instanceof AST_Return) { + let returned = stat.value; + if (!returned || returned.is_constant_expression()) { + if (returned) { + returned = returned.clone(true); + } else { + returned = make_node(AST_Undefined, self); + } + const args = self.args.concat(returned); + return make_sequence(self, args).optimize(compressor); + } + + // optimize identity function + if ( + fn.argnames.length === 1 + && (fn.argnames[0] instanceof AST_SymbolFunarg) + && self.args.length < 2 + && !(self.args[0] instanceof AST_Expansion) + && returned instanceof AST_SymbolRef + && returned.name === fn.argnames[0].name + ) { + const replacement = + (self.args[0] || make_node(AST_Undefined)).optimize(compressor); + + let parent; + if ( + replacement instanceof AST_PropAccess + && (parent = compressor.parent()) instanceof AST_Call + && parent.expression === self + ) { + // identity function was being used to remove `this`, like in + // + // id(bag.no_this)(...) + // + // Replace with a larger but more effish (0, bag.no_this) wrapper. + + return make_sequence(self, [ + make_node(AST_Number, self, { value: 0 }), + replacement + ]); + } + // replace call with first argument or undefined if none passed + return replacement; + } + } + + if (can_inline) { + var scope, in_loop, level = -1; + let def; + let returned_value; + let nearest_scope; + if (simple_args + && !fn.uses_arguments + && !(compressor.parent() instanceof AST_Class) + && !(fn.name && fn instanceof AST_Function) + && (returned_value = can_flatten_body(stat)) + && (exp === fn + || has_annotation(self, _INLINE) + || compressor.option("unused") + && (def = exp.definition()).references.length == 1 + && !is_recursive_ref(compressor, def) + && fn.is_constant_expression(exp.scope)) + && !has_annotation(self, _PURE | _NOINLINE) + && !fn.contains_this() + && can_inject_symbols() + && (nearest_scope = compressor.find_scope()) + && !scope_encloses_variables_in_this_scope(nearest_scope, fn) + && !(function in_default_assign() { + // Due to the fact function parameters have their own scope + // which can't use `var something` in the function body within, + // we simply don't inline into DefaultAssign. + let i = 0; + let p; + while ((p = compressor.parent(i++))) { + if (p instanceof AST_DefaultAssign) return true; + if (p instanceof AST_Block) break; + } + return false; + })() + && !(scope instanceof AST_Class) + ) { + set_flag(fn, SQUEEZED); + nearest_scope.add_child_scope(fn); + return make_sequence(self, flatten_fn(returned_value)).optimize(compressor); + } + } + + if (can_inline && has_annotation(self, _INLINE)) { + set_flag(fn, SQUEEZED); + fn = make_node(fn.CTOR === AST_Defun ? AST_Function : fn.CTOR, fn, fn); + fn = fn.clone(true); + fn.figure_out_scope({}, { + parent_scope: compressor.find_scope(), + toplevel: compressor.get_toplevel() + }); + + return make_node(AST_Call, self, { + expression: fn, + args: self.args, + }).optimize(compressor); + } + + const can_drop_this_call = is_regular_func && compressor.option("side_effects") && fn.body.every(is_empty); + if (can_drop_this_call) { + var args = self.args.concat(make_node(AST_Undefined, self)); + return make_sequence(self, args).optimize(compressor); + } + + if (compressor.option("negate_iife") + && compressor.parent() instanceof AST_SimpleStatement + && is_iife_call(self)) { + return self.negate(compressor, true); + } + + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + + return self; + + function return_value(stat) { + if (!stat) return make_node(AST_Undefined, self); + if (stat instanceof AST_Return) { + if (!stat.value) return make_node(AST_Undefined, self); + return stat.value.clone(true); + } + if (stat instanceof AST_SimpleStatement) { + return make_node(AST_UnaryPrefix, stat, { + operator: "void", + expression: stat.body.clone(true) + }); + } + } + + function can_flatten_body(stat) { + var body = fn.body; + var len = body.length; + if (compressor.option("inline") < 3) { + return len == 1 && return_value(stat); + } + stat = null; + for (var i = 0; i < len; i++) { + var line = body[i]; + if (line instanceof AST_Var) { + if (stat && !line.definitions.every((var_def) => + !var_def.value + )) { + return false; + } + } else if (stat) { + return false; + } else if (!(line instanceof AST_EmptyStatement)) { + stat = line; + } + } + return return_value(stat); + } + + function can_inject_args(block_scoped, safe_to_inject) { + for (var i = 0, len = fn.argnames.length; i < len; i++) { + var arg = fn.argnames[i]; + if (arg instanceof AST_DefaultAssign) { + if (has_flag(arg.left, UNUSED)) continue; + return false; + } + if (arg instanceof AST_Destructuring) return false; + if (arg instanceof AST_Expansion) { + if (has_flag(arg.expression, UNUSED)) continue; + return false; + } + if (has_flag(arg, UNUSED)) continue; + if (!safe_to_inject + || block_scoped.has(arg.name) + || identifier_atom.has(arg.name) + || scope.conflicting_def(arg.name)) { + return false; + } + if (in_loop) in_loop.push(arg.definition()); + } + return true; + } + + function can_inject_vars(block_scoped, safe_to_inject) { + var len = fn.body.length; + for (var i = 0; i < len; i++) { + var stat = fn.body[i]; + if (!(stat instanceof AST_Var)) continue; + if (!safe_to_inject) return false; + for (var j = stat.definitions.length; --j >= 0;) { + var name = stat.definitions[j].name; + if (name instanceof AST_Destructuring + || block_scoped.has(name.name) + || identifier_atom.has(name.name) + || scope.conflicting_def(name.name)) { + return false; + } + if (in_loop) in_loop.push(name.definition()); + } + } + return true; + } + + function can_inject_symbols() { + var block_scoped = new Set(); + do { + scope = compressor.parent(++level); + if (scope.is_block_scope() && scope.block_scope) { + // TODO this is sometimes undefined during compression. + // But it should always have a value! + scope.block_scope.variables.forEach(function (variable) { + block_scoped.add(variable.name); + }); + } + if (scope instanceof AST_Catch) { + // TODO can we delete? AST_Catch is a block scope. + if (scope.argname) { + block_scoped.add(scope.argname.name); + } + } else if (scope instanceof AST_IterationStatement) { + in_loop = []; + } else if (scope instanceof AST_SymbolRef) { + if (scope.fixed_value() instanceof AST_Scope) return false; + } + } while (!(scope instanceof AST_Scope)); + + var safe_to_inject = !(scope instanceof AST_Toplevel) || compressor.toplevel.vars; + var inline = compressor.option("inline"); + if (!can_inject_vars(block_scoped, inline >= 3 && safe_to_inject)) return false; + if (!can_inject_args(block_scoped, inline >= 2 && safe_to_inject)) return false; + return !in_loop || in_loop.length == 0 || !is_reachable(fn, in_loop); + } + + function append_var(decls, expressions, name, value) { + var def = name.definition(); + + // Name already exists, only when a function argument had the same name + const already_appended = scope.variables.has(name.name); + if (!already_appended) { + scope.variables.set(name.name, def); + scope.enclosed.push(def); + decls.push(make_node(AST_VarDef, name, { + name: name, + value: null + })); + } + + var sym = make_node(AST_SymbolRef, name, name); + def.references.push(sym); + if (value) expressions.push(make_node(AST_Assign, self, { + operator: "=", + logical: false, + left: sym, + right: value.clone() + })); + } + + function flatten_args(decls, expressions) { + var len = fn.argnames.length; + for (var i = self.args.length; --i >= len;) { + expressions.push(self.args[i]); + } + for (i = len; --i >= 0;) { + var name = fn.argnames[i]; + var value = self.args[i]; + if (has_flag(name, UNUSED) || !name.name || scope.conflicting_def(name.name)) { + if (value) expressions.push(value); + } else { + var symbol = make_node(AST_SymbolVar, name, name); + name.definition().orig.push(symbol); + if (!value && in_loop) value = make_node(AST_Undefined, self); + append_var(decls, expressions, symbol, value); + } + } + decls.reverse(); + expressions.reverse(); + } + + function flatten_vars(decls, expressions) { + var pos = expressions.length; + for (var i = 0, lines = fn.body.length; i < lines; i++) { + var stat = fn.body[i]; + if (!(stat instanceof AST_Var)) continue; + for (var j = 0, defs = stat.definitions.length; j < defs; j++) { + var var_def = stat.definitions[j]; + var name = var_def.name; + append_var(decls, expressions, name, var_def.value); + if (in_loop && fn.argnames.every((argname) => + argname.name != name.name + )) { + var def = fn.variables.get(name.name); + var sym = make_node(AST_SymbolRef, name, name); + def.references.push(sym); + expressions.splice(pos++, 0, make_node(AST_Assign, var_def, { + operator: "=", + logical: false, + left: sym, + right: make_node(AST_Undefined, name) + })); + } + } + } + } + + function flatten_fn(returned_value) { + var decls = []; + var expressions = []; + flatten_args(decls, expressions); + flatten_vars(decls, expressions); + expressions.push(returned_value); + + if (decls.length) { + const i = scope.body.indexOf(compressor.parent(level - 1)) + 1; + scope.body.splice(i, 0, make_node(AST_Var, fn, { + definitions: decls + })); + } + + return expressions.map(exp => exp.clone(true)); + } +} diff --git a/node_modules/terser/lib/compress/native-objects.js b/node_modules/terser/lib/compress/native-objects.js new file mode 100644 index 0000000..d7cb704 --- /dev/null +++ b/node_modules/terser/lib/compress/native-objects.js @@ -0,0 +1,206 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { makePredicate } from "../utils/index.js"; + +// Lists of native methods, useful for `unsafe` option which assumes they exist. +// Note: Lots of methods and functions are missing here, in case they aren't pure +// or not available in all JS environments. + +function make_nested_lookup(obj) { + const out = new Map(); + for (var key of Object.keys(obj)) { + out.set(key, makePredicate(obj[key])); + } + + const does_have = (global_name, fname) => { + const inner_map = out.get(global_name); + return inner_map != null && inner_map.has(fname); + }; + return does_have; +} + +// Objects which are safe to access without throwing or causing a side effect. +// Usually we'd check the `unsafe` option first but these are way too common for that +export const pure_prop_access_globals = new Set([ + "Number", + "String", + "Array", + "Object", + "Function", + "Promise", +]); + +const object_methods = [ + "constructor", + "toString", + "valueOf", +]; + +export const is_pure_native_method = make_nested_lookup({ + Array: [ + "at", + "flat", + "includes", + "indexOf", + "join", + "lastIndexOf", + "slice", + ...object_methods, + ], + Boolean: object_methods, + Function: object_methods, + Number: [ + "toExponential", + "toFixed", + "toPrecision", + ...object_methods, + ], + Object: object_methods, + RegExp: [ + "test", + ...object_methods, + ], + String: [ + "at", + "charAt", + "charCodeAt", + "charPointAt", + "concat", + "endsWith", + "fromCharCode", + "fromCodePoint", + "includes", + "indexOf", + "italics", + "lastIndexOf", + "localeCompare", + "match", + "matchAll", + "normalize", + "padStart", + "padEnd", + "repeat", + "replace", + "replaceAll", + "search", + "slice", + "split", + "startsWith", + "substr", + "substring", + "repeat", + "toLocaleLowerCase", + "toLocaleUpperCase", + "toLowerCase", + "toUpperCase", + "trim", + "trimEnd", + "trimStart", + ...object_methods, + ], +}); + +export const is_pure_native_fn = make_nested_lookup({ + Array: [ + "isArray", + ], + Math: [ + "abs", + "acos", + "asin", + "atan", + "ceil", + "cos", + "exp", + "floor", + "log", + "round", + "sin", + "sqrt", + "tan", + "atan2", + "pow", + "max", + "min", + ], + Number: [ + "isFinite", + "isNaN", + ], + Object: [ + "create", + "getOwnPropertyDescriptor", + "getOwnPropertyNames", + "getPrototypeOf", + "isExtensible", + "isFrozen", + "isSealed", + "hasOwn", + "keys", + ], + String: [ + "fromCharCode", + ], +}); + +// Known numeric values which come with JS environments +export const is_pure_native_value = make_nested_lookup({ + Math: [ + "E", + "LN10", + "LN2", + "LOG2E", + "LOG10E", + "PI", + "SQRT1_2", + "SQRT2", + ], + Number: [ + "MAX_VALUE", + "MIN_VALUE", + "NaN", + "NEGATIVE_INFINITY", + "POSITIVE_INFINITY", + ], +}); diff --git a/node_modules/terser/lib/compress/reduce-vars.js b/node_modules/terser/lib/compress/reduce-vars.js new file mode 100644 index 0000000..ec1dd60 --- /dev/null +++ b/node_modules/terser/lib/compress/reduce-vars.js @@ -0,0 +1,859 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { + AST_Accessor, + AST_Array, + AST_Assign, + AST_Await, + AST_Binary, + AST_Block, + AST_Call, + AST_Case, + AST_Chain, + AST_Class, + AST_ClassStaticBlock, + AST_ClassExpression, + AST_Conditional, + AST_Default, + AST_Defun, + AST_Destructuring, + AST_Do, + AST_Exit, + AST_Expansion, + AST_For, + AST_ForIn, + AST_If, + AST_LabeledStatement, + AST_Lambda, + AST_New, + AST_Node, + AST_Number, + AST_ObjectKeyVal, + AST_PropAccess, + AST_Scope, + AST_Sequence, + AST_SimpleStatement, + AST_Symbol, + AST_SymbolCatch, + AST_SymbolConst, + AST_SymbolDeclaration, + AST_SymbolDefun, + AST_SymbolFunarg, + AST_SymbolLambda, + AST_SymbolRef, + AST_This, + AST_Toplevel, + AST_Try, + AST_Unary, + AST_UnaryPrefix, + AST_Undefined, + AST_VarDef, + AST_While, + AST_Yield, + + walk, + walk_body, + walk_parent, +} from "../ast.js"; +import { HOP, make_node, noop } from "../utils/index.js"; + +import { lazy_op, is_modified, is_lhs } from "./inference.js"; +import { INLINED, clear_flag } from "./compressor-flags.js"; +import { read_property, has_break_or_continue, is_recursive_ref } from "./common.js"; + +/** + * Define the method AST_Node#reduce_vars, which goes through the AST in + * execution order to perform basic flow analysis + */ +function def_reduce_vars(node, func) { + node.DEFMETHOD("reduce_vars", func); +} + +def_reduce_vars(AST_Node, noop); + +/** Clear definition properties */ +function reset_def(compressor, def) { + def.assignments = 0; + def.chained = false; + def.direct_access = false; + def.escaped = 0; + def.recursive_refs = 0; + def.references = []; + def.single_use = undefined; + if ( + def.scope.pinned() + || (def.orig[0] instanceof AST_SymbolFunarg && def.scope.uses_arguments) + ) { + def.fixed = false; + } else if (def.orig[0] instanceof AST_SymbolConst || !compressor.exposed(def)) { + def.fixed = def.init; + } else { + def.fixed = false; + } +} + +function reset_variables(tw, compressor, node) { + node.variables.forEach(function(def) { + reset_def(compressor, def); + if (def.fixed === null) { + tw.defs_to_safe_ids.set(def.id, tw.safe_ids); + mark(tw, def, true); + } else if (def.fixed) { + tw.loop_ids.set(def.id, tw.in_loop); + mark(tw, def, true); + } + }); +} + +function reset_block_variables(compressor, node) { + if (node.block_scope) node.block_scope.variables.forEach((def) => { + reset_def(compressor, def); + }); +} + +function push(tw) { + tw.safe_ids = Object.create(tw.safe_ids); +} + +function pop(tw) { + tw.safe_ids = Object.getPrototypeOf(tw.safe_ids); +} + +function mark(tw, def, safe) { + tw.safe_ids[def.id] = safe; +} + +function safe_to_read(tw, def) { + if (def.single_use == "m") return false; + if (tw.safe_ids[def.id]) { + if (def.fixed == null) { + var orig = def.orig[0]; + if (orig instanceof AST_SymbolFunarg || orig.name == "arguments") return false; + def.fixed = make_node(AST_Undefined, orig); + } + return true; + } + return def.fixed instanceof AST_Defun; +} + +function safe_to_assign(tw, def, scope, value) { + if (def.fixed === undefined) return true; + let def_safe_ids; + if (def.fixed === null + && (def_safe_ids = tw.defs_to_safe_ids.get(def.id)) + ) { + def_safe_ids[def.id] = false; + tw.defs_to_safe_ids.delete(def.id); + return true; + } + if (!HOP(tw.safe_ids, def.id)) return false; + if (!safe_to_read(tw, def)) return false; + if (def.fixed === false) return false; + if (def.fixed != null && (!value || def.references.length > def.assignments)) return false; + if (def.fixed instanceof AST_Defun) { + return value instanceof AST_Node && def.fixed.parent_scope === scope; + } + return def.orig.every((sym) => { + return !(sym instanceof AST_SymbolConst + || sym instanceof AST_SymbolDefun + || sym instanceof AST_SymbolLambda); + }); +} + +function ref_once(tw, compressor, def) { + return compressor.option("unused") + && !def.scope.pinned() + && def.references.length - def.recursive_refs == 1 + && tw.loop_ids.get(def.id) === tw.in_loop; +} + +function is_immutable(value) { + if (!value) return false; + return value.is_constant() + || value instanceof AST_Lambda + || value instanceof AST_This; +} + +// A definition "escapes" when its value can leave the point of use. +// Example: `a = b || c` +// In this example, "b" and "c" are escaping, because they're going into "a" +// +// def.escaped is != 0 when it escapes. +// +// When greater than 1, it means that N chained properties will be read off +// of that def before an escape occurs. This is useful for evaluating +// property accesses, where you need to know when to stop. +function mark_escaped(tw, d, scope, node, value, level = 0, depth = 1) { + var parent = tw.parent(level); + if (value) { + if (value.is_constant()) return; + if (value instanceof AST_ClassExpression) return; + } + + if ( + parent instanceof AST_Assign && (parent.operator === "=" || parent.logical) && node === parent.right + || parent instanceof AST_Call && (node !== parent.expression || parent instanceof AST_New) + || parent instanceof AST_Exit && node === parent.value && node.scope !== d.scope + || parent instanceof AST_VarDef && node === parent.value + || parent instanceof AST_Yield && node === parent.value && node.scope !== d.scope + ) { + if (depth > 1 && !(value && value.is_constant_expression(scope))) depth = 1; + if (!d.escaped || d.escaped > depth) d.escaped = depth; + return; + } else if ( + parent instanceof AST_Array + || parent instanceof AST_Await + || parent instanceof AST_Binary && lazy_op.has(parent.operator) + || parent instanceof AST_Conditional && node !== parent.condition + || parent instanceof AST_Expansion + || parent instanceof AST_Sequence && node === parent.tail_node() + ) { + mark_escaped(tw, d, scope, parent, parent, level + 1, depth); + } else if (parent instanceof AST_ObjectKeyVal && node === parent.value) { + var obj = tw.parent(level + 1); + + mark_escaped(tw, d, scope, obj, obj, level + 2, depth); + } else if (parent instanceof AST_PropAccess && node === parent.expression) { + value = read_property(value, parent.property); + + mark_escaped(tw, d, scope, parent, value, level + 1, depth + 1); + if (value) return; + } + + if (level > 0) return; + if (parent instanceof AST_Sequence && node !== parent.tail_node()) return; + if (parent instanceof AST_SimpleStatement) return; + + d.direct_access = true; +} + +const suppress = node => walk(node, node => { + if (!(node instanceof AST_Symbol)) return; + var d = node.definition(); + if (!d) return; + if (node instanceof AST_SymbolRef) d.references.push(node); + d.fixed = false; +}); + +def_reduce_vars(AST_Accessor, function(tw, descend, compressor) { + push(tw); + reset_variables(tw, compressor, this); + descend(); + pop(tw); + return true; +}); + +def_reduce_vars(AST_Assign, function(tw, descend, compressor) { + var node = this; + if (node.left instanceof AST_Destructuring) { + suppress(node.left); + return; + } + + const finish_walk = () => { + if (node.logical) { + node.left.walk(tw); + + push(tw); + node.right.walk(tw); + pop(tw); + + return true; + } + }; + + var sym = node.left; + if (!(sym instanceof AST_SymbolRef)) return finish_walk(); + + var def = sym.definition(); + var safe = safe_to_assign(tw, def, sym.scope, node.right); + def.assignments++; + if (!safe) return finish_walk(); + + var fixed = def.fixed; + if (!fixed && node.operator != "=" && !node.logical) return finish_walk(); + + var eq = node.operator == "="; + var value = eq ? node.right : node; + if (is_modified(compressor, tw, node, value, 0)) return finish_walk(); + + def.references.push(sym); + + if (!node.logical) { + if (!eq) def.chained = true; + + def.fixed = eq ? function() { + return node.right; + } : function() { + return make_node(AST_Binary, node, { + operator: node.operator.slice(0, -1), + left: fixed instanceof AST_Node ? fixed : fixed(), + right: node.right + }); + }; + } + + if (node.logical) { + mark(tw, def, false); + push(tw); + node.right.walk(tw); + pop(tw); + return true; + } + + mark(tw, def, false); + node.right.walk(tw); + mark(tw, def, true); + + mark_escaped(tw, def, sym.scope, node, value, 0, 1); + + return true; +}); + +def_reduce_vars(AST_Binary, function(tw) { + if (!lazy_op.has(this.operator)) return; + this.left.walk(tw); + push(tw); + this.right.walk(tw); + pop(tw); + return true; +}); + +def_reduce_vars(AST_Block, function(tw, descend, compressor) { + reset_block_variables(compressor, this); +}); + +def_reduce_vars(AST_Case, function(tw) { + push(tw); + this.expression.walk(tw); + pop(tw); + push(tw); + walk_body(this, tw); + pop(tw); + return true; +}); + +def_reduce_vars(AST_Class, function(tw, descend) { + clear_flag(this, INLINED); + push(tw); + descend(); + pop(tw); + return true; +}); + +def_reduce_vars(AST_ClassStaticBlock, function(tw, descend, compressor) { + reset_block_variables(compressor, this); +}); + +def_reduce_vars(AST_Conditional, function(tw) { + this.condition.walk(tw); + push(tw); + this.consequent.walk(tw); + pop(tw); + push(tw); + this.alternative.walk(tw); + pop(tw); + return true; +}); + +def_reduce_vars(AST_Chain, function(tw, descend) { + // Chains' conditions apply left-to-right, cumulatively. + // If we walk normally we don't go in that order because we would pop before pushing again + // Solution: AST_PropAccess and AST_Call push when they are optional, and never pop. + // Then we pop everything when they are done being walked. + const safe_ids = tw.safe_ids; + + descend(); + + // Unroll back to start + tw.safe_ids = safe_ids; + return true; +}); + +def_reduce_vars(AST_Call, function (tw) { + this.expression.walk(tw); + + if (this.optional) { + // Never pop -- it's popped at AST_Chain above + push(tw); + } + + for (const arg of this.args) arg.walk(tw); + + return true; +}); + +def_reduce_vars(AST_PropAccess, function (tw) { + if (!this.optional) return; + + this.expression.walk(tw); + + // Never pop -- it's popped at AST_Chain above + push(tw); + + if (this.property instanceof AST_Node) this.property.walk(tw); + + return true; +}); + +def_reduce_vars(AST_Default, function(tw, descend) { + push(tw); + descend(); + pop(tw); + return true; +}); + +function mark_lambda(tw, descend, compressor) { + clear_flag(this, INLINED); + push(tw); + reset_variables(tw, compressor, this); + + var iife; + if (!this.name + && !this.uses_arguments + && !this.pinned() + && (iife = tw.parent()) instanceof AST_Call + && iife.expression === this + && !iife.args.some(arg => arg instanceof AST_Expansion) + && this.argnames.every(arg_name => arg_name instanceof AST_Symbol) + ) { + // Virtually turn IIFE parameters into variable definitions: + // (function(a,b) {...})(c,d) => (function() {var a=c,b=d; ...})() + // So existing transformation rules can work on them. + this.argnames.forEach((arg, i) => { + if (!arg.definition) return; + var d = arg.definition(); + // Avoid setting fixed when there's more than one origin for a variable value + if (d.orig.length > 1) return; + if (d.fixed === undefined && (!this.uses_arguments || tw.has_directive("use strict"))) { + d.fixed = function() { + return iife.args[i] || make_node(AST_Undefined, iife); + }; + tw.loop_ids.set(d.id, tw.in_loop); + mark(tw, d, true); + } else { + d.fixed = false; + } + }); + } + + descend(); + pop(tw); + + handle_defined_after_hoist(this); + + return true; +} + +/** + * It's possible for a hoisted function to use something that's not defined yet. Example: + * + * hoisted(); + * var defined_after = true; + * function hoisted() { + * // use defined_after + * } + * + * Or even indirectly: + * + * B(); + * var defined_after = true; + * function A() { + * // use defined_after + * } + * function B() { + * A(); + * } + * + * Access a variable before declaration will either throw a ReferenceError + * (if the variable is declared with `let` or `const`), + * or get an `undefined` (if the variable is declared with `var`). + * + * If the variable is inlined into the function, the behavior will change. + * + * This function is called on the parent to disallow inlining of such variables, + */ +function handle_defined_after_hoist(parent) { + const defuns = []; + walk(parent, node => { + if (node === parent) return; + if (node instanceof AST_Defun) { + defuns.push(node); + return true; + } + if ( + node instanceof AST_Scope + || node instanceof AST_SimpleStatement + ) return true; + }); + + // `defun` id to array of `defun` it uses + const defun_dependencies_map = new Map(); + // `defun` id to array of enclosing `def` that are used by the function + const dependencies_map = new Map(); + // all symbol ids that will be tracked for read/write + const symbols_of_interest = new Set(); + const defuns_of_interest = new Set(); + + for (const defun of defuns) { + const fname_def = defun.name.definition(); + const enclosing_defs = []; + + for (const def of defun.enclosed) { + if ( + def.fixed === false + || def === fname_def + || def.scope.get_defun_scope() !== parent + ) { + continue; + } + + symbols_of_interest.add(def.id); + + // found a reference to another function + if ( + def.assignments === 0 + && def.orig.length === 1 + && def.orig[0] instanceof AST_SymbolDefun + ) { + defuns_of_interest.add(def.id); + symbols_of_interest.add(def.id); + + defuns_of_interest.add(fname_def.id); + symbols_of_interest.add(fname_def.id); + + if (!defun_dependencies_map.has(fname_def.id)) { + defun_dependencies_map.set(fname_def.id, []); + } + defun_dependencies_map.get(fname_def.id).push(def.id); + + continue; + } + + enclosing_defs.push(def); + } + + if (enclosing_defs.length) { + dependencies_map.set(fname_def.id, enclosing_defs); + defuns_of_interest.add(fname_def.id); + symbols_of_interest.add(fname_def.id); + } + } + + // No defuns use outside constants + if (!dependencies_map.size) { + return; + } + + // Increment to count "symbols of interest" (defuns or defs) that we found. + // These are tracked in AST order so we can check which is after which. + let symbol_index = 1; + // Map a defun ID to its first read (a `symbol_index`) + const defun_first_read_map = new Map(); + // Map a symbol ID to its last write (a `symbol_index`) + const symbol_last_write_map = new Map(); + + walk_parent(parent, (node, walk_info) => { + if (node instanceof AST_Symbol && node.thedef) { + const id = node.definition().id; + + symbol_index++; + + // Track last-writes to symbols + if (symbols_of_interest.has(id)) { + if (node instanceof AST_SymbolDeclaration || is_lhs(node, walk_info.parent())) { + symbol_last_write_map.set(id, symbol_index); + } + } + + // Track first-reads of defuns (refined later) + if (defuns_of_interest.has(id)) { + if (!defun_first_read_map.has(id) && !is_recursive_ref(walk_info, id)) { + defun_first_read_map.set(id, symbol_index); + } + } + } + }); + + // Refine `defun_first_read_map` to be as high as possible + for (const [defun, defun_first_read] of defun_first_read_map) { + // Update all depdencies of `defun` + const queue = new Set(defun_dependencies_map.get(defun)); + for (const enclosed_defun of queue) { + let enclosed_defun_first_read = defun_first_read_map.get(enclosed_defun); + if (enclosed_defun_first_read != null && enclosed_defun_first_read < defun_first_read) { + continue; + } + + defun_first_read_map.set(enclosed_defun, defun_first_read); + + for (const enclosed_enclosed_defun of defun_dependencies_map.get(enclosed_defun) || []) { + queue.add(enclosed_enclosed_defun); + } + } + } + + // ensure write-then-read order, otherwise clear `fixed` + // This is safe because last-writes (found_symbol_writes) are assumed to be as late as possible, and first-reads (defun_first_read_map) are assumed to be as early as possible. + for (const [defun, defs] of dependencies_map) { + const defun_first_read = defun_first_read_map.get(defun); + if (defun_first_read === undefined) { + continue; + } + + for (const def of defs) { + if (def.fixed === false) { + continue; + } + + let def_last_write = symbol_last_write_map.get(def.id) || 0; + + if (defun_first_read < def_last_write) { + def.fixed = false; + } + } + } +} + +def_reduce_vars(AST_Lambda, mark_lambda); + +def_reduce_vars(AST_Do, function(tw, descend, compressor) { + reset_block_variables(compressor, this); + const saved_loop = tw.in_loop; + tw.in_loop = this; + push(tw); + this.body.walk(tw); + if (has_break_or_continue(this)) { + pop(tw); + push(tw); + } + this.condition.walk(tw); + pop(tw); + tw.in_loop = saved_loop; + return true; +}); + +def_reduce_vars(AST_For, function(tw, descend, compressor) { + reset_block_variables(compressor, this); + if (this.init) this.init.walk(tw); + const saved_loop = tw.in_loop; + tw.in_loop = this; + push(tw); + if (this.condition) this.condition.walk(tw); + this.body.walk(tw); + if (this.step) { + if (has_break_or_continue(this)) { + pop(tw); + push(tw); + } + this.step.walk(tw); + } + pop(tw); + tw.in_loop = saved_loop; + return true; +}); + +def_reduce_vars(AST_ForIn, function(tw, descend, compressor) { + reset_block_variables(compressor, this); + suppress(this.init); + this.object.walk(tw); + const saved_loop = tw.in_loop; + tw.in_loop = this; + push(tw); + this.body.walk(tw); + pop(tw); + tw.in_loop = saved_loop; + return true; +}); + +def_reduce_vars(AST_If, function(tw) { + this.condition.walk(tw); + push(tw); + this.body.walk(tw); + pop(tw); + if (this.alternative) { + push(tw); + this.alternative.walk(tw); + pop(tw); + } + return true; +}); + +def_reduce_vars(AST_LabeledStatement, function(tw) { + push(tw); + this.body.walk(tw); + pop(tw); + return true; +}); + +def_reduce_vars(AST_SymbolCatch, function() { + this.definition().fixed = false; +}); + +def_reduce_vars(AST_SymbolRef, function(tw, descend, compressor) { + var d = this.definition(); + d.references.push(this); + if (d.references.length == 1 + && !d.fixed + && d.orig[0] instanceof AST_SymbolDefun) { + tw.loop_ids.set(d.id, tw.in_loop); + } + var fixed_value; + if (d.fixed === undefined || !safe_to_read(tw, d)) { + d.fixed = false; + } else if (d.fixed) { + fixed_value = this.fixed_value(); + if ( + fixed_value instanceof AST_Lambda + && is_recursive_ref(tw, d) + ) { + d.recursive_refs++; + } else if (fixed_value + && !compressor.exposed(d) + && ref_once(tw, compressor, d) + ) { + d.single_use = + fixed_value instanceof AST_Lambda && !fixed_value.pinned() + || fixed_value instanceof AST_Class + || d.scope === this.scope && fixed_value.is_constant_expression(); + } else { + d.single_use = false; + } + if (is_modified(compressor, tw, this, fixed_value, 0, is_immutable(fixed_value))) { + if (d.single_use) { + d.single_use = "m"; + } else { + d.fixed = false; + } + } + } + mark_escaped(tw, d, this.scope, this, fixed_value, 0, 1); +}); + +def_reduce_vars(AST_Toplevel, function(tw, descend, compressor) { + this.globals.forEach(function(def) { + reset_def(compressor, def); + }); + reset_variables(tw, compressor, this); + descend(); + handle_defined_after_hoist(this); + return true; +}); + +def_reduce_vars(AST_Try, function(tw, descend, compressor) { + reset_block_variables(compressor, this); + push(tw); + this.body.walk(tw); + pop(tw); + if (this.bcatch) { + push(tw); + this.bcatch.walk(tw); + pop(tw); + } + if (this.bfinally) this.bfinally.walk(tw); + return true; +}); + +def_reduce_vars(AST_Unary, function(tw) { + var node = this; + if (node.operator !== "++" && node.operator !== "--") return; + var exp = node.expression; + if (!(exp instanceof AST_SymbolRef)) return; + var def = exp.definition(); + var safe = safe_to_assign(tw, def, exp.scope, true); + def.assignments++; + if (!safe) return; + var fixed = def.fixed; + if (!fixed) return; + def.references.push(exp); + def.chained = true; + def.fixed = function() { + return make_node(AST_Binary, node, { + operator: node.operator.slice(0, -1), + left: make_node(AST_UnaryPrefix, node, { + operator: "+", + expression: fixed instanceof AST_Node ? fixed : fixed() + }), + right: make_node(AST_Number, node, { + value: 1 + }) + }); + }; + mark(tw, def, true); + return true; +}); + +def_reduce_vars(AST_VarDef, function(tw, descend) { + var node = this; + if (node.name instanceof AST_Destructuring) { + suppress(node.name); + return; + } + var d = node.name.definition(); + if (node.value) { + if (safe_to_assign(tw, d, node.name.scope, node.value)) { + d.fixed = function() { + return node.value; + }; + tw.loop_ids.set(d.id, tw.in_loop); + mark(tw, d, false); + descend(); + mark(tw, d, true); + return true; + } else { + d.fixed = false; + } + } +}); + +def_reduce_vars(AST_While, function(tw, descend, compressor) { + reset_block_variables(compressor, this); + const saved_loop = tw.in_loop; + tw.in_loop = this; + push(tw); + descend(); + pop(tw); + tw.in_loop = saved_loop; + return true; +}); diff --git a/node_modules/terser/lib/compress/tighten-body.js b/node_modules/terser/lib/compress/tighten-body.js new file mode 100644 index 0000000..4ff8f07 --- /dev/null +++ b/node_modules/terser/lib/compress/tighten-body.js @@ -0,0 +1,1516 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { + AST_Array, + AST_Arrow, + AST_Assign, + AST_Await, + AST_Binary, + AST_Block, + AST_BlockStatement, + AST_Break, + AST_Call, + AST_Case, + AST_Chain, + AST_Class, + AST_Conditional, + AST_Const, + AST_Constant, + AST_Continue, + AST_Debugger, + AST_Default, + AST_Definitions, + AST_Defun, + AST_Destructuring, + AST_Directive, + AST_Dot, + AST_DWLoop, + AST_EmptyStatement, + AST_Exit, + AST_Expansion, + AST_Export, + AST_For, + AST_ForIn, + AST_If, + AST_Import, + AST_IterationStatement, + AST_Lambda, + AST_Let, + AST_LoopControl, + AST_Node, + AST_Number, + AST_Object, + AST_ObjectKeyVal, + AST_ObjectProperty, + AST_PropAccess, + AST_RegExp, + AST_Return, + AST_Scope, + AST_Sequence, + AST_SimpleStatement, + AST_Sub, + AST_Switch, + AST_Symbol, + AST_SymbolConst, + AST_SymbolDeclaration, + AST_SymbolDefun, + AST_SymbolFunarg, + AST_SymbolLambda, + AST_SymbolLet, + AST_SymbolRef, + AST_SymbolVar, + AST_This, + AST_Try, + AST_TryBlock, + AST_Unary, + AST_UnaryPostfix, + AST_UnaryPrefix, + AST_Undefined, + AST_Var, + AST_VarDef, + AST_With, + AST_Yield, + + TreeTransformer, + TreeWalker, + walk, + walk_abort, + + _NOINLINE, +} from "../ast.js"; +import { + make_node, + MAP, + member, + remove, + has_annotation +} from "../utils/index.js"; + +import { pure_prop_access_globals } from "./native-objects.js"; +import { + lazy_op, + unary_side_effects, + is_modified, + is_lhs, + aborts +} from "./inference.js"; +import { WRITE_ONLY, clear_flag } from "./compressor-flags.js"; +import { + make_sequence, + merge_sequence, + maintain_this_binding, + is_func_expr, + is_identifier_atom, + is_ref_of, + can_be_evicted_from_block, + as_statement_array, +} from "./common.js"; + +function loop_body(x) { + if (x instanceof AST_IterationStatement) { + return x.body instanceof AST_BlockStatement ? x.body : x; + } + return x; +} + +function is_lhs_read_only(lhs) { + if (lhs instanceof AST_This) return true; + if (lhs instanceof AST_SymbolRef) return lhs.definition().orig[0] instanceof AST_SymbolLambda; + if (lhs instanceof AST_PropAccess) { + lhs = lhs.expression; + if (lhs instanceof AST_SymbolRef) { + if (lhs.is_immutable()) return false; + lhs = lhs.fixed_value(); + } + if (!lhs) return true; + if (lhs instanceof AST_RegExp) return false; + if (lhs instanceof AST_Constant) return true; + return is_lhs_read_only(lhs); + } + return false; +} + +/** var a = 1 --> var a*/ +function remove_initializers(var_statement) { + var decls = []; + var_statement.definitions.forEach(function(def) { + if (def.name instanceof AST_SymbolDeclaration) { + def.value = null; + decls.push(def); + } else { + def.declarations_as_names().forEach(name => { + decls.push(make_node(AST_VarDef, def, { + name, + value: null + })); + }); + } + }); + return decls.length ? make_node(AST_Var, var_statement, { definitions: decls }) : null; +} + +/** Called on code which we know is unreachable, to keep elements that affect outside of it. */ +export function trim_unreachable_code(compressor, stat, target) { + walk(stat, node => { + if (node instanceof AST_Var) { + const no_initializers = remove_initializers(node); + if (no_initializers) target.push(no_initializers); + return true; + } + if ( + node instanceof AST_Defun + && (node === stat || !compressor.has_directive("use strict")) + ) { + target.push(node === stat ? node : make_node(AST_Var, node, { + definitions: [ + make_node(AST_VarDef, node, { + name: make_node(AST_SymbolVar, node.name, node.name), + value: null + }) + ] + })); + return true; + } + if (node instanceof AST_Export || node instanceof AST_Import) { + target.push(node); + return true; + } + if (node instanceof AST_Scope) { + return true; + } + }); +} + +/** Tighten a bunch of statements together, and perform statement-level optimization. */ +export function tighten_body(statements, compressor) { + const nearest_scope = compressor.find_scope(); + const defun_scope = nearest_scope.get_defun_scope(); + const { in_loop, in_try } = find_loop_scope_try(); + + var CHANGED, max_iter = 10; + do { + CHANGED = false; + eliminate_spurious_blocks(statements); + if (compressor.option("dead_code")) { + eliminate_dead_code(statements, compressor); + } + if (compressor.option("if_return")) { + handle_if_return(statements, compressor); + } + if (compressor.sequences_limit > 0) { + sequencesize(statements, compressor); + sequencesize_2(statements, compressor); + } + if (compressor.option("join_vars")) { + join_consecutive_vars(statements); + } + if (compressor.option("collapse_vars")) { + collapse(statements, compressor); + } + } while (CHANGED && max_iter-- > 0); + + function find_loop_scope_try() { + var node = compressor.self(), level = 0, in_loop = false, in_try = false; + do { + if (node instanceof AST_IterationStatement) { + in_loop = true; + } else if (node instanceof AST_Scope) { + break; + } else if (node instanceof AST_TryBlock) { + in_try = true; + } + } while (node = compressor.parent(level++)); + + return { in_loop, in_try }; + } + + // Search from right to left for assignment-like expressions: + // - `var a = x;` + // - `a = x;` + // - `++a` + // For each candidate, scan from left to right for first usage, then try + // to fold assignment into the site for compression. + // Will not attempt to collapse assignments into or past code blocks + // which are not sequentially executed, e.g. loops and conditionals. + function collapse(statements, compressor) { + if (nearest_scope.pinned() || defun_scope.pinned()) + return statements; + var args; + var candidates = []; + var stat_index = statements.length; + var scanner = new TreeTransformer(function (node) { + if (abort) + return node; + // Skip nodes before `candidate` as quickly as possible + if (!hit) { + if (node !== hit_stack[hit_index]) + return node; + hit_index++; + if (hit_index < hit_stack.length) + return handle_custom_scan_order(node); + hit = true; + stop_after = find_stop(node, 0); + if (stop_after === node) + abort = true; + return node; + } + // Stop immediately if these node types are encountered + var parent = scanner.parent(); + if (node instanceof AST_Assign + && (node.logical || node.operator != "=" && lhs.equivalent_to(node.left)) + || node instanceof AST_Await + || node instanceof AST_Call && lhs instanceof AST_PropAccess && lhs.equivalent_to(node.expression) + || + (node instanceof AST_Call || node instanceof AST_PropAccess) + && node.optional + || node instanceof AST_Debugger + || node instanceof AST_Destructuring + || node instanceof AST_Expansion + && node.expression instanceof AST_Symbol + && ( + node.expression instanceof AST_This + || node.expression.definition().references.length > 1 + ) + || node instanceof AST_IterationStatement && !(node instanceof AST_For) + || node instanceof AST_LoopControl + || node instanceof AST_Try + || node instanceof AST_With + || node instanceof AST_Yield + || node instanceof AST_Export + || node instanceof AST_Class + || parent instanceof AST_For && node !== parent.init + || !replace_all + && ( + node instanceof AST_SymbolRef + && !node.is_declared(compressor) + && !pure_prop_access_globals.has(node) + ) + || node instanceof AST_SymbolRef + && parent instanceof AST_Call + && has_annotation(parent, _NOINLINE) + || node instanceof AST_ObjectProperty && node.key instanceof AST_Node + ) { + abort = true; + return node; + } + // Stop only if candidate is found within conditional branches + if (!stop_if_hit && (!lhs_local || !replace_all) + && (parent instanceof AST_Binary && lazy_op.has(parent.operator) && parent.left !== node + || parent instanceof AST_Conditional && parent.condition !== node + || parent instanceof AST_If && parent.condition !== node)) { + stop_if_hit = parent; + } + // Replace variable with assignment when found + if ( + can_replace + && !(node instanceof AST_SymbolDeclaration) + && lhs.equivalent_to(node) + && !shadows(scanner.find_scope() || nearest_scope, lvalues) + ) { + if (stop_if_hit) { + abort = true; + return node; + } + if (is_lhs(node, parent)) { + if (value_def) + replaced++; + return node; + } else { + replaced++; + if (value_def && candidate instanceof AST_VarDef) + return node; + } + CHANGED = abort = true; + if (candidate instanceof AST_UnaryPostfix) { + return make_node(AST_UnaryPrefix, candidate, candidate); + } + if (candidate instanceof AST_VarDef) { + var def = candidate.name.definition(); + var value = candidate.value; + if (def.references.length - def.replaced == 1 && !compressor.exposed(def)) { + def.replaced++; + if (funarg && is_identifier_atom(value)) { + return value.transform(compressor); + } else { + return maintain_this_binding(parent, node, value); + } + } + return make_node(AST_Assign, candidate, { + operator: "=", + logical: false, + left: make_node(AST_SymbolRef, candidate.name, candidate.name), + right: value + }); + } + clear_flag(candidate, WRITE_ONLY); + return candidate; + } + // These node types have child nodes that execute sequentially, + // but are otherwise not safe to scan into or beyond them. + var sym; + if (node instanceof AST_Call + || node instanceof AST_Exit + && (side_effects || lhs instanceof AST_PropAccess || may_modify(lhs)) + || node instanceof AST_PropAccess + && (side_effects || node.expression.may_throw_on_access(compressor)) + || node instanceof AST_SymbolRef + && ((lvalues.has(node.name) && lvalues.get(node.name).modified) || side_effects && may_modify(node)) + || node instanceof AST_VarDef && node.value + && (lvalues.has(node.name.name) || side_effects && may_modify(node.name)) + || (sym = is_lhs(node.left, node)) + && (sym instanceof AST_PropAccess || lvalues.has(sym.name)) + || may_throw + && (in_try ? node.has_side_effects(compressor) : side_effects_external(node))) { + stop_after = node; + if (node instanceof AST_Scope) + abort = true; + } + return handle_custom_scan_order(node); + }, function (node) { + if (abort) + return; + if (stop_after === node) + abort = true; + if (stop_if_hit === node) + stop_if_hit = null; + }); + + var multi_replacer = new TreeTransformer(function (node) { + if (abort) + return node; + // Skip nodes before `candidate` as quickly as possible + if (!hit) { + if (node !== hit_stack[hit_index]) + return node; + hit_index++; + if (hit_index < hit_stack.length) + return; + hit = true; + return node; + } + // Replace variable when found + if (node instanceof AST_SymbolRef + && node.name == def.name) { + if (!--replaced) + abort = true; + if (is_lhs(node, multi_replacer.parent())) + return node; + def.replaced++; + value_def.replaced--; + return candidate.value; + } + // Skip (non-executed) functions and (leading) default case in switch statements + if (node instanceof AST_Default || node instanceof AST_Scope) + return node; + }); + + while (--stat_index >= 0) { + // Treat parameters as collapsible in IIFE, i.e. + // function(a, b){ ... }(x()); + // would be translated into equivalent assignments: + // var a = x(), b = undefined; + if (stat_index == 0 && compressor.option("unused")) + extract_args(); + // Find collapsible assignments + var hit_stack = []; + extract_candidates(statements[stat_index]); + while (candidates.length > 0) { + hit_stack = candidates.pop(); + var hit_index = 0; + var candidate = hit_stack[hit_stack.length - 1]; + var value_def = null; + var stop_after = null; + var stop_if_hit = null; + var lhs = get_lhs(candidate); + if (!lhs || is_lhs_read_only(lhs) || lhs.has_side_effects(compressor)) + continue; + // Locate symbols which may execute code outside of scanning range + var lvalues = get_lvalues(candidate); + var lhs_local = is_lhs_local(lhs); + if (lhs instanceof AST_SymbolRef) { + lvalues.set(lhs.name, { def: lhs.definition(), modified: false }); + } + var side_effects = value_has_side_effects(candidate); + var replace_all = replace_all_symbols(); + var may_throw = candidate.may_throw(compressor); + var funarg = candidate.name instanceof AST_SymbolFunarg; + var hit = funarg; + var abort = false, replaced = 0, can_replace = !args || !hit; + if (!can_replace) { + for ( + let j = compressor.self().argnames.lastIndexOf(candidate.name) + 1; + !abort && j < args.length; + j++ + ) { + args[j].transform(scanner); + } + can_replace = true; + } + for (var i = stat_index; !abort && i < statements.length; i++) { + statements[i].transform(scanner); + } + if (value_def) { + var def = candidate.name.definition(); + if (abort && def.references.length - def.replaced > replaced) + replaced = false; + else { + abort = false; + hit_index = 0; + hit = funarg; + for (var i = stat_index; !abort && i < statements.length; i++) { + statements[i].transform(multi_replacer); + } + value_def.single_use = false; + } + } + if (replaced && !remove_candidate(candidate)) + statements.splice(stat_index, 1); + } + } + + function handle_custom_scan_order(node) { + // Skip (non-executed) functions + if (node instanceof AST_Scope) + return node; + + // Scan case expressions first in a switch statement + if (node instanceof AST_Switch) { + node.expression = node.expression.transform(scanner); + for (var i = 0, len = node.body.length; !abort && i < len; i++) { + var branch = node.body[i]; + if (branch instanceof AST_Case) { + if (!hit) { + if (branch !== hit_stack[hit_index]) + continue; + hit_index++; + } + branch.expression = branch.expression.transform(scanner); + if (!replace_all) + break; + } + } + abort = true; + return node; + } + } + + function redefined_within_scope(def, scope) { + if (def.global) + return false; + let cur_scope = def.scope; + while (cur_scope && cur_scope !== scope) { + if (cur_scope.variables.has(def.name)) { + return true; + } + cur_scope = cur_scope.parent_scope; + } + return false; + } + + function has_overlapping_symbol(fn, arg, fn_strict) { + var found = false, scan_this = !(fn instanceof AST_Arrow); + arg.walk(new TreeWalker(function (node, descend) { + if (found) + return true; + if (node instanceof AST_SymbolRef && (fn.variables.has(node.name) || redefined_within_scope(node.definition(), fn))) { + var s = node.definition().scope; + if (s !== defun_scope) + while (s = s.parent_scope) { + if (s === defun_scope) + return true; + } + return found = true; + } + if ((fn_strict || scan_this) && node instanceof AST_This) { + return found = true; + } + if (node instanceof AST_Scope && !(node instanceof AST_Arrow)) { + var prev = scan_this; + scan_this = false; + descend(); + scan_this = prev; + return true; + } + })); + return found; + } + + function arg_is_injectable(arg) { + if (arg instanceof AST_Expansion) return false; + const contains_await = walk(arg, (node) => { + if (node instanceof AST_Await) return walk_abort; + }); + if (contains_await) return false; + return true; + } + function extract_args() { + var iife, fn = compressor.self(); + if (is_func_expr(fn) + && !fn.name + && !fn.uses_arguments + && !fn.pinned() + && (iife = compressor.parent()) instanceof AST_Call + && iife.expression === fn + && iife.args.every(arg_is_injectable) + ) { + var fn_strict = compressor.has_directive("use strict"); + if (fn_strict && !member(fn_strict, fn.body)) + fn_strict = false; + var len = fn.argnames.length; + args = iife.args.slice(len); + var names = new Set(); + for (var i = len; --i >= 0;) { + var sym = fn.argnames[i]; + var arg = iife.args[i]; + // The following two line fix is a duplicate of the fix at + // https://github.com/terser/terser/commit/011d3eb08cefe6922c7d1bdfa113fc4aeaca1b75 + // This might mean that these two pieces of code (one here in collapse_vars and another in reduce_vars + // Might be doing the exact same thing. + const def = sym.definition && sym.definition(); + const is_reassigned = def && def.orig.length > 1; + if (is_reassigned) + continue; + args.unshift(make_node(AST_VarDef, sym, { + name: sym, + value: arg + })); + if (names.has(sym.name)) + continue; + names.add(sym.name); + if (sym instanceof AST_Expansion) { + var elements = iife.args.slice(i); + if (elements.every((arg) => !has_overlapping_symbol(fn, arg, fn_strict) + )) { + candidates.unshift([make_node(AST_VarDef, sym, { + name: sym.expression, + value: make_node(AST_Array, iife, { + elements: elements + }) + })]); + } + } else { + if (!arg) { + arg = make_node(AST_Undefined, sym).transform(compressor); + } else if (arg instanceof AST_Lambda && arg.pinned() + || has_overlapping_symbol(fn, arg, fn_strict)) { + arg = null; + } + if (arg) + candidates.unshift([make_node(AST_VarDef, sym, { + name: sym, + value: arg + })]); + } + } + } + } + + function extract_candidates(expr) { + hit_stack.push(expr); + if (expr instanceof AST_Assign) { + if (!expr.left.has_side_effects(compressor) + && !(expr.right instanceof AST_Chain)) { + candidates.push(hit_stack.slice()); + } + extract_candidates(expr.right); + } else if (expr instanceof AST_Binary) { + extract_candidates(expr.left); + extract_candidates(expr.right); + } else if (expr instanceof AST_Call && !has_annotation(expr, _NOINLINE)) { + extract_candidates(expr.expression); + expr.args.forEach(extract_candidates); + } else if (expr instanceof AST_Case) { + extract_candidates(expr.expression); + } else if (expr instanceof AST_Conditional) { + extract_candidates(expr.condition); + extract_candidates(expr.consequent); + extract_candidates(expr.alternative); + } else if (expr instanceof AST_Definitions) { + var len = expr.definitions.length; + // limit number of trailing variable definitions for consideration + var i = len - 200; + if (i < 0) + i = 0; + for (; i < len; i++) { + extract_candidates(expr.definitions[i]); + } + } else if (expr instanceof AST_DWLoop) { + extract_candidates(expr.condition); + if (!(expr.body instanceof AST_Block)) { + extract_candidates(expr.body); + } + } else if (expr instanceof AST_Exit) { + if (expr.value) + extract_candidates(expr.value); + } else if (expr instanceof AST_For) { + if (expr.init) + extract_candidates(expr.init); + if (expr.condition) + extract_candidates(expr.condition); + if (expr.step) + extract_candidates(expr.step); + if (!(expr.body instanceof AST_Block)) { + extract_candidates(expr.body); + } + } else if (expr instanceof AST_ForIn) { + extract_candidates(expr.object); + if (!(expr.body instanceof AST_Block)) { + extract_candidates(expr.body); + } + } else if (expr instanceof AST_If) { + extract_candidates(expr.condition); + if (!(expr.body instanceof AST_Block)) { + extract_candidates(expr.body); + } + if (expr.alternative && !(expr.alternative instanceof AST_Block)) { + extract_candidates(expr.alternative); + } + } else if (expr instanceof AST_Sequence) { + expr.expressions.forEach(extract_candidates); + } else if (expr instanceof AST_SimpleStatement) { + extract_candidates(expr.body); + } else if (expr instanceof AST_Switch) { + extract_candidates(expr.expression); + expr.body.forEach(extract_candidates); + } else if (expr instanceof AST_Unary) { + if (expr.operator == "++" || expr.operator == "--") { + candidates.push(hit_stack.slice()); + } + } else if (expr instanceof AST_VarDef) { + if (expr.value && !(expr.value instanceof AST_Chain)) { + candidates.push(hit_stack.slice()); + extract_candidates(expr.value); + } + } + hit_stack.pop(); + } + + function find_stop(node, level, write_only) { + var parent = scanner.parent(level); + if (parent instanceof AST_Assign) { + if (write_only + && !parent.logical + && !(parent.left instanceof AST_PropAccess + || lvalues.has(parent.left.name))) { + return find_stop(parent, level + 1, write_only); + } + return node; + } + if (parent instanceof AST_Binary) { + if (write_only && (!lazy_op.has(parent.operator) || parent.left === node)) { + return find_stop(parent, level + 1, write_only); + } + return node; + } + if (parent instanceof AST_Call) + return node; + if (parent instanceof AST_Case) + return node; + if (parent instanceof AST_Conditional) { + if (write_only && parent.condition === node) { + return find_stop(parent, level + 1, write_only); + } + return node; + } + if (parent instanceof AST_Definitions) { + return find_stop(parent, level + 1, true); + } + if (parent instanceof AST_Exit) { + return write_only ? find_stop(parent, level + 1, write_only) : node; + } + if (parent instanceof AST_If) { + if (write_only && parent.condition === node) { + return find_stop(parent, level + 1, write_only); + } + return node; + } + if (parent instanceof AST_IterationStatement) + return node; + if (parent instanceof AST_Sequence) { + return find_stop(parent, level + 1, parent.tail_node() !== node); + } + if (parent instanceof AST_SimpleStatement) { + return find_stop(parent, level + 1, true); + } + if (parent instanceof AST_Switch) + return node; + if (parent instanceof AST_VarDef) + return node; + return null; + } + + function mangleable_var(var_def) { + var value = var_def.value; + if (!(value instanceof AST_SymbolRef)) + return; + if (value.name == "arguments") + return; + var def = value.definition(); + if (def.undeclared) + return; + return value_def = def; + } + + function get_lhs(expr) { + if (expr instanceof AST_Assign && expr.logical) { + return false; + } else if (expr instanceof AST_VarDef && expr.name instanceof AST_SymbolDeclaration) { + var def = expr.name.definition(); + if (!member(expr.name, def.orig)) + return; + var referenced = def.references.length - def.replaced; + if (!referenced) + return; + var declared = def.orig.length - def.eliminated; + if (declared > 1 && !(expr.name instanceof AST_SymbolFunarg) + || (referenced > 1 ? mangleable_var(expr) : !compressor.exposed(def))) { + return make_node(AST_SymbolRef, expr.name, expr.name); + } + } else { + const lhs = expr instanceof AST_Assign + ? expr.left + : expr.expression; + return !is_ref_of(lhs, AST_SymbolConst) + && !is_ref_of(lhs, AST_SymbolLet) && lhs; + } + } + + function get_rvalue(expr) { + if (expr instanceof AST_Assign) { + return expr.right; + } else { + return expr.value; + } + } + + function get_lvalues(expr) { + var lvalues = new Map(); + if (expr instanceof AST_Unary) + return lvalues; + var tw = new TreeWalker(function (node) { + var sym = node; + while (sym instanceof AST_PropAccess) + sym = sym.expression; + if (sym instanceof AST_SymbolRef) { + const prev = lvalues.get(sym.name); + if (!prev || !prev.modified) { + lvalues.set(sym.name, { + def: sym.definition(), + modified: is_modified(compressor, tw, node, node, 0) + }); + } + } + }); + get_rvalue(expr).walk(tw); + return lvalues; + } + + function remove_candidate(expr) { + if (expr.name instanceof AST_SymbolFunarg) { + var iife = compressor.parent(), argnames = compressor.self().argnames; + var index = argnames.indexOf(expr.name); + if (index < 0) { + iife.args.length = Math.min(iife.args.length, argnames.length - 1); + } else { + var args = iife.args; + if (args[index]) + args[index] = make_node(AST_Number, args[index], { + value: 0 + }); + } + return true; + } + var found = false; + return statements[stat_index].transform(new TreeTransformer(function (node, descend, in_list) { + if (found) + return node; + if (node === expr || node.body === expr) { + found = true; + if (node instanceof AST_VarDef) { + node.value = node.name instanceof AST_SymbolConst + ? make_node(AST_Undefined, node.value) // `const` always needs value. + : null; + return node; + } + return in_list ? MAP.skip : null; + } + }, function (node) { + if (node instanceof AST_Sequence) + switch (node.expressions.length) { + case 0: return null; + case 1: return node.expressions[0]; + } + })); + } + + function is_lhs_local(lhs) { + while (lhs instanceof AST_PropAccess) + lhs = lhs.expression; + return lhs instanceof AST_SymbolRef + && lhs.definition().scope.get_defun_scope() === defun_scope + && !(in_loop + && (lvalues.has(lhs.name) + || candidate instanceof AST_Unary + || (candidate instanceof AST_Assign + && !candidate.logical + && candidate.operator != "="))); + } + + function value_has_side_effects(expr) { + if (expr instanceof AST_Unary) + return unary_side_effects.has(expr.operator); + return get_rvalue(expr).has_side_effects(compressor); + } + + function replace_all_symbols() { + if (side_effects) + return false; + if (value_def) + return true; + if (lhs instanceof AST_SymbolRef) { + var def = lhs.definition(); + if (def.references.length - def.replaced == (candidate instanceof AST_VarDef ? 1 : 2)) { + return true; + } + } + return false; + } + + function may_modify(sym) { + if (!sym.definition) + return true; // AST_Destructuring + var def = sym.definition(); + if (def.orig.length == 1 && def.orig[0] instanceof AST_SymbolDefun) + return false; + if (def.scope.get_defun_scope() !== defun_scope) + return true; + return def.references.some((ref) => + ref.scope.get_defun_scope() !== defun_scope + ); + } + + function side_effects_external(node, lhs) { + if (node instanceof AST_Assign) + return side_effects_external(node.left, true); + if (node instanceof AST_Unary) + return side_effects_external(node.expression, true); + if (node instanceof AST_VarDef) + return node.value && side_effects_external(node.value); + if (lhs) { + if (node instanceof AST_Dot) + return side_effects_external(node.expression, true); + if (node instanceof AST_Sub) + return side_effects_external(node.expression, true); + if (node instanceof AST_SymbolRef) + return node.definition().scope.get_defun_scope() !== defun_scope; + } + return false; + } + + /** + * Will any of the pulled-in lvalues shadow a variable in newScope or parents? + * similar to scope_encloses_variables_in_this_scope */ + function shadows(my_scope, lvalues) { + for (const { def } of lvalues.values()) { + const looked_up = my_scope.find_variable(def.name); + if (looked_up) { + if (looked_up === def) continue; + return true; + } + } + return false; + } + } + + function eliminate_spurious_blocks(statements) { + var seen_dirs = []; + for (var i = 0; i < statements.length;) { + var stat = statements[i]; + if (stat instanceof AST_BlockStatement && stat.body.every(can_be_evicted_from_block)) { + CHANGED = true; + eliminate_spurious_blocks(stat.body); + statements.splice(i, 1, ...stat.body); + i += stat.body.length; + } else if (stat instanceof AST_EmptyStatement) { + CHANGED = true; + statements.splice(i, 1); + } else if (stat instanceof AST_Directive) { + if (seen_dirs.indexOf(stat.value) < 0) { + i++; + seen_dirs.push(stat.value); + } else { + CHANGED = true; + statements.splice(i, 1); + } + } else + i++; + } + } + + function handle_if_return(statements, compressor) { + var self = compressor.self(); + var multiple_if_returns = has_multiple_if_returns(statements); + var in_lambda = self instanceof AST_Lambda; + // Prevent extremely deep nesting + // https://github.com/terser/terser/issues/1432 + // https://github.com/webpack/webpack/issues/17548 + const iteration_start = Math.min(statements.length, 500); + for (var i = iteration_start; --i >= 0;) { + var stat = statements[i]; + var j = next_index(i); + var next = statements[j]; + + if (in_lambda && !next && stat instanceof AST_Return) { + if (!stat.value) { + CHANGED = true; + statements.splice(i, 1); + continue; + } + if (stat.value instanceof AST_UnaryPrefix && stat.value.operator == "void") { + CHANGED = true; + statements[i] = make_node(AST_SimpleStatement, stat, { + body: stat.value.expression + }); + continue; + } + } + + if (stat instanceof AST_If) { + let ab, new_else; + + ab = aborts(stat.body); + if ( + can_merge_flow(ab) + && (new_else = as_statement_array_with_return(stat.body, ab)) + ) { + if (ab.label) { + remove(ab.label.thedef.references, ab); + } + CHANGED = true; + stat = stat.clone(); + stat.condition = stat.condition.negate(compressor); + stat.body = make_node(AST_BlockStatement, stat, { + body: as_statement_array(stat.alternative).concat(extract_functions()) + }); + stat.alternative = make_node(AST_BlockStatement, stat, { + body: new_else + }); + statements[i] = stat.transform(compressor); + continue; + } + + ab = aborts(stat.alternative); + if ( + can_merge_flow(ab) + && (new_else = as_statement_array_with_return(stat.alternative, ab)) + ) { + if (ab.label) { + remove(ab.label.thedef.references, ab); + } + CHANGED = true; + stat = stat.clone(); + stat.body = make_node(AST_BlockStatement, stat.body, { + body: as_statement_array(stat.body).concat(extract_functions()) + }); + stat.alternative = make_node(AST_BlockStatement, stat.alternative, { + body: new_else + }); + statements[i] = stat.transform(compressor); + continue; + } + } + + if (stat instanceof AST_If && stat.body instanceof AST_Return) { + var value = stat.body.value; + //--- + // pretty silly case, but: + // if (foo()) return; return; ==> foo(); return; + if (!value && !stat.alternative + && (in_lambda && !next || next instanceof AST_Return && !next.value)) { + CHANGED = true; + statements[i] = make_node(AST_SimpleStatement, stat.condition, { + body: stat.condition + }); + continue; + } + //--- + // if (foo()) return x; return y; ==> return foo() ? x : y; + if (value && !stat.alternative && next instanceof AST_Return && next.value) { + CHANGED = true; + stat = stat.clone(); + stat.alternative = next; + statements[i] = stat.transform(compressor); + statements.splice(j, 1); + continue; + } + //--- + // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined; + if (value && !stat.alternative + && (!next && in_lambda && multiple_if_returns + || next instanceof AST_Return)) { + CHANGED = true; + stat = stat.clone(); + stat.alternative = next || make_node(AST_Return, stat, { + value: null + }); + statements[i] = stat.transform(compressor); + if (next) + statements.splice(j, 1); + continue; + } + //--- + // if (a) return b; if (c) return d; e; ==> return a ? b : c ? d : void e; + // + // if sequences is not enabled, this can lead to an endless loop (issue #866). + // however, with sequences on this helps producing slightly better output for + // the example code. + var prev = statements[prev_index(i)]; + if (compressor.option("sequences") && in_lambda && !stat.alternative + && prev instanceof AST_If && prev.body instanceof AST_Return + && next_index(j) == statements.length && next instanceof AST_SimpleStatement) { + CHANGED = true; + stat = stat.clone(); + stat.alternative = make_node(AST_BlockStatement, next, { + body: [ + next, + make_node(AST_Return, next, { + value: null + }) + ] + }); + statements[i] = stat.transform(compressor); + statements.splice(j, 1); + continue; + } + } + } + + function has_multiple_if_returns(statements) { + var n = 0; + for (var i = statements.length; --i >= 0;) { + var stat = statements[i]; + if (stat instanceof AST_If && stat.body instanceof AST_Return) { + if (++n > 1) + return true; + } + } + return false; + } + + function is_return_void(value) { + return !value || value instanceof AST_UnaryPrefix && value.operator == "void"; + } + + function can_merge_flow(ab) { + if (!ab) + return false; + for (var j = i + 1, len = statements.length; j < len; j++) { + var stat = statements[j]; + if (stat instanceof AST_Const || stat instanceof AST_Let) + return false; + } + var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab) : null; + return ab instanceof AST_Return && in_lambda && is_return_void(ab.value) + || ab instanceof AST_Continue && self === loop_body(lct) + || ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct; + } + + function extract_functions() { + var tail = statements.slice(i + 1); + statements.length = i + 1; + return tail.filter(function (stat) { + if (stat instanceof AST_Defun) { + statements.push(stat); + return false; + } + return true; + }); + } + + function as_statement_array_with_return(node, ab) { + var body = as_statement_array(node); + if (ab !== body[body.length - 1]) { + return undefined; + } + body = body.slice(0, -1); + if (ab.value) { + body.push(make_node(AST_SimpleStatement, ab.value, { + body: ab.value.expression + })); + } + return body; + } + + function next_index(i) { + for (var j = i + 1, len = statements.length; j < len; j++) { + var stat = statements[j]; + if (!(stat instanceof AST_Var && declarations_only(stat))) { + break; + } + } + return j; + } + + function prev_index(i) { + for (var j = i; --j >= 0;) { + var stat = statements[j]; + if (!(stat instanceof AST_Var && declarations_only(stat))) { + break; + } + } + return j; + } + } + + function eliminate_dead_code(statements, compressor) { + var has_quit; + var self = compressor.self(); + for (var i = 0, n = 0, len = statements.length; i < len; i++) { + var stat = statements[i]; + if (stat instanceof AST_LoopControl) { + var lct = compressor.loopcontrol_target(stat); + if (stat instanceof AST_Break + && !(lct instanceof AST_IterationStatement) + && loop_body(lct) === self + || stat instanceof AST_Continue + && loop_body(lct) === self) { + if (stat.label) { + remove(stat.label.thedef.references, stat); + } + } else { + statements[n++] = stat; + } + } else { + statements[n++] = stat; + } + if (aborts(stat)) { + has_quit = statements.slice(i + 1); + break; + } + } + statements.length = n; + CHANGED = n != len; + if (has_quit) + has_quit.forEach(function (stat) { + trim_unreachable_code(compressor, stat, statements); + }); + } + + function declarations_only(node) { + return node.definitions.every((var_def) => !var_def.value); + } + + function sequencesize(statements, compressor) { + if (statements.length < 2) + return; + var seq = [], n = 0; + function push_seq() { + if (!seq.length) + return; + var body = make_sequence(seq[0], seq); + statements[n++] = make_node(AST_SimpleStatement, body, { body: body }); + seq = []; + } + for (var i = 0, len = statements.length; i < len; i++) { + var stat = statements[i]; + if (stat instanceof AST_SimpleStatement) { + if (seq.length >= compressor.sequences_limit) + push_seq(); + var body = stat.body; + if (seq.length > 0) + body = body.drop_side_effect_free(compressor); + if (body) + merge_sequence(seq, body); + } else if (stat instanceof AST_Definitions && declarations_only(stat) + || stat instanceof AST_Defun) { + statements[n++] = stat; + } else { + push_seq(); + statements[n++] = stat; + } + } + push_seq(); + statements.length = n; + if (n != len) + CHANGED = true; + } + + function to_simple_statement(block, decls) { + if (!(block instanceof AST_BlockStatement)) + return block; + var stat = null; + for (var i = 0, len = block.body.length; i < len; i++) { + var line = block.body[i]; + if (line instanceof AST_Var && declarations_only(line)) { + decls.push(line); + } else if (stat || line instanceof AST_Const || line instanceof AST_Let) { + return false; + } else { + stat = line; + } + } + return stat; + } + + function sequencesize_2(statements, compressor) { + function cons_seq(right) { + n--; + CHANGED = true; + var left = prev.body; + return make_sequence(left, [left, right]).transform(compressor); + } + var n = 0, prev; + for (var i = 0; i < statements.length; i++) { + var stat = statements[i]; + if (prev) { + if (stat instanceof AST_Exit) { + stat.value = cons_seq(stat.value || make_node(AST_Undefined, stat).transform(compressor)); + } else if (stat instanceof AST_For) { + if (!(stat.init instanceof AST_Definitions)) { + const abort = walk(prev.body, node => { + if (node instanceof AST_Scope) + return true; + if (node instanceof AST_Binary + && node.operator === "in") { + return walk_abort; + } + }); + if (!abort) { + if (stat.init) + stat.init = cons_seq(stat.init); + else { + stat.init = prev.body; + n--; + CHANGED = true; + } + } + } + } else if (stat instanceof AST_ForIn) { + if (!(stat.init instanceof AST_Const) && !(stat.init instanceof AST_Let)) { + stat.object = cons_seq(stat.object); + } + } else if (stat instanceof AST_If) { + stat.condition = cons_seq(stat.condition); + } else if (stat instanceof AST_Switch) { + stat.expression = cons_seq(stat.expression); + } else if (stat instanceof AST_With) { + stat.expression = cons_seq(stat.expression); + } + } + if (compressor.option("conditionals") && stat instanceof AST_If) { + var decls = []; + var body = to_simple_statement(stat.body, decls); + var alt = to_simple_statement(stat.alternative, decls); + if (body !== false && alt !== false && decls.length > 0) { + var len = decls.length; + decls.push(make_node(AST_If, stat, { + condition: stat.condition, + body: body || make_node(AST_EmptyStatement, stat.body), + alternative: alt + })); + decls.unshift(n, 1); + [].splice.apply(statements, decls); + i += len; + n += len + 1; + prev = null; + CHANGED = true; + continue; + } + } + statements[n++] = stat; + prev = stat instanceof AST_SimpleStatement ? stat : null; + } + statements.length = n; + } + + function join_object_assignments(defn, body) { + if (!(defn instanceof AST_Definitions)) + return; + var def = defn.definitions[defn.definitions.length - 1]; + if (!(def.value instanceof AST_Object)) + return; + var exprs; + if (body instanceof AST_Assign && !body.logical) { + exprs = [body]; + } else if (body instanceof AST_Sequence) { + exprs = body.expressions.slice(); + } + if (!exprs) + return; + var trimmed = false; + do { + var node = exprs[0]; + if (!(node instanceof AST_Assign)) + break; + if (node.operator != "=") + break; + if (!(node.left instanceof AST_PropAccess)) + break; + var sym = node.left.expression; + if (!(sym instanceof AST_SymbolRef)) + break; + if (def.name.name != sym.name) + break; + if (!node.right.is_constant_expression(nearest_scope)) + break; + var prop = node.left.property; + if (prop instanceof AST_Node) { + prop = prop.evaluate(compressor); + } + if (prop instanceof AST_Node) + break; + prop = "" + prop; + var diff = compressor.option("ecma") < 2015 + && compressor.has_directive("use strict") ? function (node) { + return node.key != prop && (node.key && node.key.name != prop); + } : function (node) { + return node.key && node.key.name != prop; + }; + if (!def.value.properties.every(diff)) + break; + var p = def.value.properties.filter(function (p) { return p.key === prop; })[0]; + if (!p) { + def.value.properties.push(make_node(AST_ObjectKeyVal, node, { + key: prop, + value: node.right + })); + } else { + p.value = new AST_Sequence({ + start: p.start, + expressions: [p.value.clone(), node.right.clone()], + end: p.end + }); + } + exprs.shift(); + trimmed = true; + } while (exprs.length); + return trimmed && exprs; + } + + function join_consecutive_vars(statements) { + var defs; + for (var i = 0, j = -1, len = statements.length; i < len; i++) { + var stat = statements[i]; + var prev = statements[j]; + if (stat instanceof AST_Definitions) { + if (prev && prev.TYPE == stat.TYPE) { + prev.definitions = prev.definitions.concat(stat.definitions); + CHANGED = true; + } else if (defs && defs.TYPE == stat.TYPE && declarations_only(stat)) { + defs.definitions = defs.definitions.concat(stat.definitions); + CHANGED = true; + } else { + statements[++j] = stat; + defs = stat; + } + } else if (stat instanceof AST_Exit) { + stat.value = extract_object_assignments(stat.value); + } else if (stat instanceof AST_For) { + var exprs = join_object_assignments(prev, stat.init); + if (exprs) { + CHANGED = true; + stat.init = exprs.length ? make_sequence(stat.init, exprs) : null; + statements[++j] = stat; + } else if ( + prev instanceof AST_Var + && (!stat.init || stat.init.TYPE == prev.TYPE) + ) { + if (stat.init) { + prev.definitions = prev.definitions.concat(stat.init.definitions); + } + stat.init = prev; + statements[j] = stat; + CHANGED = true; + } else if ( + defs instanceof AST_Var + && stat.init instanceof AST_Var + && declarations_only(stat.init) + ) { + defs.definitions = defs.definitions.concat(stat.init.definitions); + stat.init = null; + statements[++j] = stat; + CHANGED = true; + } else { + statements[++j] = stat; + } + } else if (stat instanceof AST_ForIn) { + stat.object = extract_object_assignments(stat.object); + } else if (stat instanceof AST_If) { + stat.condition = extract_object_assignments(stat.condition); + } else if (stat instanceof AST_SimpleStatement) { + var exprs = join_object_assignments(prev, stat.body); + if (exprs) { + CHANGED = true; + if (!exprs.length) + continue; + stat.body = make_sequence(stat.body, exprs); + } + statements[++j] = stat; + } else if (stat instanceof AST_Switch) { + stat.expression = extract_object_assignments(stat.expression); + } else if (stat instanceof AST_With) { + stat.expression = extract_object_assignments(stat.expression); + } else { + statements[++j] = stat; + } + } + statements.length = j + 1; + + function extract_object_assignments(value) { + statements[++j] = stat; + var exprs = join_object_assignments(prev, value); + if (exprs) { + CHANGED = true; + if (exprs.length) { + return make_sequence(value, exprs); + } else if (value instanceof AST_Sequence) { + return value.tail_node().left; + } else { + return value.left; + } + } + return value; + } + } +} diff --git a/node_modules/terser/lib/equivalent-to.js b/node_modules/terser/lib/equivalent-to.js new file mode 100644 index 0000000..3359615 --- /dev/null +++ b/node_modules/terser/lib/equivalent-to.js @@ -0,0 +1,287 @@ +import { + AST_Array, + AST_Atom, + AST_Await, + AST_BigInt, + AST_Binary, + AST_Block, + AST_Call, + AST_Catch, + AST_Chain, + AST_Class, + AST_ClassProperty, + AST_ConciseMethod, + AST_Conditional, + AST_Debugger, + AST_Definitions, + AST_Destructuring, + AST_Directive, + AST_Do, + AST_Dot, + AST_DotHash, + AST_EmptyStatement, + AST_Expansion, + AST_Export, + AST_Finally, + AST_For, + AST_ForIn, + AST_ForOf, + AST_If, + AST_Import, + AST_ImportMeta, + AST_Jump, + AST_LabeledStatement, + AST_Lambda, + AST_LoopControl, + AST_NameMapping, + AST_NewTarget, + AST_Node, + AST_Number, + AST_Object, + AST_ObjectGetter, + AST_ObjectKeyVal, + AST_ObjectProperty, + AST_ObjectSetter, + AST_PrefixedTemplateString, + AST_PropAccess, + AST_RegExp, + AST_Sequence, + AST_SimpleStatement, + AST_String, + AST_Super, + AST_Switch, + AST_SwitchBranch, + AST_Symbol, + AST_TemplateSegment, + AST_TemplateString, + AST_This, + AST_Toplevel, + AST_Try, + AST_Unary, + AST_VarDef, + AST_While, + AST_With, + AST_Yield +} from "./ast.js"; + +const shallow_cmp = (node1, node2) => { + return ( + node1 === null && node2 === null + || node1.TYPE === node2.TYPE && node1.shallow_cmp(node2) + ); +}; + +export const equivalent_to = (tree1, tree2) => { + if (!shallow_cmp(tree1, tree2)) return false; + const walk_1_state = [tree1]; + const walk_2_state = [tree2]; + + const walk_1_push = walk_1_state.push.bind(walk_1_state); + const walk_2_push = walk_2_state.push.bind(walk_2_state); + + while (walk_1_state.length && walk_2_state.length) { + const node_1 = walk_1_state.pop(); + const node_2 = walk_2_state.pop(); + + if (!shallow_cmp(node_1, node_2)) return false; + + node_1._children_backwards(walk_1_push); + node_2._children_backwards(walk_2_push); + + if (walk_1_state.length !== walk_2_state.length) { + // Different number of children + return false; + } + } + + return walk_1_state.length == 0 && walk_2_state.length == 0; +}; + +const pass_through = () => true; + +AST_Node.prototype.shallow_cmp = function () { + throw new Error("did not find a shallow_cmp function for " + this.constructor.name); +}; + +AST_Debugger.prototype.shallow_cmp = pass_through; + +AST_Directive.prototype.shallow_cmp = function(other) { + return this.value === other.value; +}; + +AST_SimpleStatement.prototype.shallow_cmp = pass_through; + +AST_Block.prototype.shallow_cmp = pass_through; + +AST_EmptyStatement.prototype.shallow_cmp = pass_through; + +AST_LabeledStatement.prototype.shallow_cmp = function(other) { + return this.label.name === other.label.name; +}; + +AST_Do.prototype.shallow_cmp = pass_through; + +AST_While.prototype.shallow_cmp = pass_through; + +AST_For.prototype.shallow_cmp = function(other) { + return (this.init == null ? other.init == null : this.init === other.init) && (this.condition == null ? other.condition == null : this.condition === other.condition) && (this.step == null ? other.step == null : this.step === other.step); +}; + +AST_ForIn.prototype.shallow_cmp = pass_through; + +AST_ForOf.prototype.shallow_cmp = pass_through; + +AST_With.prototype.shallow_cmp = pass_through; + +AST_Toplevel.prototype.shallow_cmp = pass_through; + +AST_Expansion.prototype.shallow_cmp = pass_through; + +AST_Lambda.prototype.shallow_cmp = function(other) { + return this.is_generator === other.is_generator && this.async === other.async; +}; + +AST_Destructuring.prototype.shallow_cmp = function(other) { + return this.is_array === other.is_array; +}; + +AST_PrefixedTemplateString.prototype.shallow_cmp = pass_through; + +AST_TemplateString.prototype.shallow_cmp = pass_through; + +AST_TemplateSegment.prototype.shallow_cmp = function(other) { + return this.value === other.value; +}; + +AST_Jump.prototype.shallow_cmp = pass_through; + +AST_LoopControl.prototype.shallow_cmp = pass_through; + +AST_Await.prototype.shallow_cmp = pass_through; + +AST_Yield.prototype.shallow_cmp = function(other) { + return this.is_star === other.is_star; +}; + +AST_If.prototype.shallow_cmp = function(other) { + return this.alternative == null ? other.alternative == null : this.alternative === other.alternative; +}; + +AST_Switch.prototype.shallow_cmp = pass_through; + +AST_SwitchBranch.prototype.shallow_cmp = pass_through; + +AST_Try.prototype.shallow_cmp = function(other) { + return (this.body === other.body) && (this.bcatch == null ? other.bcatch == null : this.bcatch === other.bcatch) && (this.bfinally == null ? other.bfinally == null : this.bfinally === other.bfinally); +}; + +AST_Catch.prototype.shallow_cmp = function(other) { + return this.argname == null ? other.argname == null : this.argname === other.argname; +}; + +AST_Finally.prototype.shallow_cmp = pass_through; + +AST_Definitions.prototype.shallow_cmp = pass_through; + +AST_VarDef.prototype.shallow_cmp = function(other) { + return this.value == null ? other.value == null : this.value === other.value; +}; + +AST_NameMapping.prototype.shallow_cmp = pass_through; + +AST_Import.prototype.shallow_cmp = function(other) { + return (this.imported_name == null ? other.imported_name == null : this.imported_name === other.imported_name) && (this.imported_names == null ? other.imported_names == null : this.imported_names === other.imported_names); +}; + +AST_ImportMeta.prototype.shallow_cmp = pass_through; + +AST_Export.prototype.shallow_cmp = function(other) { + return (this.exported_definition == null ? other.exported_definition == null : this.exported_definition === other.exported_definition) && (this.exported_value == null ? other.exported_value == null : this.exported_value === other.exported_value) && (this.exported_names == null ? other.exported_names == null : this.exported_names === other.exported_names) && this.module_name === other.module_name && this.is_default === other.is_default; +}; + +AST_Call.prototype.shallow_cmp = pass_through; + +AST_Sequence.prototype.shallow_cmp = pass_through; + +AST_PropAccess.prototype.shallow_cmp = pass_through; + +AST_Chain.prototype.shallow_cmp = pass_through; + +AST_Dot.prototype.shallow_cmp = function(other) { + return this.property === other.property; +}; + +AST_DotHash.prototype.shallow_cmp = function(other) { + return this.property === other.property; +}; + +AST_Unary.prototype.shallow_cmp = function(other) { + return this.operator === other.operator; +}; + +AST_Binary.prototype.shallow_cmp = function(other) { + return this.operator === other.operator; +}; + +AST_Conditional.prototype.shallow_cmp = pass_through; + +AST_Array.prototype.shallow_cmp = pass_through; + +AST_Object.prototype.shallow_cmp = pass_through; + +AST_ObjectProperty.prototype.shallow_cmp = pass_through; + +AST_ObjectKeyVal.prototype.shallow_cmp = function(other) { + return this.key === other.key; +}; + +AST_ObjectSetter.prototype.shallow_cmp = function(other) { + return this.static === other.static; +}; + +AST_ObjectGetter.prototype.shallow_cmp = function(other) { + return this.static === other.static; +}; + +AST_ConciseMethod.prototype.shallow_cmp = function(other) { + return this.static === other.static && this.is_generator === other.is_generator && this.async === other.async; +}; + +AST_Class.prototype.shallow_cmp = function(other) { + return (this.name == null ? other.name == null : this.name === other.name) && (this.extends == null ? other.extends == null : this.extends === other.extends); +}; + +AST_ClassProperty.prototype.shallow_cmp = function(other) { + return this.static === other.static; +}; + +AST_Symbol.prototype.shallow_cmp = function(other) { + return this.name === other.name; +}; + +AST_NewTarget.prototype.shallow_cmp = pass_through; + +AST_This.prototype.shallow_cmp = pass_through; + +AST_Super.prototype.shallow_cmp = pass_through; + +AST_String.prototype.shallow_cmp = function(other) { + return this.value === other.value; +}; + +AST_Number.prototype.shallow_cmp = function(other) { + return this.value === other.value; +}; + +AST_BigInt.prototype.shallow_cmp = function(other) { + return this.value === other.value; +}; + +AST_RegExp.prototype.shallow_cmp = function (other) { + return ( + this.value.flags === other.value.flags + && this.value.source === other.value.source + ); +}; + +AST_Atom.prototype.shallow_cmp = pass_through; diff --git a/node_modules/terser/lib/minify.js b/node_modules/terser/lib/minify.js new file mode 100644 index 0000000..68af570 --- /dev/null +++ b/node_modules/terser/lib/minify.js @@ -0,0 +1,412 @@ +"use strict"; +/* eslint-env browser, es6, node */ + +import { + defaults, + map_from_object, + map_to_object, + HOP, +} from "./utils/index.js"; +import { AST_Toplevel, AST_Node, walk, AST_Scope } from "./ast.js"; +import { parse } from "./parse.js"; +import { OutputStream } from "./output.js"; +import { Compressor } from "./compress/index.js"; +import { base54 } from "./scope.js"; +import { SourceMap } from "./sourcemap.js"; +import { + mangle_properties, + mangle_private_properties, + reserve_quoted_keys, + find_annotated_props, +} from "./propmangle.js"; + +// to/from base64 functions +// Prefer built-in Buffer, if available, then use hack +// https://developer.mozilla.org/en-US/docs/Glossary/Base64#The_Unicode_Problem +var to_ascii = typeof Buffer !== "undefined" + ? (b64) => Buffer.from(b64, "base64").toString() + : (b64) => decodeURIComponent(escape(atob(b64))); +var to_base64 = typeof Buffer !== "undefined" + ? (str) => Buffer.from(str).toString("base64") + : (str) => btoa(unescape(encodeURIComponent(str))); + +function read_source_map(code) { + var match = /(?:^|[^.])\/\/# sourceMappingURL=data:application\/json(;[\w=-]*)?;base64,([+/0-9A-Za-z]*=*)\s*$/.exec(code); + if (!match) { + console.warn("inline source map not found"); + return null; + } + return to_ascii(match[2]); +} + +function set_shorthand(name, options, keys) { + if (options[name]) { + keys.forEach(function(key) { + if (options[key]) { + if (typeof options[key] != "object") options[key] = {}; + if (!(name in options[key])) options[key][name] = options[name]; + } + }); + } +} + +function init_cache(cache) { + if (!cache) return; + if (!("props" in cache)) { + cache.props = new Map(); + } else if (!(cache.props instanceof Map)) { + cache.props = map_from_object(cache.props); + } +} + +function cache_to_json(cache) { + return { + props: map_to_object(cache.props) + }; +} + +function log_input(files, options, fs, debug_folder) { + if (!(fs && fs.writeFileSync && fs.mkdirSync)) { + return; + } + + try { + fs.mkdirSync(debug_folder); + } catch (e) { + if (e.code !== "EEXIST") throw e; + } + + const log_path = `${debug_folder}/terser-debug-${(Math.random() * 9999999) | 0}.log`; + + options = options || {}; + + const options_str = JSON.stringify(options, (_key, thing) => { + if (typeof thing === "function") return "[Function " + thing.toString() + "]"; + if (thing instanceof RegExp) return "[RegExp " + thing.toString() + "]"; + return thing; + }, 4); + + const files_str = (file) => { + if (typeof file === "object" && options.parse && options.parse.spidermonkey) { + return JSON.stringify(file, null, 2); + } else if (typeof file === "object") { + return Object.keys(file) + .map((key) => key + ": " + files_str(file[key])) + .join("\n\n"); + } else if (typeof file === "string") { + return "```\n" + file + "\n```"; + } else { + return file; // What do? + } + }; + + fs.writeFileSync(log_path, "Options: \n" + options_str + "\n\nInput files:\n\n" + files_str(files) + "\n"); +} + +function* minify_sync_or_async(files, options, _fs_module) { + if ( + _fs_module + && typeof process === "object" + && process.env + && typeof process.env.TERSER_DEBUG_DIR === "string" + ) { + log_input(files, options, _fs_module, process.env.TERSER_DEBUG_DIR); + } + + options = defaults(options, { + compress: {}, + ecma: undefined, + enclose: false, + ie8: false, + keep_classnames: undefined, + keep_fnames: false, + mangle: {}, + module: false, + nameCache: null, + output: null, + format: null, + parse: {}, + rename: undefined, + safari10: false, + sourceMap: false, + spidermonkey: false, + timings: false, + toplevel: false, + warnings: false, + wrap: false, + }, true); + + var timings = options.timings && { + start: Date.now() + }; + if (options.keep_classnames === undefined) { + options.keep_classnames = options.keep_fnames; + } + if (options.rename === undefined) { + options.rename = options.compress && options.mangle; + } + if (options.output && options.format) { + throw new Error("Please only specify either output or format option, preferrably format."); + } + options.format = options.format || options.output || {}; + set_shorthand("ecma", options, [ "parse", "compress", "format" ]); + set_shorthand("ie8", options, [ "compress", "mangle", "format" ]); + set_shorthand("keep_classnames", options, [ "compress", "mangle" ]); + set_shorthand("keep_fnames", options, [ "compress", "mangle" ]); + set_shorthand("module", options, [ "parse", "compress", "mangle" ]); + set_shorthand("safari10", options, [ "mangle", "format" ]); + set_shorthand("toplevel", options, [ "compress", "mangle" ]); + set_shorthand("warnings", options, [ "compress" ]); // legacy + var quoted_props; + if (options.mangle) { + options.mangle = defaults(options.mangle, { + cache: options.nameCache && (options.nameCache.vars || {}), + eval: false, + ie8: false, + keep_classnames: false, + keep_fnames: false, + module: false, + nth_identifier: base54, + properties: false, + reserved: [], + safari10: false, + toplevel: false, + }, true); + if (options.mangle.properties) { + if (typeof options.mangle.properties != "object") { + options.mangle.properties = {}; + } + if (options.mangle.properties.keep_quoted) { + quoted_props = options.mangle.properties.reserved; + if (!Array.isArray(quoted_props)) quoted_props = []; + options.mangle.properties.reserved = quoted_props; + } + if (options.nameCache && !("cache" in options.mangle.properties)) { + options.mangle.properties.cache = options.nameCache.props || {}; + } + } + init_cache(options.mangle.cache); + init_cache(options.mangle.properties.cache); + } + if (options.sourceMap) { + options.sourceMap = defaults(options.sourceMap, { + asObject: false, + content: null, + filename: null, + includeSources: false, + root: null, + url: null, + }, true); + } + + // -- Parse phase -- + if (timings) timings.parse = Date.now(); + var toplevel; + if (files instanceof AST_Toplevel) { + toplevel = files; + } else { + if (typeof files == "string" || (options.parse.spidermonkey && !Array.isArray(files))) { + files = [ files ]; + } + options.parse = options.parse || {}; + options.parse.toplevel = null; + + if (options.parse.spidermonkey) { + options.parse.toplevel = AST_Node.from_mozilla_ast(Object.keys(files).reduce(function(toplevel, name) { + if (!toplevel) return files[name]; + toplevel.body = toplevel.body.concat(files[name].body); + return toplevel; + }, null)); + } else { + delete options.parse.spidermonkey; + + for (var name in files) if (HOP(files, name)) { + options.parse.filename = name; + options.parse.toplevel = parse(files[name], options.parse); + if (options.sourceMap && options.sourceMap.content == "inline") { + if (Object.keys(files).length > 1) + throw new Error("inline source map only works with singular input"); + options.sourceMap.content = read_source_map(files[name]); + } + } + } + if (options.parse.toplevel === null) { + throw new Error("no source file given"); + } + + toplevel = options.parse.toplevel; + } + if (quoted_props && options.mangle.properties.keep_quoted !== "strict") { + reserve_quoted_keys(toplevel, quoted_props); + } + var annotated_props; + if (options.mangle && options.mangle.properties) { + annotated_props = find_annotated_props(toplevel); + } + if (options.wrap) { + toplevel = toplevel.wrap_commonjs(options.wrap); + } + if (options.enclose) { + toplevel = toplevel.wrap_enclose(options.enclose); + } + if (timings) timings.rename = Date.now(); + // disable rename on harmony due to expand_names bug in for-of loops + // https://github.com/mishoo/UglifyJS2/issues/2794 + if (0 && options.rename) { + toplevel.figure_out_scope(options.mangle); + toplevel.expand_names(options.mangle); + } + + // -- Compress phase -- + if (timings) timings.compress = Date.now(); + if (options.compress) { + toplevel = new Compressor(options.compress, { + mangle_options: options.mangle + }).compress(toplevel); + } + + // -- Mangle phase -- + if (timings) timings.scope = Date.now(); + if (options.mangle) toplevel.figure_out_scope(options.mangle); + if (timings) timings.mangle = Date.now(); + if (options.mangle) { + toplevel.compute_char_frequency(options.mangle); + toplevel.mangle_names(options.mangle); + toplevel = mangle_private_properties(toplevel, options.mangle); + } + if (timings) timings.properties = Date.now(); + if (options.mangle && options.mangle.properties) { + toplevel = mangle_properties(toplevel, options.mangle.properties, annotated_props); + } + + // Format phase + if (timings) timings.format = Date.now(); + var result = {}; + if (options.format.ast) { + result.ast = toplevel; + } + if (options.format.spidermonkey) { + result.ast = toplevel.to_mozilla_ast(); + } + let format_options; + if (!HOP(options.format, "code") || options.format.code) { + // Make a shallow copy so that we can modify without mutating the user's input. + format_options = {...options.format}; + if (!format_options.ast) { + // Destroy stuff to save RAM. (unless the deprecated `ast` option is on) + format_options._destroy_ast = true; + + walk(toplevel, node => { + if (node instanceof AST_Scope) { + node.variables = undefined; + node.enclosed = undefined; + node.parent_scope = undefined; + } + if (node.block_scope) { + node.block_scope.variables = undefined; + node.block_scope.enclosed = undefined; + node.parent_scope = undefined; + } + }); + } + + if (options.sourceMap) { + if (options.sourceMap.includeSources && files instanceof AST_Toplevel) { + throw new Error("original source content unavailable"); + } + format_options.source_map = yield* SourceMap({ + file: options.sourceMap.filename, + orig: options.sourceMap.content, + root: options.sourceMap.root, + files: options.sourceMap.includeSources ? files : null, + }); + } + delete format_options.ast; + delete format_options.code; + delete format_options.spidermonkey; + var stream = OutputStream(format_options); + toplevel.print(stream); + result.code = stream.get(); + if (options.sourceMap) { + Object.defineProperty(result, "map", { + configurable: true, + enumerable: true, + get() { + const map = format_options.source_map.getEncoded(); + return (result.map = options.sourceMap.asObject ? map : JSON.stringify(map)); + }, + set(value) { + Object.defineProperty(result, "map", { + value, + writable: true, + }); + } + }); + result.decoded_map = format_options.source_map.getDecoded(); + if (options.sourceMap.url == "inline") { + var sourceMap = typeof result.map === "object" ? JSON.stringify(result.map) : result.map; + result.code += "\n//# sourceMappingURL=data:application/json;charset=utf-8;base64," + to_base64(sourceMap); + } else if (options.sourceMap.url) { + result.code += "\n//# sourceMappingURL=" + options.sourceMap.url; + } + } + } + if (options.nameCache && options.mangle) { + if (options.mangle.cache) options.nameCache.vars = cache_to_json(options.mangle.cache); + if (options.mangle.properties && options.mangle.properties.cache) { + options.nameCache.props = cache_to_json(options.mangle.properties.cache); + } + } + if (format_options && format_options.source_map) { + format_options.source_map.destroy(); + } + if (timings) { + timings.end = Date.now(); + result.timings = { + parse: 1e-3 * (timings.rename - timings.parse), + rename: 1e-3 * (timings.compress - timings.rename), + compress: 1e-3 * (timings.scope - timings.compress), + scope: 1e-3 * (timings.mangle - timings.scope), + mangle: 1e-3 * (timings.properties - timings.mangle), + properties: 1e-3 * (timings.format - timings.properties), + format: 1e-3 * (timings.end - timings.format), + total: 1e-3 * (timings.end - timings.start) + }; + } + return result; +} + +async function minify(files, options, _fs_module) { + const gen = minify_sync_or_async(files, options, _fs_module); + + let yielded; + let val; + do { + val = gen.next(await yielded); + yielded = val.value; + } while (!val.done); + + return val.value; +} + +function minify_sync(files, options, _fs_module) { + const gen = minify_sync_or_async(files, options, _fs_module); + + let yielded; + let val; + do { + if (yielded && typeof yielded.then === "function") { + throw new Error("minify_sync cannot be used with the legacy source-map module"); + } + val = gen.next(yielded); + yielded = val.value; + } while (!val.done); + + return val.value; +} + +export { + minify, + minify_sync, + to_ascii, +}; diff --git a/node_modules/terser/lib/mozilla-ast.js b/node_modules/terser/lib/mozilla-ast.js new file mode 100644 index 0000000..9e32b7e --- /dev/null +++ b/node_modules/terser/lib/mozilla-ast.js @@ -0,0 +1,1907 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +import { make_node } from "./utils/index.js"; +import { + AST_Accessor, + AST_Array, + AST_Arrow, + AST_Assign, + AST_Atom, + AST_Await, + AST_BigInt, + AST_Binary, + AST_Block, + AST_BlockStatement, + AST_Boolean, + AST_Break, + AST_Call, + AST_Case, + AST_Catch, + AST_Chain, + AST_Class, + AST_ClassStaticBlock, + AST_ClassExpression, + AST_ClassProperty, + AST_ClassPrivateProperty, + AST_ConciseMethod, + AST_Conditional, + AST_Const, + AST_Constant, + AST_Continue, + AST_Debugger, + AST_Default, + AST_DefaultAssign, + AST_DefClass, + AST_Definitions, + AST_Defun, + AST_Destructuring, + AST_Directive, + AST_Do, + AST_Dot, + AST_DotHash, + AST_EmptyStatement, + AST_Expansion, + AST_Export, + AST_False, + AST_Finally, + AST_For, + AST_ForIn, + AST_ForOf, + AST_Function, + AST_Hole, + AST_If, + AST_Import, + AST_ImportMeta, + AST_Label, + AST_LabeledStatement, + AST_LabelRef, + AST_Lambda, + AST_Let, + AST_NameMapping, + AST_New, + AST_NewTarget, + AST_Node, + AST_Null, + AST_Number, + AST_Object, + AST_ObjectGetter, + AST_ObjectKeyVal, + AST_ObjectProperty, + AST_ObjectSetter, + AST_PrefixedTemplateString, + AST_PrivateGetter, + AST_PrivateMethod, + AST_PrivateSetter, + AST_PrivateIn, + AST_PropAccess, + AST_RegExp, + AST_Return, + AST_Sequence, + AST_SimpleStatement, + AST_Statement, + AST_String, + AST_Sub, + AST_Super, + AST_Switch, + AST_SwitchBranch, + AST_Symbol, + AST_SymbolCatch, + AST_SymbolClass, + AST_SymbolClassProperty, + AST_SymbolPrivateProperty, + AST_SymbolConst, + AST_SymbolDefClass, + AST_SymbolDefun, + AST_SymbolExport, + AST_SymbolExportForeign, + AST_SymbolFunarg, + AST_SymbolImport, + AST_SymbolImportForeign, + AST_SymbolLambda, + AST_SymbolLet, + AST_SymbolMethod, + AST_SymbolRef, + AST_SymbolVar, + AST_TemplateSegment, + AST_TemplateString, + AST_This, + AST_Throw, + AST_Token, + AST_Toplevel, + AST_True, + AST_Try, + AST_TryBlock, + AST_Unary, + AST_UnaryPostfix, + AST_UnaryPrefix, + AST_Var, + AST_VarDef, + AST_While, + AST_With, + AST_Yield, +} from "./ast.js"; +import { is_basic_identifier_string } from "./parse.js"; + +(function() { + + var normalize_directives = function(body) { + for (var i = 0; i < body.length; i++) { + if (body[i] instanceof AST_Statement && body[i].body instanceof AST_String) { + body[i] = new AST_Directive({ + start: body[i].start, + end: body[i].end, + value: body[i].body.value + }); + } else { + return body; + } + } + + return body; + }; + + const assert_clause_from_moz = (assertions) => { + if (assertions && assertions.length > 0) { + return new AST_Object({ + start: my_start_token(assertions), + end: my_end_token(assertions), + properties: assertions.map((assertion_kv) => + new AST_ObjectKeyVal({ + start: my_start_token(assertion_kv), + end: my_end_token(assertion_kv), + key: assertion_kv.key.name || assertion_kv.key.value, + value: from_moz(assertion_kv.value) + }) + ) + }); + } + return null; + }; + + var MOZ_TO_ME = { + Program: function(M) { + return new AST_Toplevel({ + start: my_start_token(M), + end: my_end_token(M), + body: normalize_directives(M.body.map(from_moz)) + }); + }, + + ArrayPattern: function(M) { + return new AST_Destructuring({ + start: my_start_token(M), + end: my_end_token(M), + names: M.elements.map(function(elm) { + if (elm === null) { + return new AST_Hole(); + } + return from_moz(elm); + }), + is_array: true + }); + }, + + ObjectPattern: function(M) { + return new AST_Destructuring({ + start: my_start_token(M), + end: my_end_token(M), + names: M.properties.map(from_moz), + is_array: false + }); + }, + + AssignmentPattern: function(M) { + return new AST_DefaultAssign({ + start: my_start_token(M), + end: my_end_token(M), + left: from_moz(M.left), + operator: "=", + right: from_moz(M.right) + }); + }, + + SpreadElement: function(M) { + return new AST_Expansion({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz(M.argument) + }); + }, + + RestElement: function(M) { + return new AST_Expansion({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz(M.argument) + }); + }, + + TemplateElement: function(M) { + return new AST_TemplateSegment({ + start: my_start_token(M), + end: my_end_token(M), + value: M.value.cooked, + raw: M.value.raw + }); + }, + + TemplateLiteral: function(M) { + var segments = []; + for (var i = 0; i < M.quasis.length; i++) { + segments.push(from_moz(M.quasis[i])); + if (M.expressions[i]) { + segments.push(from_moz(M.expressions[i])); + } + } + return new AST_TemplateString({ + start: my_start_token(M), + end: my_end_token(M), + segments: segments + }); + }, + + TaggedTemplateExpression: function(M) { + return new AST_PrefixedTemplateString({ + start: my_start_token(M), + end: my_end_token(M), + template_string: from_moz(M.quasi), + prefix: from_moz(M.tag) + }); + }, + + FunctionDeclaration: function(M) { + return new AST_Defun({ + start: my_start_token(M), + end: my_end_token(M), + name: from_moz(M.id), + argnames: M.params.map(from_moz), + is_generator: M.generator, + async: M.async, + body: normalize_directives(from_moz(M.body).body) + }); + }, + + FunctionExpression: function(M) { + return new AST_Function({ + start: my_start_token(M), + end: my_end_token(M), + name: from_moz(M.id), + argnames: M.params.map(from_moz), + is_generator: M.generator, + async: M.async, + body: normalize_directives(from_moz(M.body).body) + }); + }, + + ArrowFunctionExpression: function(M) { + const body = M.body.type === "BlockStatement" + ? from_moz(M.body).body + : [make_node(AST_Return, {}, { value: from_moz(M.body) })]; + return new AST_Arrow({ + start: my_start_token(M), + end: my_end_token(M), + argnames: M.params.map(from_moz), + body, + async: M.async, + }); + }, + + ExpressionStatement: function(M) { + return new AST_SimpleStatement({ + start: my_start_token(M), + end: my_end_token(M), + body: from_moz(M.expression) + }); + }, + + TryStatement: function(M) { + var handlers = M.handlers || [M.handler]; + if (handlers.length > 1 || M.guardedHandlers && M.guardedHandlers.length) { + throw new Error("Multiple catch clauses are not supported."); + } + return new AST_Try({ + start : my_start_token(M), + end : my_end_token(M), + body : new AST_TryBlock(from_moz(M.block)), + bcatch : from_moz(handlers[0]), + bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null + }); + }, + + Property: function(M) { + var key = M.key; + var args = { + start : my_start_token(key || M.value), + end : my_end_token(M.value), + key : key.type == "Identifier" ? key.name : key.value, + value : from_moz(M.value) + }; + if (M.computed) { + args.key = from_moz(M.key); + } + if (M.method) { + args.is_generator = M.value.generator; + args.async = M.value.async; + if (!M.computed) { + args.key = new AST_SymbolMethod({ name: args.key }); + } else { + args.key = from_moz(M.key); + } + return new AST_ConciseMethod(args); + } + if (M.kind == "init") { + if (key.type != "Identifier" && key.type != "Literal") { + args.key = from_moz(key); + } + return new AST_ObjectKeyVal(args); + } + if (typeof args.key === "string" || typeof args.key === "number") { + args.key = new AST_SymbolMethod({ + name: args.key + }); + } + args.value = new AST_Accessor(args.value); + if (M.kind == "get") return new AST_ObjectGetter(args); + if (M.kind == "set") return new AST_ObjectSetter(args); + if (M.kind == "method") { + args.async = M.value.async; + args.is_generator = M.value.generator; + args.quote = M.computed ? "\"" : null; + return new AST_ConciseMethod(args); + } + }, + + MethodDefinition: function(M) { + const is_private = M.key.type === "PrivateIdentifier"; + const key = M.computed ? from_moz(M.key) : new AST_SymbolMethod({ name: M.key.name || M.key.value }); + + var args = { + start : my_start_token(M), + end : my_end_token(M), + key, + value : from_moz(M.value), + static : M.static, + }; + if (M.kind == "get") { + return new (is_private ? AST_PrivateGetter : AST_ObjectGetter)(args); + } + if (M.kind == "set") { + return new (is_private ? AST_PrivateSetter : AST_ObjectSetter)(args); + } + args.is_generator = M.value.generator; + args.async = M.value.async; + return new (is_private ? AST_PrivateMethod : AST_ConciseMethod)(args); + }, + + FieldDefinition: function(M) { + let key; + if (M.computed) { + key = from_moz(M.key); + } else { + if (M.key.type !== "Identifier") throw new Error("Non-Identifier key in FieldDefinition"); + key = from_moz(M.key); + } + return new AST_ClassProperty({ + start : my_start_token(M), + end : my_end_token(M), + key, + value : from_moz(M.value), + static : M.static, + }); + }, + + PropertyDefinition: function(M) { + let key; + if (M.computed) { + key = from_moz(M.key); + } else if (M.key.type === "PrivateIdentifier") { + return new AST_ClassPrivateProperty({ + start : my_start_token(M), + end : my_end_token(M), + key : from_moz(M.key), + value : from_moz(M.value), + static : M.static, + }); + } else { + if (M.key.type !== "Identifier") { + throw new Error("Non-Identifier key in PropertyDefinition"); + } + key = from_moz(M.key); + } + + return new AST_ClassProperty({ + start : my_start_token(M), + end : my_end_token(M), + key, + value : from_moz(M.value), + static : M.static, + }); + }, + + PrivateIdentifier: function (M) { + return new AST_SymbolPrivateProperty({ + start: my_start_token(M), + end: my_end_token(M), + name: M.name + }); + }, + + StaticBlock: function(M) { + return new AST_ClassStaticBlock({ + start : my_start_token(M), + end : my_end_token(M), + body : M.body.map(from_moz), + }); + }, + + ArrayExpression: function(M) { + return new AST_Array({ + start : my_start_token(M), + end : my_end_token(M), + elements : M.elements.map(function(elem) { + return elem === null ? new AST_Hole() : from_moz(elem); + }) + }); + }, + + ObjectExpression: function(M) { + return new AST_Object({ + start : my_start_token(M), + end : my_end_token(M), + properties : M.properties.map(function(prop) { + if (prop.type === "SpreadElement") { + return from_moz(prop); + } + prop.type = "Property"; + return from_moz(prop); + }) + }); + }, + + SequenceExpression: function(M) { + return new AST_Sequence({ + start : my_start_token(M), + end : my_end_token(M), + expressions: M.expressions.map(from_moz) + }); + }, + + MemberExpression: function(M) { + if (M.property.type === "PrivateIdentifier") { + return new AST_DotHash({ + start : my_start_token(M), + end : my_end_token(M), + property : M.property.name, + expression : from_moz(M.object), + optional : M.optional || false + }); + } + return new (M.computed ? AST_Sub : AST_Dot)({ + start : my_start_token(M), + end : my_end_token(M), + property : M.computed ? from_moz(M.property) : M.property.name, + expression : from_moz(M.object), + optional : M.optional || false + }); + }, + + ChainExpression: function(M) { + return new AST_Chain({ + start : my_start_token(M), + end : my_end_token(M), + expression : from_moz(M.expression) + }); + }, + + SwitchCase: function(M) { + return new (M.test ? AST_Case : AST_Default)({ + start : my_start_token(M), + end : my_end_token(M), + expression : from_moz(M.test), + body : M.consequent.map(from_moz) + }); + }, + + VariableDeclaration: function(M) { + return new (M.kind === "const" ? AST_Const : + M.kind === "let" ? AST_Let : AST_Var)({ + start : my_start_token(M), + end : my_end_token(M), + definitions : M.declarations.map(from_moz) + }); + }, + + ImportDeclaration: function(M) { + var imported_name = null; + var imported_names = null; + M.specifiers.forEach(function (specifier) { + if (specifier.type === "ImportSpecifier" || specifier.type === "ImportNamespaceSpecifier") { + if (!imported_names) { imported_names = []; } + imported_names.push(from_moz(specifier)); + } else if (specifier.type === "ImportDefaultSpecifier") { + imported_name = from_moz(specifier); + } + }); + return new AST_Import({ + start : my_start_token(M), + end : my_end_token(M), + imported_name: imported_name, + imported_names : imported_names, + module_name : from_moz(M.source), + assert_clause: assert_clause_from_moz(M.assertions) + }); + }, + + ImportSpecifier: function(M) { + return new AST_NameMapping({ + start: my_start_token(M), + end: my_end_token(M), + foreign_name: from_moz(M.imported), + name: from_moz(M.local) + }); + }, + + ImportDefaultSpecifier: function(M) { + return from_moz(M.local); + }, + + ImportNamespaceSpecifier: function(M) { + return new AST_NameMapping({ + start: my_start_token(M), + end: my_end_token(M), + foreign_name: new AST_SymbolImportForeign({ name: "*" }), + name: from_moz(M.local) + }); + }, + + ImportExpression: function(M) { + return new AST_Call({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz({ + type: "Identifier", + name: "import" + }), + optional: false, + args: [from_moz(M.source)] + }); + }, + + ExportAllDeclaration: function(M) { + var foreign_name = M.exported == null ? + new AST_SymbolExportForeign({ name: "*" }) : + from_moz(M.exported); + return new AST_Export({ + start: my_start_token(M), + end: my_end_token(M), + exported_names: [ + new AST_NameMapping({ + name: new AST_SymbolExportForeign({ name: "*" }), + foreign_name: foreign_name + }) + ], + module_name: from_moz(M.source), + assert_clause: assert_clause_from_moz(M.assertions) + }); + }, + + ExportNamedDeclaration: function(M) { + return new AST_Export({ + start: my_start_token(M), + end: my_end_token(M), + exported_definition: from_moz(M.declaration), + exported_names: M.specifiers && M.specifiers.length ? M.specifiers.map(from_moz) : null, + module_name: from_moz(M.source), + assert_clause: assert_clause_from_moz(M.assertions) + }); + }, + + ExportDefaultDeclaration: function(M) { + return new AST_Export({ + start: my_start_token(M), + end: my_end_token(M), + exported_value: from_moz(M.declaration), + is_default: true + }); + }, + + ExportSpecifier: function(M) { + return new AST_NameMapping({ + foreign_name: from_moz(M.exported), + name: from_moz(M.local) + }); + }, + + Literal: function(M) { + var val = M.value, args = { + start : my_start_token(M), + end : my_end_token(M) + }; + var rx = M.regex; + if (rx && rx.pattern) { + // RegExpLiteral as per ESTree AST spec + args.value = { + source: rx.pattern, + flags: rx.flags + }; + return new AST_RegExp(args); + } else if (rx) { + // support legacy RegExp + const rx_source = M.raw || val; + const match = rx_source.match(/^\/(.*)\/(\w*)$/); + if (!match) throw new Error("Invalid regex source " + rx_source); + const [_, source, flags] = match; + args.value = { source, flags }; + return new AST_RegExp(args); + } + const bi = typeof M.value === "bigint" ? M.value.toString() : M.bigint; + if (typeof bi === "string") { + args.value = bi; + return new AST_BigInt(args); + } + if (val === null) return new AST_Null(args); + switch (typeof val) { + case "string": + args.quote = "\""; + var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2]; + if (p.type == "ImportSpecifier") { + args.name = val; + return new AST_SymbolImportForeign(args); + } else if (p.type == "ExportSpecifier") { + args.name = val; + if (M == p.exported) { + return new AST_SymbolExportForeign(args); + } else { + return new AST_SymbolExport(args); + } + } else if (p.type == "ExportAllDeclaration" && M == p.exported) { + args.name = val; + return new AST_SymbolExportForeign(args); + } + args.value = val; + return new AST_String(args); + case "number": + args.value = val; + args.raw = M.raw || val.toString(); + return new AST_Number(args); + case "boolean": + return new (val ? AST_True : AST_False)(args); + } + }, + + MetaProperty: function(M) { + if (M.meta.name === "new" && M.property.name === "target") { + return new AST_NewTarget({ + start: my_start_token(M), + end: my_end_token(M) + }); + } else if (M.meta.name === "import" && M.property.name === "meta") { + return new AST_ImportMeta({ + start: my_start_token(M), + end: my_end_token(M) + }); + } + }, + + Identifier: function(M) { + var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2]; + return new ( p.type == "LabeledStatement" ? AST_Label + : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : p.kind == "let" ? AST_SymbolLet : AST_SymbolVar) + : /Import.*Specifier/.test(p.type) ? (p.local === M ? AST_SymbolImport : AST_SymbolImportForeign) + : p.type == "ExportSpecifier" ? (p.local === M ? AST_SymbolExport : AST_SymbolExportForeign) + : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg) + : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg) + : p.type == "ArrowFunctionExpression" ? (p.params.includes(M)) ? AST_SymbolFunarg : AST_SymbolRef + : p.type == "ClassExpression" ? (p.id === M ? AST_SymbolClass : AST_SymbolRef) + : p.type == "Property" ? (p.key === M && p.computed || p.value === M ? AST_SymbolRef : AST_SymbolMethod) + : p.type == "PropertyDefinition" || p.type === "FieldDefinition" ? (p.key === M && p.computed || p.value === M ? AST_SymbolRef : AST_SymbolClassProperty) + : p.type == "ClassDeclaration" ? (p.id === M ? AST_SymbolDefClass : AST_SymbolRef) + : p.type == "MethodDefinition" ? (p.computed ? AST_SymbolRef : AST_SymbolMethod) + : p.type == "CatchClause" ? AST_SymbolCatch + : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef + : AST_SymbolRef)({ + start : my_start_token(M), + end : my_end_token(M), + name : M.name + }); + }, + + EmptyStatement: function(M) { + return new AST_EmptyStatement({ + start: my_start_token(M), + end: my_end_token(M) + }); + }, + + BlockStatement: function(M) { + return new AST_BlockStatement({ + start: my_start_token(M), + end: my_end_token(M), + body: M.body.map(from_moz) + }); + }, + + IfStatement: function(M) { + return new AST_If({ + start: my_start_token(M), + end: my_end_token(M), + condition: from_moz(M.test), + body: from_moz(M.consequent), + alternative: from_moz(M.alternate) + }); + }, + + LabeledStatement: function(M) { + return new AST_LabeledStatement({ + start: my_start_token(M), + end: my_end_token(M), + label: from_moz(M.label), + body: from_moz(M.body) + }); + }, + + BreakStatement: function(M) { + return new AST_Break({ + start: my_start_token(M), + end: my_end_token(M), + label: from_moz(M.label) + }); + }, + + ContinueStatement: function(M) { + return new AST_Continue({ + start: my_start_token(M), + end: my_end_token(M), + label: from_moz(M.label) + }); + }, + + WithStatement: function(M) { + return new AST_With({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz(M.object), + body: from_moz(M.body) + }); + }, + + SwitchStatement: function(M) { + return new AST_Switch({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz(M.discriminant), + body: M.cases.map(from_moz) + }); + }, + + ReturnStatement: function(M) { + return new AST_Return({ + start: my_start_token(M), + end: my_end_token(M), + value: from_moz(M.argument) + }); + }, + + ThrowStatement: function(M) { + return new AST_Throw({ + start: my_start_token(M), + end: my_end_token(M), + value: from_moz(M.argument) + }); + }, + + WhileStatement: function(M) { + return new AST_While({ + start: my_start_token(M), + end: my_end_token(M), + condition: from_moz(M.test), + body: from_moz(M.body) + }); + }, + + DoWhileStatement: function(M) { + return new AST_Do({ + start: my_start_token(M), + end: my_end_token(M), + condition: from_moz(M.test), + body: from_moz(M.body) + }); + }, + + ForStatement: function(M) { + return new AST_For({ + start: my_start_token(M), + end: my_end_token(M), + init: from_moz(M.init), + condition: from_moz(M.test), + step: from_moz(M.update), + body: from_moz(M.body) + }); + }, + + ForInStatement: function(M) { + return new AST_ForIn({ + start: my_start_token(M), + end: my_end_token(M), + init: from_moz(M.left), + object: from_moz(M.right), + body: from_moz(M.body) + }); + }, + + ForOfStatement: function(M) { + return new AST_ForOf({ + start: my_start_token(M), + end: my_end_token(M), + init: from_moz(M.left), + object: from_moz(M.right), + body: from_moz(M.body), + await: M.await + }); + }, + + AwaitExpression: function(M) { + return new AST_Await({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz(M.argument) + }); + }, + + YieldExpression: function(M) { + return new AST_Yield({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz(M.argument), + is_star: M.delegate + }); + }, + + DebuggerStatement: function(M) { + return new AST_Debugger({ + start: my_start_token(M), + end: my_end_token(M) + }); + }, + + VariableDeclarator: function(M) { + return new AST_VarDef({ + start: my_start_token(M), + end: my_end_token(M), + name: from_moz(M.id), + value: from_moz(M.init) + }); + }, + + CatchClause: function(M) { + return new AST_Catch({ + start: my_start_token(M), + end: my_end_token(M), + argname: from_moz(M.param), + body: from_moz(M.body).body + }); + }, + + ThisExpression: function(M) { + return new AST_This({ + start: my_start_token(M), + end: my_end_token(M) + }); + }, + + Super: function(M) { + return new AST_Super({ + start: my_start_token(M), + end: my_end_token(M) + }); + }, + + BinaryExpression: function(M) { + if (M.left.type === "PrivateIdentifier") { + return new AST_PrivateIn({ + start: my_start_token(M), + end: my_end_token(M), + key: new AST_SymbolPrivateProperty({ + start: my_start_token(M.left), + end: my_end_token(M.left), + name: M.left.name + }), + value: from_moz(M.right), + }); + } + return new AST_Binary({ + start: my_start_token(M), + end: my_end_token(M), + operator: M.operator, + left: from_moz(M.left), + right: from_moz(M.right) + }); + }, + + LogicalExpression: function(M) { + return new AST_Binary({ + start: my_start_token(M), + end: my_end_token(M), + operator: M.operator, + left: from_moz(M.left), + right: from_moz(M.right) + }); + }, + + AssignmentExpression: function(M) { + return new AST_Assign({ + start: my_start_token(M), + end: my_end_token(M), + operator: M.operator, + left: from_moz(M.left), + right: from_moz(M.right) + }); + }, + + ConditionalExpression: function(M) { + return new AST_Conditional({ + start: my_start_token(M), + end: my_end_token(M), + condition: from_moz(M.test), + consequent: from_moz(M.consequent), + alternative: from_moz(M.alternate) + }); + }, + + NewExpression: function(M) { + return new AST_New({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz(M.callee), + args: M.arguments.map(from_moz) + }); + }, + + CallExpression: function(M) { + return new AST_Call({ + start: my_start_token(M), + end: my_end_token(M), + expression: from_moz(M.callee), + optional: M.optional, + args: M.arguments.map(from_moz) + }); + } + }; + + MOZ_TO_ME.UpdateExpression = + MOZ_TO_ME.UnaryExpression = function To_Moz_Unary(M) { + var prefix = "prefix" in M ? M.prefix + : M.type == "UnaryExpression" ? true : false; + return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({ + start : my_start_token(M), + end : my_end_token(M), + operator : M.operator, + expression : from_moz(M.argument) + }); + }; + + MOZ_TO_ME.ClassDeclaration = + MOZ_TO_ME.ClassExpression = function From_Moz_Class(M) { + return new (M.type === "ClassDeclaration" ? AST_DefClass : AST_ClassExpression)({ + start : my_start_token(M), + end : my_end_token(M), + name : from_moz(M.id), + extends : from_moz(M.superClass), + properties: M.body.body.map(from_moz) + }); + }; + + def_to_moz(AST_EmptyStatement, function To_Moz_EmptyStatement() { + return { + type: "EmptyStatement" + }; + }); + def_to_moz(AST_BlockStatement, function To_Moz_BlockStatement(M) { + return { + type: "BlockStatement", + body: M.body.map(to_moz) + }; + }); + def_to_moz(AST_If, function To_Moz_IfStatement(M) { + return { + type: "IfStatement", + test: to_moz(M.condition), + consequent: to_moz(M.body), + alternate: to_moz(M.alternative) + }; + }); + def_to_moz(AST_LabeledStatement, function To_Moz_LabeledStatement(M) { + return { + type: "LabeledStatement", + label: to_moz(M.label), + body: to_moz(M.body) + }; + }); + def_to_moz(AST_Break, function To_Moz_BreakStatement(M) { + return { + type: "BreakStatement", + label: to_moz(M.label) + }; + }); + def_to_moz(AST_Continue, function To_Moz_ContinueStatement(M) { + return { + type: "ContinueStatement", + label: to_moz(M.label) + }; + }); + def_to_moz(AST_With, function To_Moz_WithStatement(M) { + return { + type: "WithStatement", + object: to_moz(M.expression), + body: to_moz(M.body) + }; + }); + def_to_moz(AST_Switch, function To_Moz_SwitchStatement(M) { + return { + type: "SwitchStatement", + discriminant: to_moz(M.expression), + cases: M.body.map(to_moz) + }; + }); + def_to_moz(AST_Return, function To_Moz_ReturnStatement(M) { + return { + type: "ReturnStatement", + argument: to_moz(M.value) + }; + }); + def_to_moz(AST_Throw, function To_Moz_ThrowStatement(M) { + return { + type: "ThrowStatement", + argument: to_moz(M.value) + }; + }); + def_to_moz(AST_While, function To_Moz_WhileStatement(M) { + return { + type: "WhileStatement", + test: to_moz(M.condition), + body: to_moz(M.body) + }; + }); + def_to_moz(AST_Do, function To_Moz_DoWhileStatement(M) { + return { + type: "DoWhileStatement", + test: to_moz(M.condition), + body: to_moz(M.body) + }; + }); + def_to_moz(AST_For, function To_Moz_ForStatement(M) { + return { + type: "ForStatement", + init: to_moz(M.init), + test: to_moz(M.condition), + update: to_moz(M.step), + body: to_moz(M.body) + }; + }); + def_to_moz(AST_ForIn, function To_Moz_ForInStatement(M) { + return { + type: "ForInStatement", + left: to_moz(M.init), + right: to_moz(M.object), + body: to_moz(M.body) + }; + }); + def_to_moz(AST_ForOf, function To_Moz_ForOfStatement(M) { + return { + type: "ForOfStatement", + left: to_moz(M.init), + right: to_moz(M.object), + body: to_moz(M.body), + await: M.await + }; + }); + def_to_moz(AST_Await, function To_Moz_AwaitExpression(M) { + return { + type: "AwaitExpression", + argument: to_moz(M.expression) + }; + }); + def_to_moz(AST_Yield, function To_Moz_YieldExpression(M) { + return { + type: "YieldExpression", + argument: to_moz(M.expression), + delegate: M.is_star + }; + }); + def_to_moz(AST_Debugger, function To_Moz_DebuggerStatement() { + return { + type: "DebuggerStatement" + }; + }); + def_to_moz(AST_VarDef, function To_Moz_VariableDeclarator(M) { + return { + type: "VariableDeclarator", + id: to_moz(M.name), + init: to_moz(M.value) + }; + }); + def_to_moz(AST_Catch, function To_Moz_CatchClause(M) { + return { + type: "CatchClause", + param: to_moz(M.argname), + body: to_moz_block(M) + }; + }); + + def_to_moz(AST_This, function To_Moz_ThisExpression() { + return { + type: "ThisExpression" + }; + }); + def_to_moz(AST_Super, function To_Moz_Super() { + return { + type: "Super" + }; + }); + def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) { + return { + type: "BinaryExpression", + operator: M.operator, + left: to_moz(M.left), + right: to_moz(M.right) + }; + }); + def_to_moz(AST_Binary, function To_Moz_LogicalExpression(M) { + return { + type: "LogicalExpression", + operator: M.operator, + left: to_moz(M.left), + right: to_moz(M.right) + }; + }); + def_to_moz(AST_Assign, function To_Moz_AssignmentExpression(M) { + return { + type: "AssignmentExpression", + operator: M.operator, + left: to_moz(M.left), + right: to_moz(M.right) + }; + }); + def_to_moz(AST_Conditional, function To_Moz_ConditionalExpression(M) { + return { + type: "ConditionalExpression", + test: to_moz(M.condition), + consequent: to_moz(M.consequent), + alternate: to_moz(M.alternative) + }; + }); + def_to_moz(AST_New, function To_Moz_NewExpression(M) { + return { + type: "NewExpression", + callee: to_moz(M.expression), + arguments: M.args.map(to_moz) + }; + }); + def_to_moz(AST_Call, function To_Moz_CallExpression(M) { + if (M.expression instanceof AST_SymbolRef && M.expression.name === "import") { + const [source] = M.args.map(to_moz); + return { + type: "ImportExpression", + source, + }; + } + + return { + type: "CallExpression", + callee: to_moz(M.expression), + optional: M.optional, + arguments: M.args.map(to_moz) + }; + }); + + def_to_moz(AST_Toplevel, function To_Moz_Program(M) { + return to_moz_scope("Program", M); + }); + + def_to_moz(AST_Expansion, function To_Moz_Spread(M) { + return { + type: to_moz_in_destructuring() ? "RestElement" : "SpreadElement", + argument: to_moz(M.expression) + }; + }); + + def_to_moz(AST_PrefixedTemplateString, function To_Moz_TaggedTemplateExpression(M) { + return { + type: "TaggedTemplateExpression", + tag: to_moz(M.prefix), + quasi: to_moz(M.template_string) + }; + }); + + def_to_moz(AST_TemplateString, function To_Moz_TemplateLiteral(M) { + var quasis = []; + var expressions = []; + for (var i = 0; i < M.segments.length; i++) { + if (i % 2 !== 0) { + expressions.push(to_moz(M.segments[i])); + } else { + quasis.push({ + type: "TemplateElement", + value: { + raw: M.segments[i].raw, + cooked: M.segments[i].value + }, + tail: i === M.segments.length - 1 + }); + } + } + return { + type: "TemplateLiteral", + quasis: quasis, + expressions: expressions + }; + }); + + def_to_moz(AST_Defun, function To_Moz_FunctionDeclaration(M) { + return { + type: "FunctionDeclaration", + id: to_moz(M.name), + params: M.argnames.map(to_moz), + generator: M.is_generator, + async: M.async, + body: to_moz_scope("BlockStatement", M) + }; + }); + + def_to_moz(AST_Function, function To_Moz_FunctionExpression(M, parent) { + var is_generator = parent.is_generator !== undefined ? + parent.is_generator : M.is_generator; + return { + type: "FunctionExpression", + id: to_moz(M.name), + params: M.argnames.map(to_moz), + generator: is_generator, + async: M.async, + body: to_moz_scope("BlockStatement", M) + }; + }); + + def_to_moz(AST_Arrow, function To_Moz_ArrowFunctionExpression(M) { + var body = { + type: "BlockStatement", + body: M.body.map(to_moz) + }; + return { + type: "ArrowFunctionExpression", + params: M.argnames.map(to_moz), + async: M.async, + body: body + }; + }); + + def_to_moz(AST_Destructuring, function To_Moz_ObjectPattern(M) { + if (M.is_array) { + return { + type: "ArrayPattern", + elements: M.names.map(to_moz) + }; + } + return { + type: "ObjectPattern", + properties: M.names.map(to_moz) + }; + }); + + def_to_moz(AST_Directive, function To_Moz_Directive(M) { + return { + type: "ExpressionStatement", + expression: { + type: "Literal", + value: M.value, + raw: M.print_to_string() + }, + directive: M.value + }; + }); + + def_to_moz(AST_SimpleStatement, function To_Moz_ExpressionStatement(M) { + return { + type: "ExpressionStatement", + expression: to_moz(M.body) + }; + }); + + def_to_moz(AST_SwitchBranch, function To_Moz_SwitchCase(M) { + return { + type: "SwitchCase", + test: to_moz(M.expression), + consequent: M.body.map(to_moz) + }; + }); + + def_to_moz(AST_Try, function To_Moz_TryStatement(M) { + return { + type: "TryStatement", + block: to_moz_block(M.body), + handler: to_moz(M.bcatch), + guardedHandlers: [], + finalizer: to_moz(M.bfinally) + }; + }); + + def_to_moz(AST_Catch, function To_Moz_CatchClause(M) { + return { + type: "CatchClause", + param: to_moz(M.argname), + guard: null, + body: to_moz_block(M) + }; + }); + + def_to_moz(AST_Definitions, function To_Moz_VariableDeclaration(M) { + return { + type: "VariableDeclaration", + kind: + M instanceof AST_Const ? "const" : + M instanceof AST_Let ? "let" : "var", + declarations: M.definitions.map(to_moz) + }; + }); + + const assert_clause_to_moz = assert_clause => { + const assertions = []; + if (assert_clause) { + for (const { key, value } of assert_clause.properties) { + const key_moz = is_basic_identifier_string(key) + ? { type: "Identifier", name: key } + : { type: "Literal", value: key, raw: JSON.stringify(key) }; + assertions.push({ + type: "ImportAttribute", + key: key_moz, + value: to_moz(value) + }); + } + } + return assertions; + }; + + def_to_moz(AST_Export, function To_Moz_ExportDeclaration(M) { + if (M.exported_names) { + var first_exported = M.exported_names[0]; + var first_exported_name = first_exported.name; + if (first_exported_name.name === "*" && !first_exported_name.quote) { + var foreign_name = first_exported.foreign_name; + var exported = foreign_name.name === "*" && !foreign_name.quote + ? null + : to_moz(foreign_name); + return { + type: "ExportAllDeclaration", + source: to_moz(M.module_name), + exported: exported, + assertions: assert_clause_to_moz(M.assert_clause) + }; + } + return { + type: "ExportNamedDeclaration", + specifiers: M.exported_names.map(function (name_mapping) { + return { + type: "ExportSpecifier", + exported: to_moz(name_mapping.foreign_name), + local: to_moz(name_mapping.name) + }; + }), + declaration: to_moz(M.exported_definition), + source: to_moz(M.module_name), + assertions: assert_clause_to_moz(M.assert_clause) + }; + } + return { + type: M.is_default ? "ExportDefaultDeclaration" : "ExportNamedDeclaration", + declaration: to_moz(M.exported_value || M.exported_definition) + }; + }); + + def_to_moz(AST_Import, function To_Moz_ImportDeclaration(M) { + var specifiers = []; + if (M.imported_name) { + specifiers.push({ + type: "ImportDefaultSpecifier", + local: to_moz(M.imported_name) + }); + } + if (M.imported_names) { + var first_imported_foreign_name = M.imported_names[0].foreign_name; + if (first_imported_foreign_name.name === "*" && !first_imported_foreign_name.quote) { + specifiers.push({ + type: "ImportNamespaceSpecifier", + local: to_moz(M.imported_names[0].name) + }); + } else { + M.imported_names.forEach(function(name_mapping) { + specifiers.push({ + type: "ImportSpecifier", + local: to_moz(name_mapping.name), + imported: to_moz(name_mapping.foreign_name) + }); + }); + } + } + return { + type: "ImportDeclaration", + specifiers: specifiers, + source: to_moz(M.module_name), + assertions: assert_clause_to_moz(M.assert_clause) + }; + }); + + def_to_moz(AST_ImportMeta, function To_Moz_MetaProperty() { + return { + type: "MetaProperty", + meta: { + type: "Identifier", + name: "import" + }, + property: { + type: "Identifier", + name: "meta" + } + }; + }); + + def_to_moz(AST_Sequence, function To_Moz_SequenceExpression(M) { + return { + type: "SequenceExpression", + expressions: M.expressions.map(to_moz) + }; + }); + + def_to_moz(AST_DotHash, function To_Moz_PrivateMemberExpression(M) { + return { + type: "MemberExpression", + object: to_moz(M.expression), + computed: false, + property: { + type: "PrivateIdentifier", + name: M.property + }, + optional: M.optional + }; + }); + + def_to_moz(AST_PropAccess, function To_Moz_MemberExpression(M) { + var isComputed = M instanceof AST_Sub; + return { + type: "MemberExpression", + object: to_moz(M.expression), + computed: isComputed, + property: isComputed ? to_moz(M.property) : {type: "Identifier", name: M.property}, + optional: M.optional + }; + }); + + def_to_moz(AST_Chain, function To_Moz_ChainExpression(M) { + return { + type: "ChainExpression", + expression: to_moz(M.expression) + }; + }); + + def_to_moz(AST_Unary, function To_Moz_Unary(M) { + return { + type: M.operator == "++" || M.operator == "--" ? "UpdateExpression" : "UnaryExpression", + operator: M.operator, + prefix: M instanceof AST_UnaryPrefix, + argument: to_moz(M.expression) + }; + }); + + def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) { + if (M.operator == "=" && to_moz_in_destructuring()) { + return { + type: "AssignmentPattern", + left: to_moz(M.left), + right: to_moz(M.right) + }; + } + + const type = M.operator == "&&" || M.operator == "||" || M.operator === "??" + ? "LogicalExpression" + : "BinaryExpression"; + + return { + type, + left: to_moz(M.left), + operator: M.operator, + right: to_moz(M.right) + }; + }); + + def_to_moz(AST_PrivateIn, function To_Moz_BinaryExpression_PrivateIn(M) { + return { + type: "BinaryExpression", + left: { type: "PrivateIdentifier", name: M.key.name }, + operator: "in", + right: to_moz(M.value), + }; + }); + + def_to_moz(AST_Array, function To_Moz_ArrayExpression(M) { + return { + type: "ArrayExpression", + elements: M.elements.map(to_moz) + }; + }); + + def_to_moz(AST_Object, function To_Moz_ObjectExpression(M) { + return { + type: "ObjectExpression", + properties: M.properties.map(to_moz) + }; + }); + + def_to_moz(AST_ObjectProperty, function To_Moz_Property(M, parent) { + var key = M.key instanceof AST_Node ? to_moz(M.key) : { + type: "Identifier", + value: M.key + }; + if (typeof M.key === "number") { + key = { + type: "Literal", + value: Number(M.key) + }; + } + if (typeof M.key === "string") { + key = { + type: "Identifier", + name: M.key + }; + } + var kind; + var string_or_num = typeof M.key === "string" || typeof M.key === "number"; + var computed = string_or_num ? false : !(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef; + if (M instanceof AST_ObjectKeyVal) { + kind = "init"; + computed = !string_or_num; + } else + if (M instanceof AST_ObjectGetter) { + kind = "get"; + } else + if (M instanceof AST_ObjectSetter) { + kind = "set"; + } + if (M instanceof AST_PrivateGetter || M instanceof AST_PrivateSetter) { + const kind = M instanceof AST_PrivateGetter ? "get" : "set"; + return { + type: "MethodDefinition", + computed: false, + kind: kind, + static: M.static, + key: { + type: "PrivateIdentifier", + name: M.key.name + }, + value: to_moz(M.value) + }; + } + if (M instanceof AST_ClassPrivateProperty) { + return { + type: "PropertyDefinition", + key: { + type: "PrivateIdentifier", + name: M.key.name + }, + value: to_moz(M.value), + computed: false, + static: M.static + }; + } + if (M instanceof AST_ClassProperty) { + return { + type: "PropertyDefinition", + key, + value: to_moz(M.value), + computed, + static: M.static + }; + } + if (parent instanceof AST_Class) { + return { + type: "MethodDefinition", + computed: computed, + kind: kind, + static: M.static, + key: to_moz(M.key), + value: to_moz(M.value) + }; + } + return { + type: "Property", + computed: computed, + kind: kind, + key: key, + value: to_moz(M.value) + }; + }); + + def_to_moz(AST_ConciseMethod, function To_Moz_MethodDefinition(M, parent) { + if (parent instanceof AST_Object) { + return { + type: "Property", + computed: !(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef, + kind: "init", + method: true, + shorthand: false, + key: to_moz(M.key), + value: to_moz(M.value) + }; + } + + const key = M instanceof AST_PrivateMethod + ? { + type: "PrivateIdentifier", + name: M.key.name + } + : to_moz(M.key); + + return { + type: "MethodDefinition", + kind: M.key === "constructor" ? "constructor" : "method", + key, + value: to_moz(M.value), + computed: !(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef, + static: M.static, + }; + }); + + def_to_moz(AST_Class, function To_Moz_Class(M) { + var type = M instanceof AST_ClassExpression ? "ClassExpression" : "ClassDeclaration"; + return { + type: type, + superClass: to_moz(M.extends), + id: M.name ? to_moz(M.name) : null, + body: { + type: "ClassBody", + body: M.properties.map(to_moz) + } + }; + }); + + def_to_moz(AST_ClassStaticBlock, function To_Moz_StaticBlock(M) { + return { + type: "StaticBlock", + body: M.body.map(to_moz), + }; + }); + + def_to_moz(AST_NewTarget, function To_Moz_MetaProperty() { + return { + type: "MetaProperty", + meta: { + type: "Identifier", + name: "new" + }, + property: { + type: "Identifier", + name: "target" + } + }; + }); + + def_to_moz(AST_Symbol, function To_Moz_Identifier(M, parent) { + if ( + (M instanceof AST_SymbolMethod && parent.quote) || + (( + M instanceof AST_SymbolImportForeign || + M instanceof AST_SymbolExportForeign || + M instanceof AST_SymbolExport + ) && M.quote) + ) { + return { + type: "Literal", + value: M.name + }; + } + var def = M.definition(); + return { + type: "Identifier", + name: def ? def.mangled_name || def.name : M.name + }; + }); + + def_to_moz(AST_RegExp, function To_Moz_RegExpLiteral(M) { + const pattern = M.value.source; + const flags = M.value.flags; + return { + type: "Literal", + value: null, + raw: M.print_to_string(), + regex: { pattern, flags } + }; + }); + + def_to_moz(AST_Constant, function To_Moz_Literal(M) { + var value = M.value; + return { + type: "Literal", + value: value, + raw: M.raw || M.print_to_string() + }; + }); + + def_to_moz(AST_Atom, function To_Moz_Atom(M) { + return { + type: "Identifier", + name: String(M.value) + }; + }); + + def_to_moz(AST_BigInt, M => ({ + type: "Literal", + // value cannot be represented natively + // see: https://github.com/estree/estree/blob/master/es2020.md#bigintliteral + value: null, + // `M.value` is a string that may be a hex number representation. + // but "bigint" property should have only decimal digits + bigint: typeof BigInt === "function" ? BigInt(M.value).toString() : M.value, + })); + + AST_Boolean.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast); + AST_Null.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast); + AST_Hole.DEFMETHOD("to_mozilla_ast", function To_Moz_ArrayHole() { return null; }); + + AST_Block.DEFMETHOD("to_mozilla_ast", AST_BlockStatement.prototype.to_mozilla_ast); + AST_Lambda.DEFMETHOD("to_mozilla_ast", AST_Function.prototype.to_mozilla_ast); + + /* -----[ tools ]----- */ + + function my_start_token(moznode) { + var loc = moznode.loc, start = loc && loc.start; + var range = moznode.range; + return new AST_Token( + "", + "", + start && start.line || 0, + start && start.column || 0, + range ? range [0] : moznode.start, + false, + [], + [], + loc && loc.source, + ); + } + + function my_end_token(moznode) { + var loc = moznode.loc, end = loc && loc.end; + var range = moznode.range; + return new AST_Token( + "", + "", + end && end.line || 0, + end && end.column || 0, + range ? range [0] : moznode.end, + false, + [], + [], + loc && loc.source, + ); + } + + var FROM_MOZ_STACK = null; + + function from_moz(node) { + FROM_MOZ_STACK.push(node); + var ret = node != null ? MOZ_TO_ME[node.type](node) : null; + FROM_MOZ_STACK.pop(); + return ret; + } + + AST_Node.from_mozilla_ast = function(node) { + var save_stack = FROM_MOZ_STACK; + FROM_MOZ_STACK = []; + var ast = from_moz(node); + FROM_MOZ_STACK = save_stack; + return ast; + }; + + function set_moz_loc(mynode, moznode) { + var start = mynode.start; + var end = mynode.end; + if (!(start && end)) { + return moznode; + } + if (start.pos != null && end.endpos != null) { + moznode.range = [start.pos, end.endpos]; + } + if (start.line) { + moznode.loc = { + start: {line: start.line, column: start.col}, + end: end.endline ? {line: end.endline, column: end.endcol} : null + }; + if (start.file) { + moznode.loc.source = start.file; + } + } + return moznode; + } + + function def_to_moz(mytype, handler) { + mytype.DEFMETHOD("to_mozilla_ast", function(parent) { + return set_moz_loc(this, handler(this, parent)); + }); + } + + var TO_MOZ_STACK = null; + + function to_moz(node) { + if (TO_MOZ_STACK === null) { TO_MOZ_STACK = []; } + TO_MOZ_STACK.push(node); + var ast = node != null ? node.to_mozilla_ast(TO_MOZ_STACK[TO_MOZ_STACK.length - 2]) : null; + TO_MOZ_STACK.pop(); + if (TO_MOZ_STACK.length === 0) { TO_MOZ_STACK = null; } + return ast; + } + + function to_moz_in_destructuring() { + var i = TO_MOZ_STACK.length; + while (i--) { + if (TO_MOZ_STACK[i] instanceof AST_Destructuring) { + return true; + } + } + return false; + } + + function to_moz_block(node) { + return { + type: "BlockStatement", + body: node.body.map(to_moz) + }; + } + + function to_moz_scope(type, node) { + var body = node.body.map(to_moz); + if (node.body[0] instanceof AST_SimpleStatement && node.body[0].body instanceof AST_String) { + body.unshift(to_moz(new AST_EmptyStatement(node.body[0]))); + } + return { + type: type, + body: body + }; + } +})(); diff --git a/node_modules/terser/lib/output.js b/node_modules/terser/lib/output.js new file mode 100644 index 0000000..8168c75 --- /dev/null +++ b/node_modules/terser/lib/output.js @@ -0,0 +1,2528 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +import { + defaults, + makePredicate, + noop, + regexp_source_fix, + sort_regexp_flags, + return_false, + return_true, +} from "./utils/index.js"; +import { first_in_statement, left_is_object } from "./utils/first_in_statement.js"; +import { + AST_Array, + AST_Arrow, + AST_Assign, + AST_Await, + AST_BigInt, + AST_Binary, + AST_BlockStatement, + AST_Break, + AST_Call, + AST_Case, + AST_Catch, + AST_Chain, + AST_Class, + AST_ClassExpression, + AST_ClassPrivateProperty, + AST_ClassProperty, + AST_ClassStaticBlock, + AST_ConciseMethod, + AST_PrivateGetter, + AST_PrivateMethod, + AST_SymbolPrivateProperty, + AST_PrivateSetter, + AST_PrivateIn, + AST_Conditional, + AST_Const, + AST_Constant, + AST_Continue, + AST_Debugger, + AST_Default, + AST_DefaultAssign, + AST_Definitions, + AST_Defun, + AST_Destructuring, + AST_Directive, + AST_Do, + AST_Dot, + AST_DotHash, + AST_EmptyStatement, + AST_Exit, + AST_Expansion, + AST_Export, + AST_Finally, + AST_For, + AST_ForIn, + AST_ForOf, + AST_Function, + AST_Hole, + AST_If, + AST_Import, + AST_ImportMeta, + AST_Jump, + AST_LabeledStatement, + AST_Lambda, + AST_Let, + AST_LoopControl, + AST_NameMapping, + AST_New, + AST_NewTarget, + AST_Node, + AST_Number, + AST_Object, + AST_ObjectGetter, + AST_ObjectKeyVal, + AST_ObjectProperty, + AST_ObjectSetter, + AST_PrefixedTemplateString, + AST_PropAccess, + AST_RegExp, + AST_Return, + AST_Scope, + AST_Sequence, + AST_SimpleStatement, + AST_Statement, + AST_StatementWithBody, + AST_String, + AST_Sub, + AST_Super, + AST_Switch, + AST_SwitchBranch, + AST_Symbol, + AST_SymbolClassProperty, + AST_SymbolMethod, + AST_SymbolRef, + AST_TemplateSegment, + AST_TemplateString, + AST_This, + AST_Throw, + AST_Toplevel, + AST_Try, + AST_TryBlock, + AST_Unary, + AST_UnaryPostfix, + AST_UnaryPrefix, + AST_Var, + AST_VarDef, + AST_While, + AST_With, + AST_Yield, + TreeWalker, + walk, + walk_abort +} from "./ast.js"; +import { + get_full_char_code, + get_full_char, + is_identifier_char, + is_basic_identifier_string, + is_identifier_string, + PRECEDENCE, + ALL_RESERVED_WORDS, +} from "./parse.js"; + +const CODE_LINE_BREAK = 10; +const CODE_SPACE = 32; + +const r_annotation = /[@#]__(PURE|INLINE|NOINLINE)__/; + +function is_some_comments(comment) { + // multiline comment + return ( + (comment.type === "comment2" || comment.type === "comment1") + && /@preserve|@copyright|@lic|@cc_on|^\**!/i.test(comment.value) + ); +} + +const ROPE_COMMIT_WHEN = 8 * 1000; +class Rope { + constructor() { + this.committed = ""; + this.current = ""; + } + + append(str) { + /** When `this.current` is too long, commit it. */ + if (this.current.length > ROPE_COMMIT_WHEN) { + this.committed += this.current + str; + this.current = ""; + } else { + this.current += str; + } + } + + insertAt(char, index) { + const { committed, current } = this; + if (index < committed.length) { + this.committed = committed.slice(0, index) + char + committed.slice(index); + } else if (index === committed.length) { + this.committed += char; + } else { + index -= committed.length; + this.committed += current.slice(0, index) + char; + this.current = current.slice(index); + } + } + + charAt(index) { + const { committed } = this; + if (index < committed.length) return committed[index]; + return this.current[index - committed.length]; + } + + charCodeAt(index) { + const { committed } = this; + if (index < committed.length) return committed.charCodeAt(index); + return this.current.charCodeAt(index - committed.length); + } + + length() { + return this.committed.length + this.current.length; + } + + expectDirective() { + // /^$|[;{][\s\n]*$/ + + let ch, n = this.length(); + + if (n <= 0) return true; + + // Skip N whitespace from the end + while ( + (ch = this.charCodeAt(--n)) + && (ch == CODE_SPACE || ch == CODE_LINE_BREAK) + ); + + // either ";", or "{", or the string ended + return !ch || ch === 59 || ch === 123; + } + + hasNLB() { + let n = this.length() - 1; + while (n >= 0) { + const code = this.charCodeAt(n--); + + if (code === CODE_LINE_BREAK) return true; + if (code !== CODE_SPACE) return false; + } + return true; + } + + + toString() { + return this.committed + this.current; + } +} + +function OutputStream(options) { + + var readonly = !options; + options = defaults(options, { + ascii_only : false, + beautify : false, + braces : false, + comments : "some", + ecma : 5, + ie8 : false, + indent_level : 4, + indent_start : 0, + inline_script : true, + keep_numbers : false, + keep_quoted_props : false, + max_line_len : false, + preamble : null, + preserve_annotations : false, + quote_keys : false, + quote_style : 0, + safari10 : false, + semicolons : true, + shebang : true, + shorthand : undefined, + source_map : null, + webkit : false, + width : 80, + wrap_iife : false, + wrap_func_args : true, + + _destroy_ast : false + }, true); + + if (options.shorthand === undefined) + options.shorthand = options.ecma > 5; + + // Convert comment option to RegExp if necessary and set up comments filter + var comment_filter = return_false; // Default case, throw all comments away + if (options.comments) { + let comments = options.comments; + if (typeof options.comments === "string" && /^\/.*\/[a-zA-Z]*$/.test(options.comments)) { + var regex_pos = options.comments.lastIndexOf("/"); + comments = new RegExp( + options.comments.substr(1, regex_pos - 1), + options.comments.substr(regex_pos + 1) + ); + } + if (comments instanceof RegExp) { + comment_filter = function(comment) { + return comment.type != "comment5" && comments.test(comment.value); + }; + } else if (typeof comments === "function") { + comment_filter = function(comment) { + return comment.type != "comment5" && comments(this, comment); + }; + } else if (comments === "some") { + comment_filter = is_some_comments; + } else { // NOTE includes "all" option + comment_filter = return_true; + } + } + + if (options.preserve_annotations) { + let prev_comment_filter = comment_filter; + comment_filter = function (comment) { + return r_annotation.test(comment.value) || prev_comment_filter.apply(this, arguments); + }; + } + + var indentation = 0; + var current_col = 0; + var current_line = 1; + var current_pos = 0; + var OUTPUT = new Rope(); + let printed_comments = new Set(); + + var to_utf8 = options.ascii_only ? function(str, identifier = false, regexp = false) { + if (options.ecma >= 2015 && !options.safari10 && !regexp) { + str = str.replace(/[\ud800-\udbff][\udc00-\udfff]/g, function(ch) { + var code = get_full_char_code(ch, 0).toString(16); + return "\\u{" + code + "}"; + }); + } + return str.replace(/[\u0000-\u001f\u007f-\uffff]/g, function(ch) { + var code = ch.charCodeAt(0).toString(16); + if (code.length <= 2 && !identifier) { + while (code.length < 2) code = "0" + code; + return "\\x" + code; + } else { + while (code.length < 4) code = "0" + code; + return "\\u" + code; + } + }); + } : function(str) { + return str.replace(/[\ud800-\udbff][\udc00-\udfff]|([\ud800-\udbff]|[\udc00-\udfff])/g, function(match, lone) { + if (lone) { + return "\\u" + lone.charCodeAt(0).toString(16); + } + return match; + }); + }; + + function make_string(str, quote) { + var dq = 0, sq = 0; + str = str.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g, + function(s, i) { + switch (s) { + case '"': ++dq; return '"'; + case "'": ++sq; return "'"; + case "\\": return "\\\\"; + case "\n": return "\\n"; + case "\r": return "\\r"; + case "\t": return "\\t"; + case "\b": return "\\b"; + case "\f": return "\\f"; + case "\x0B": return options.ie8 ? "\\x0B" : "\\v"; + case "\u2028": return "\\u2028"; + case "\u2029": return "\\u2029"; + case "\ufeff": return "\\ufeff"; + case "\0": + return /[0-9]/.test(get_full_char(str, i+1)) ? "\\x00" : "\\0"; + } + return s; + }); + function quote_single() { + return "'" + str.replace(/\x27/g, "\\'") + "'"; + } + function quote_double() { + return '"' + str.replace(/\x22/g, '\\"') + '"'; + } + function quote_template() { + return "`" + str.replace(/`/g, "\\`") + "`"; + } + str = to_utf8(str); + if (quote === "`") return quote_template(); + switch (options.quote_style) { + case 1: + return quote_single(); + case 2: + return quote_double(); + case 3: + return quote == "'" ? quote_single() : quote_double(); + default: + return dq > sq ? quote_single() : quote_double(); + } + } + + function encode_string(str, quote) { + var ret = make_string(str, quote); + if (options.inline_script) { + ret = ret.replace(/<\x2f(script)([>\/\t\n\f\r ])/gi, "<\\/$1$2"); + ret = ret.replace(/\x3c!--/g, "\\x3c!--"); + ret = ret.replace(/--\x3e/g, "--\\x3e"); + } + return ret; + } + + function make_name(name) { + name = name.toString(); + name = to_utf8(name, true); + return name; + } + + function make_indent(back) { + return " ".repeat(options.indent_start + indentation - back * options.indent_level); + } + + /* -----[ beautification/minification ]----- */ + + var has_parens = false; + var might_need_space = false; + var might_need_semicolon = false; + var might_add_newline = 0; + var need_newline_indented = false; + var need_space = false; + var newline_insert = -1; + var last = ""; + var mapping_token, mapping_name, mappings = options.source_map && []; + + var do_add_mapping = mappings ? function() { + mappings.forEach(function(mapping) { + try { + let { name, token } = mapping; + if (name !== false) { + if (token.type == "name" || token.type === "privatename") { + name = token.value; + } else if (name instanceof AST_Symbol) { + name = token.type === "string" ? token.value : name.name; + } + } + options.source_map.add( + mapping.token.file, + mapping.line, mapping.col, + mapping.token.line, mapping.token.col, + is_basic_identifier_string(name) ? name : undefined + ); + } catch(ex) { + // Ignore bad mapping + } + }); + mappings = []; + } : noop; + + var ensure_line_len = options.max_line_len ? function() { + if (current_col > options.max_line_len) { + if (might_add_newline) { + OUTPUT.insertAt("\n", might_add_newline); + const len_after_newline = OUTPUT.length() - might_add_newline - 1; + if (mappings) { + var delta = len_after_newline - current_col; + mappings.forEach(function(mapping) { + mapping.line++; + mapping.col += delta; + }); + } + current_line++; + current_pos++; + current_col = len_after_newline; + } + } + if (might_add_newline) { + might_add_newline = 0; + do_add_mapping(); + } + } : noop; + + var requireSemicolonChars = makePredicate("( [ + * / - , . `"); + + function print(str) { + str = String(str); + var ch = get_full_char(str, 0); + if (need_newline_indented && ch) { + need_newline_indented = false; + if (ch !== "\n") { + print("\n"); + indent(); + } + } + if (need_space && ch) { + need_space = false; + if (!/[\s;})]/.test(ch)) { + space(); + } + } + newline_insert = -1; + var prev = last.charAt(last.length - 1); + if (might_need_semicolon) { + might_need_semicolon = false; + + if (prev === ":" && ch === "}" || (!ch || !";}".includes(ch)) && prev !== ";") { + if (options.semicolons || requireSemicolonChars.has(ch)) { + OUTPUT.append(";"); + current_col++; + current_pos++; + } else { + ensure_line_len(); + if (current_col > 0) { + OUTPUT.append("\n"); + current_pos++; + current_line++; + current_col = 0; + } + + if (/^\s+$/.test(str)) { + // reset the semicolon flag, since we didn't print one + // now and might still have to later + might_need_semicolon = true; + } + } + + if (!options.beautify) + might_need_space = false; + } + } + + if (might_need_space) { + if ((is_identifier_char(prev) + && (is_identifier_char(ch) || ch == "\\")) + || (ch == "/" && ch == prev) + || ((ch == "+" || ch == "-") && ch == last) + ) { + OUTPUT.append(" "); + current_col++; + current_pos++; + } + might_need_space = false; + } + + if (mapping_token) { + mappings.push({ + token: mapping_token, + name: mapping_name, + line: current_line, + col: current_col + }); + mapping_token = false; + if (!might_add_newline) do_add_mapping(); + } + + OUTPUT.append(str); + has_parens = str[str.length - 1] == "("; + current_pos += str.length; + var a = str.split(/\r?\n/), n = a.length - 1; + current_line += n; + current_col += a[0].length; + if (n > 0) { + ensure_line_len(); + current_col = a[n].length; + } + last = str; + } + + var star = function() { + print("*"); + }; + + var space = options.beautify ? function() { + print(" "); + } : function() { + might_need_space = true; + }; + + var indent = options.beautify ? function(half) { + if (options.beautify) { + print(make_indent(half ? 0.5 : 0)); + } + } : noop; + + var with_indent = options.beautify ? function(col, cont) { + if (col === true) col = next_indent(); + var save_indentation = indentation; + indentation = col; + var ret = cont(); + indentation = save_indentation; + return ret; + } : function(col, cont) { return cont(); }; + + var newline = options.beautify ? function() { + if (newline_insert < 0) return print("\n"); + if (OUTPUT.charAt(newline_insert) != "\n") { + OUTPUT.insertAt("\n", newline_insert); + current_pos++; + current_line++; + } + newline_insert++; + } : options.max_line_len ? function() { + ensure_line_len(); + might_add_newline = OUTPUT.length(); + } : noop; + + var semicolon = options.beautify ? function() { + print(";"); + } : function() { + might_need_semicolon = true; + }; + + function force_semicolon() { + might_need_semicolon = false; + print(";"); + } + + function next_indent() { + return indentation + options.indent_level; + } + + function with_block(cont) { + var ret; + print("{"); + newline(); + with_indent(next_indent(), function() { + ret = cont(); + }); + indent(); + print("}"); + return ret; + } + + function with_parens(cont) { + print("("); + //XXX: still nice to have that for argument lists + //var ret = with_indent(current_col, cont); + var ret = cont(); + print(")"); + return ret; + } + + function with_square(cont) { + print("["); + //var ret = with_indent(current_col, cont); + var ret = cont(); + print("]"); + return ret; + } + + function comma() { + print(","); + space(); + } + + function colon() { + print(":"); + space(); + } + + var add_mapping = mappings ? function(token, name) { + mapping_token = token; + mapping_name = name; + } : noop; + + function get() { + if (might_add_newline) { + ensure_line_len(); + } + return OUTPUT.toString(); + } + + function filter_comment(comment) { + if (!options.preserve_annotations) { + comment = comment.replace(r_annotation, " "); + } + if (/^\s*$/.test(comment)) { + return ""; + } + return comment.replace(/(<\s*\/\s*)(script)/i, "<\\/$2"); + } + + function prepend_comments(node) { + var self = this; + var start = node.start; + if (!start) return; + var printed_comments = self.printed_comments; + + // There cannot be a newline between return/yield and its value. + const keyword_with_value = + node instanceof AST_Exit && node.value + || (node instanceof AST_Await || node instanceof AST_Yield) + && node.expression; + + if ( + start.comments_before + && printed_comments.has(start.comments_before) + ) { + if (keyword_with_value) { + start.comments_before = []; + } else { + return; + } + } + + var comments = start.comments_before; + if (!comments) { + comments = start.comments_before = []; + } + printed_comments.add(comments); + + if (keyword_with_value) { + var tw = new TreeWalker(function(node) { + var parent = tw.parent(); + if (parent instanceof AST_Exit + || parent instanceof AST_Await + || parent instanceof AST_Yield + || parent instanceof AST_Binary && parent.left === node + || parent.TYPE == "Call" && parent.expression === node + || parent instanceof AST_Conditional && parent.condition === node + || parent instanceof AST_Dot && parent.expression === node + || parent instanceof AST_Sequence && parent.expressions[0] === node + || parent instanceof AST_Sub && parent.expression === node + || parent instanceof AST_UnaryPostfix) { + if (!node.start) return; + var text = node.start.comments_before; + if (text && !printed_comments.has(text)) { + printed_comments.add(text); + comments = comments.concat(text); + } + } else { + return true; + } + }); + tw.push(node); + keyword_with_value.walk(tw); + } + + if (current_pos == 0) { + if (comments.length > 0 && options.shebang && comments[0].type === "comment5" + && !printed_comments.has(comments[0])) { + print("#!" + comments.shift().value + "\n"); + indent(); + } + var preamble = options.preamble; + if (preamble) { + print(preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n")); + } + } + + comments = comments.filter(comment_filter, node).filter(c => !printed_comments.has(c)); + if (comments.length == 0) return; + var last_nlb = OUTPUT.hasNLB(); + comments.forEach(function(c, i) { + printed_comments.add(c); + if (!last_nlb) { + if (c.nlb) { + print("\n"); + indent(); + last_nlb = true; + } else if (i > 0) { + space(); + } + } + + if (/comment[134]/.test(c.type)) { + var value = filter_comment(c.value); + if (value) { + print("//" + value + "\n"); + indent(); + } + last_nlb = true; + } else if (c.type == "comment2") { + var value = filter_comment(c.value); + if (value) { + print("/*" + value + "*/"); + } + last_nlb = false; + } + }); + if (!last_nlb) { + if (start.nlb) { + print("\n"); + indent(); + } else { + space(); + } + } + } + + function append_comments(node, tail) { + var self = this; + var token = node.end; + if (!token) return; + var printed_comments = self.printed_comments; + var comments = token[tail ? "comments_before" : "comments_after"]; + if (!comments || printed_comments.has(comments)) return; + if (!(node instanceof AST_Statement || comments.every((c) => + !/comment[134]/.test(c.type) + ))) return; + printed_comments.add(comments); + var insert = OUTPUT.length(); + comments.filter(comment_filter, node).forEach(function(c, i) { + if (printed_comments.has(c)) return; + printed_comments.add(c); + need_space = false; + if (need_newline_indented) { + print("\n"); + indent(); + need_newline_indented = false; + } else if (c.nlb && (i > 0 || !OUTPUT.hasNLB())) { + print("\n"); + indent(); + } else if (i > 0 || !tail) { + space(); + } + if (/comment[134]/.test(c.type)) { + const value = filter_comment(c.value); + if (value) { + print("//" + value); + } + need_newline_indented = true; + } else if (c.type == "comment2") { + const value = filter_comment(c.value); + if (value) { + print("/*" + value + "*/"); + } + need_space = true; + } + }); + if (OUTPUT.length() > insert) newline_insert = insert; + } + + /** + * When output.option("_destroy_ast") is enabled, destroy the function. + * Call this after printing it. + */ + const gc_scope = + options["_destroy_ast"] + ? function gc_scope(scope) { + scope.body.length = 0; + scope.argnames.length = 0; + } + : noop; + + var stack = []; + return { + get : get, + toString : get, + indent : indent, + in_directive : false, + use_asm : null, + active_scope : null, + indentation : function() { return indentation; }, + current_width : function() { return current_col - indentation; }, + should_break : function() { return options.width && this.current_width() >= options.width; }, + has_parens : function() { return has_parens; }, + newline : newline, + print : print, + star : star, + space : space, + comma : comma, + colon : colon, + last : function() { return last; }, + semicolon : semicolon, + force_semicolon : force_semicolon, + to_utf8 : to_utf8, + print_name : function(name) { print(make_name(name)); }, + print_string : function(str, quote, escape_directive) { + var encoded = encode_string(str, quote); + if (escape_directive === true && !encoded.includes("\\")) { + // Insert semicolons to break directive prologue + if (!OUTPUT.expectDirective()) { + force_semicolon(); + } + force_semicolon(); + } + print(encoded); + }, + print_template_string_chars: function(str) { + var encoded = encode_string(str, "`").replace(/\${/g, "\\${"); + return print(encoded.substr(1, encoded.length - 2)); + }, + encode_string : encode_string, + next_indent : next_indent, + with_indent : with_indent, + with_block : with_block, + with_parens : with_parens, + with_square : with_square, + add_mapping : add_mapping, + option : function(opt) { return options[opt]; }, + gc_scope, + printed_comments: printed_comments, + prepend_comments: readonly ? noop : prepend_comments, + append_comments : readonly || comment_filter === return_false ? noop : append_comments, + line : function() { return current_line; }, + col : function() { return current_col; }, + pos : function() { return current_pos; }, + push_node : function(node) { stack.push(node); }, + pop_node : function() { return stack.pop(); }, + parent : function(n) { + return stack[stack.length - 2 - (n || 0)]; + } + }; + +} + +/* -----[ code generators ]----- */ + +(function() { + + /* -----[ utils ]----- */ + + function DEFPRINT(nodetype, generator) { + nodetype.DEFMETHOD("_codegen", generator); + } + + AST_Node.DEFMETHOD("print", function(output, force_parens) { + var self = this, generator = self._codegen; + if (self instanceof AST_Scope) { + output.active_scope = self; + } else if (!output.use_asm && self instanceof AST_Directive && self.value == "use asm") { + output.use_asm = output.active_scope; + } + function doit() { + output.prepend_comments(self); + self.add_source_map(output); + generator(self, output); + output.append_comments(self); + } + output.push_node(self); + if (force_parens || self.needs_parens(output)) { + output.with_parens(doit); + } else { + doit(); + } + output.pop_node(); + if (self === output.use_asm) { + output.use_asm = null; + } + }); + AST_Node.DEFMETHOD("_print", AST_Node.prototype.print); + + AST_Node.DEFMETHOD("print_to_string", function(options) { + var output = OutputStream(options); + this.print(output); + return output.get(); + }); + + /* -----[ PARENTHESES ]----- */ + + function PARENS(nodetype, func) { + if (Array.isArray(nodetype)) { + nodetype.forEach(function(nodetype) { + PARENS(nodetype, func); + }); + } else { + nodetype.DEFMETHOD("needs_parens", func); + } + } + + PARENS(AST_Node, return_false); + + // a function expression needs parens around it when it's provably + // the first token to appear in a statement. + PARENS(AST_Function, function(output) { + if (!output.has_parens() && first_in_statement(output)) { + return true; + } + + if (output.option("webkit")) { + var p = output.parent(); + if (p instanceof AST_PropAccess && p.expression === this) { + return true; + } + } + + if (output.option("wrap_iife")) { + var p = output.parent(); + if (p instanceof AST_Call && p.expression === this) { + return true; + } + } + + if (output.option("wrap_func_args")) { + var p = output.parent(); + if (p instanceof AST_Call && p.args.includes(this)) { + return true; + } + } + + return false; + }); + + PARENS(AST_Arrow, function(output) { + var p = output.parent(); + + if ( + output.option("wrap_func_args") + && p instanceof AST_Call + && p.args.includes(this) + ) { + return true; + } + return p instanceof AST_PropAccess && p.expression === this + || p instanceof AST_Conditional && p.condition === this; + }); + + // same goes for an object literal (as in AST_Function), because + // otherwise {...} would be interpreted as a block of code. + PARENS(AST_Object, function(output) { + return !output.has_parens() && first_in_statement(output); + }); + + PARENS(AST_ClassExpression, first_in_statement); + + PARENS(AST_Unary, function(output) { + var p = output.parent(); + return p instanceof AST_PropAccess && p.expression === this + || p instanceof AST_Call && p.expression === this + || p instanceof AST_Binary + && p.operator === "**" + && this instanceof AST_UnaryPrefix + && p.left === this + && this.operator !== "++" + && this.operator !== "--"; + }); + + PARENS(AST_Await, function(output) { + var p = output.parent(); + return p instanceof AST_PropAccess && p.expression === this + || p instanceof AST_Call && p.expression === this + || p instanceof AST_Binary && p.operator === "**" && p.left === this + || output.option("safari10") && p instanceof AST_UnaryPrefix; + }); + + PARENS(AST_Sequence, function(output) { + var p = output.parent(); + return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4) + || p instanceof AST_Unary // !(foo, bar, baz) + || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8 + || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4 + || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2 + || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ] + || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2 + || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30) + * ==> 20 (side effect, set a := 10 and b := 20) */ + || p instanceof AST_Arrow // x => (x, x) + || p instanceof AST_DefaultAssign // x => (x = (0, function(){})) + || p instanceof AST_Expansion // [...(a, b)] + || p instanceof AST_ForOf && this === p.object // for (e of (foo, bar)) {} + || p instanceof AST_Yield // yield (foo, bar) + || p instanceof AST_Export // export default (foo, bar) + ; + }); + + PARENS(AST_Binary, function(output) { + var p = output.parent(); + // (foo && bar)() + if (p instanceof AST_Call && p.expression === this) + return true; + // typeof (foo && bar) + if (p instanceof AST_Unary) + return true; + // (foo && bar)["prop"], (foo && bar).prop + if (p instanceof AST_PropAccess && p.expression === this) + return true; + // this deals with precedence: 3 * (2 + 1) + if (p instanceof AST_Binary) { + const parent_op = p.operator; + const op = this.operator; + + // It is forbidden for ?? to be used with || or && without parens. + if (op === "??" && (parent_op === "||" || parent_op === "&&")) { + return true; + } + if (parent_op === "??" && (op === "||" || op === "&&")) { + return true; + } + + const pp = PRECEDENCE[parent_op]; + const sp = PRECEDENCE[op]; + if (pp > sp + || (pp == sp + && (this === p.right || parent_op == "**"))) { + return true; + } + } + if (p instanceof AST_PrivateIn) { + const op = this.operator; + + const pp = PRECEDENCE["in"]; + const sp = PRECEDENCE[op]; + if (pp > sp || (pp == sp && this === p.value)) { + return true; + } + } + }); + + PARENS(AST_PrivateIn, function(output) { + var p = output.parent(); + // (#x in this)() + if (p instanceof AST_Call && p.expression === this) { + return true; + } + // typeof (#x in this) + if (p instanceof AST_Unary) { + return true; + } + // (#x in this)["prop"], (#x in this).prop + if (p instanceof AST_PropAccess && p.expression === this) { + return true; + } + // same precedence as regular in operator + if (p instanceof AST_Binary) { + const parent_op = p.operator; + + const pp = PRECEDENCE[parent_op]; + const sp = PRECEDENCE["in"]; + if (pp > sp + || (pp == sp + && (this === p.right || parent_op == "**"))) { + return true; + } + } + // rules are the same as binary in, but the class differs + if (p instanceof AST_PrivateIn && this === p.value) { + return true; + } + }); + + PARENS(AST_Yield, function(output) { + var p = output.parent(); + // (yield 1) + (yield 2) + // a = yield 3 + if (p instanceof AST_Binary && p.operator !== "=") + return true; + // (yield 1)() + // new (yield 1)() + if (p instanceof AST_Call && p.expression === this) + return true; + // (yield 1) ? yield 2 : yield 3 + if (p instanceof AST_Conditional && p.condition === this) + return true; + // -(yield 4) + if (p instanceof AST_Unary) + return true; + // (yield x).foo + // (yield x)['foo'] + if (p instanceof AST_PropAccess && p.expression === this) + return true; + }); + + PARENS(AST_Chain, function(output) { + var p = output.parent(); + if (!(p instanceof AST_Call || p instanceof AST_PropAccess)) return false; + return p.expression === this; + }); + + PARENS(AST_PropAccess, function(output) { + var p = output.parent(); + if (p instanceof AST_New && p.expression === this) { + // i.e. new (foo.bar().baz) + // + // if there's one call into this subtree, then we need + // parens around it too, otherwise the call will be + // interpreted as passing the arguments to the upper New + // expression. + return walk(this, node => { + if (node instanceof AST_Scope) return true; + if (node instanceof AST_Call) { + return walk_abort; // makes walk() return true. + } + }); + } + }); + + PARENS(AST_Call, function(output) { + var p = output.parent(), p1; + if (p instanceof AST_New && p.expression === this + || p instanceof AST_Export && p.is_default && this.expression instanceof AST_Function) + return true; + + // workaround for Safari bug. + // https://bugs.webkit.org/show_bug.cgi?id=123506 + return this.expression instanceof AST_Function + && p instanceof AST_PropAccess + && p.expression === this + && (p1 = output.parent(1)) instanceof AST_Assign + && p1.left === p; + }); + + PARENS(AST_New, function(output) { + var p = output.parent(); + if (this.args.length === 0 + && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]() + || p instanceof AST_Call && p.expression === this + || p instanceof AST_PrefixedTemplateString && p.prefix === this)) // (new foo)(bar) + return true; + }); + + PARENS(AST_Number, function(output) { + var p = output.parent(); + if (p instanceof AST_PropAccess && p.expression === this) { + var value = this.getValue(); + if (value < 0 || /^0/.test(make_num(value))) { + return true; + } + } + }); + + PARENS(AST_BigInt, function(output) { + var p = output.parent(); + if (p instanceof AST_PropAccess && p.expression === this) { + var value = this.getValue(); + if (value.startsWith("-")) { + return true; + } + } + }); + + PARENS([ AST_Assign, AST_Conditional ], function(output) { + var p = output.parent(); + // !(a = false) → true + if (p instanceof AST_Unary) + return true; + // 1 + (a = 2) + 3 → 6, side effect setting a = 2 + if (p instanceof AST_Binary && !(p instanceof AST_Assign)) + return true; + // (a = func)() —or— new (a = Object)() + if (p instanceof AST_Call && p.expression === this) + return true; + // (a = foo) ? bar : baz + if (p instanceof AST_Conditional && p.condition === this) + return true; + // (a = foo)["prop"] —or— (a = foo).prop + if (p instanceof AST_PropAccess && p.expression === this) + return true; + // ({a, b} = {a: 1, b: 2}), a destructuring assignment + if (this instanceof AST_Assign && this.left instanceof AST_Destructuring && this.left.is_array === false) + return true; + }); + + /* -----[ PRINTERS ]----- */ + + DEFPRINT(AST_Directive, function(self, output) { + output.print_string(self.value, self.quote); + output.semicolon(); + }); + + DEFPRINT(AST_Expansion, function (self, output) { + output.print("..."); + self.expression.print(output); + }); + + DEFPRINT(AST_Destructuring, function (self, output) { + output.print(self.is_array ? "[" : "{"); + var len = self.names.length; + self.names.forEach(function (name, i) { + if (i > 0) output.comma(); + name.print(output); + // If the final element is a hole, we need to make sure it + // doesn't look like a trailing comma, by inserting an actual + // trailing comma. + if (i == len - 1 && name instanceof AST_Hole) output.comma(); + }); + output.print(self.is_array ? "]" : "}"); + }); + + DEFPRINT(AST_Debugger, function(self, output) { + output.print("debugger"); + output.semicolon(); + }); + + /* -----[ statements ]----- */ + + function display_body(body, is_toplevel, output, allow_directives) { + var last = body.length - 1; + output.in_directive = allow_directives; + body.forEach(function(stmt, i) { + if (output.in_directive === true && !(stmt instanceof AST_Directive || + stmt instanceof AST_EmptyStatement || + (stmt instanceof AST_SimpleStatement && stmt.body instanceof AST_String) + )) { + output.in_directive = false; + } + if (!(stmt instanceof AST_EmptyStatement)) { + output.indent(); + stmt.print(output); + if (!(i == last && is_toplevel)) { + output.newline(); + if (is_toplevel) output.newline(); + } + } + if (output.in_directive === true && + stmt instanceof AST_SimpleStatement && + stmt.body instanceof AST_String + ) { + output.in_directive = false; + } + }); + output.in_directive = false; + } + + AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output) { + print_maybe_braced_body(this.body, output); + }); + + DEFPRINT(AST_Statement, function(self, output) { + self.body.print(output); + output.semicolon(); + }); + DEFPRINT(AST_Toplevel, function(self, output) { + display_body(self.body, true, output, true); + output.print(""); + }); + DEFPRINT(AST_LabeledStatement, function(self, output) { + self.label.print(output); + output.colon(); + self.body.print(output); + }); + DEFPRINT(AST_SimpleStatement, function(self, output) { + self.body.print(output); + output.semicolon(); + }); + function print_braced_empty(self, output) { + output.print("{"); + output.with_indent(output.next_indent(), function() { + output.append_comments(self, true); + }); + output.add_mapping(self.end); + output.print("}"); + } + function print_braced(self, output, allow_directives) { + if (self.body.length > 0) { + output.with_block(function() { + display_body(self.body, false, output, allow_directives); + output.add_mapping(self.end); + }); + } else print_braced_empty(self, output); + } + DEFPRINT(AST_BlockStatement, function(self, output) { + print_braced(self, output); + }); + DEFPRINT(AST_EmptyStatement, function(self, output) { + output.semicolon(); + }); + DEFPRINT(AST_Do, function(self, output) { + output.print("do"); + output.space(); + make_block(self.body, output); + output.space(); + output.print("while"); + output.space(); + output.with_parens(function() { + self.condition.print(output); + }); + output.semicolon(); + }); + DEFPRINT(AST_While, function(self, output) { + output.print("while"); + output.space(); + output.with_parens(function() { + self.condition.print(output); + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_For, function(self, output) { + output.print("for"); + output.space(); + output.with_parens(function() { + if (self.init) { + if (self.init instanceof AST_Definitions) { + self.init.print(output); + } else { + parenthesize_for_noin(self.init, output, true); + } + output.print(";"); + output.space(); + } else { + output.print(";"); + } + if (self.condition) { + self.condition.print(output); + output.print(";"); + output.space(); + } else { + output.print(";"); + } + if (self.step) { + self.step.print(output); + } + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_ForIn, function(self, output) { + output.print("for"); + if (self.await) { + output.space(); + output.print("await"); + } + output.space(); + output.with_parens(function() { + self.init.print(output); + output.space(); + output.print(self instanceof AST_ForOf ? "of" : "in"); + output.space(); + self.object.print(output); + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_With, function(self, output) { + output.print("with"); + output.space(); + output.with_parens(function() { + self.expression.print(output); + }); + output.space(); + self._do_print_body(output); + }); + + /* -----[ functions ]----- */ + AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword) { + var self = this; + if (!nokeyword) { + if (self.async) { + output.print("async"); + output.space(); + } + output.print("function"); + if (self.is_generator) { + output.star(); + } + if (self.name) { + output.space(); + } + } + if (self.name instanceof AST_Symbol) { + self.name.print(output); + } else if (nokeyword && self.name instanceof AST_Node) { + output.with_square(function() { + self.name.print(output); // Computed method name + }); + } + output.with_parens(function() { + self.argnames.forEach(function(arg, i) { + if (i) output.comma(); + arg.print(output); + }); + }); + output.space(); + print_braced(self, output, true); + }); + DEFPRINT(AST_Lambda, function(self, output) { + self._do_print(output); + output.gc_scope(self); + }); + + DEFPRINT(AST_PrefixedTemplateString, function(self, output) { + var tag = self.prefix; + var parenthesize_tag = tag instanceof AST_Lambda + || tag instanceof AST_Binary + || tag instanceof AST_Conditional + || tag instanceof AST_Sequence + || tag instanceof AST_Unary + || tag instanceof AST_Dot && tag.expression instanceof AST_Object; + if (parenthesize_tag) output.print("("); + self.prefix.print(output); + if (parenthesize_tag) output.print(")"); + self.template_string.print(output); + }); + DEFPRINT(AST_TemplateString, function(self, output) { + var is_tagged = output.parent() instanceof AST_PrefixedTemplateString; + + output.print("`"); + for (var i = 0; i < self.segments.length; i++) { + if (!(self.segments[i] instanceof AST_TemplateSegment)) { + output.print("${"); + self.segments[i].print(output); + output.print("}"); + } else if (is_tagged) { + output.print(self.segments[i].raw); + } else { + output.print_template_string_chars(self.segments[i].value); + } + } + output.print("`"); + }); + DEFPRINT(AST_TemplateSegment, function(self, output) { + output.print_template_string_chars(self.value); + }); + + AST_Arrow.DEFMETHOD("_do_print", function(output) { + var self = this; + var parent = output.parent(); + var needs_parens = (parent instanceof AST_Binary && + !(parent instanceof AST_Assign) && + !(parent instanceof AST_DefaultAssign)) || + parent instanceof AST_Unary || + (parent instanceof AST_Call && self === parent.expression); + if (needs_parens) { output.print("("); } + if (self.async) { + output.print("async"); + output.space(); + } + if (self.argnames.length === 1 && self.argnames[0] instanceof AST_Symbol) { + self.argnames[0].print(output); + } else { + output.with_parens(function() { + self.argnames.forEach(function(arg, i) { + if (i) output.comma(); + arg.print(output); + }); + }); + } + output.space(); + output.print("=>"); + output.space(); + const first_statement = self.body[0]; + if ( + self.body.length === 1 + && first_statement instanceof AST_Return + ) { + const returned = first_statement.value; + if (!returned) { + output.print("{}"); + } else if (left_is_object(returned)) { + output.print("("); + returned.print(output); + output.print(")"); + } else { + returned.print(output); + } + } else { + print_braced(self, output); + } + if (needs_parens) { output.print(")"); } + output.gc_scope(self); + }); + + /* -----[ exits ]----- */ + AST_Exit.DEFMETHOD("_do_print", function(output, kind) { + output.print(kind); + if (this.value) { + output.space(); + const comments = this.value.start.comments_before; + if (comments && comments.length && !output.printed_comments.has(comments)) { + output.print("("); + this.value.print(output); + output.print(")"); + } else { + this.value.print(output); + } + } + output.semicolon(); + }); + DEFPRINT(AST_Return, function(self, output) { + self._do_print(output, "return"); + }); + DEFPRINT(AST_Throw, function(self, output) { + self._do_print(output, "throw"); + }); + + /* -----[ yield ]----- */ + + DEFPRINT(AST_Yield, function(self, output) { + var star = self.is_star ? "*" : ""; + output.print("yield" + star); + if (self.expression) { + output.space(); + self.expression.print(output); + } + }); + + DEFPRINT(AST_Await, function(self, output) { + output.print("await"); + output.space(); + var e = self.expression; + var parens = !( + e instanceof AST_Call + || e instanceof AST_SymbolRef + || e instanceof AST_PropAccess + || e instanceof AST_Unary + || e instanceof AST_Constant + || e instanceof AST_Await + || e instanceof AST_Object + ); + if (parens) output.print("("); + self.expression.print(output); + if (parens) output.print(")"); + }); + + /* -----[ loop control ]----- */ + AST_LoopControl.DEFMETHOD("_do_print", function(output, kind) { + output.print(kind); + if (this.label) { + output.space(); + this.label.print(output); + } + output.semicolon(); + }); + DEFPRINT(AST_Break, function(self, output) { + self._do_print(output, "break"); + }); + DEFPRINT(AST_Continue, function(self, output) { + self._do_print(output, "continue"); + }); + + /* -----[ if ]----- */ + function make_then(self, output) { + var b = self.body; + if (output.option("braces") + || output.option("ie8") && b instanceof AST_Do) + return make_block(b, output); + // The squeezer replaces "block"-s that contain only a single + // statement with the statement itself; technically, the AST + // is correct, but this can create problems when we output an + // IF having an ELSE clause where the THEN clause ends in an + // IF *without* an ELSE block (then the outer ELSE would refer + // to the inner IF). This function checks for this case and + // adds the block braces if needed. + if (!b) return output.force_semicolon(); + while (true) { + if (b instanceof AST_If) { + if (!b.alternative) { + make_block(self.body, output); + return; + } + b = b.alternative; + } else if (b instanceof AST_StatementWithBody) { + b = b.body; + } else break; + } + print_maybe_braced_body(self.body, output); + } + DEFPRINT(AST_If, function(self, output) { + output.print("if"); + output.space(); + output.with_parens(function() { + self.condition.print(output); + }); + output.space(); + if (self.alternative) { + make_then(self, output); + output.space(); + output.print("else"); + output.space(); + if (self.alternative instanceof AST_If) + self.alternative.print(output); + else + print_maybe_braced_body(self.alternative, output); + } else { + self._do_print_body(output); + } + }); + + /* -----[ switch ]----- */ + DEFPRINT(AST_Switch, function(self, output) { + output.print("switch"); + output.space(); + output.with_parens(function() { + self.expression.print(output); + }); + output.space(); + var last = self.body.length - 1; + if (last < 0) print_braced_empty(self, output); + else output.with_block(function() { + self.body.forEach(function(branch, i) { + output.indent(true); + branch.print(output); + if (i < last && branch.body.length > 0) + output.newline(); + }); + }); + }); + AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output) { + output.newline(); + this.body.forEach(function(stmt) { + output.indent(); + stmt.print(output); + output.newline(); + }); + }); + DEFPRINT(AST_Default, function(self, output) { + output.print("default:"); + self._do_print_body(output); + }); + DEFPRINT(AST_Case, function(self, output) { + output.print("case"); + output.space(); + self.expression.print(output); + output.print(":"); + self._do_print_body(output); + }); + + /* -----[ exceptions ]----- */ + DEFPRINT(AST_Try, function(self, output) { + output.print("try"); + output.space(); + self.body.print(output); + if (self.bcatch) { + output.space(); + self.bcatch.print(output); + } + if (self.bfinally) { + output.space(); + self.bfinally.print(output); + } + }); + DEFPRINT(AST_TryBlock, function(self, output) { + print_braced(self, output); + }); + DEFPRINT(AST_Catch, function(self, output) { + output.print("catch"); + if (self.argname) { + output.space(); + output.with_parens(function() { + self.argname.print(output); + }); + } + output.space(); + print_braced(self, output); + }); + DEFPRINT(AST_Finally, function(self, output) { + output.print("finally"); + output.space(); + print_braced(self, output); + }); + + /* -----[ var/const ]----- */ + AST_Definitions.DEFMETHOD("_do_print", function(output, kind) { + output.print(kind); + output.space(); + this.definitions.forEach(function(def, i) { + if (i) output.comma(); + def.print(output); + }); + var p = output.parent(); + var in_for = p instanceof AST_For || p instanceof AST_ForIn; + var output_semicolon = !in_for || p && p.init !== this; + if (output_semicolon) + output.semicolon(); + }); + DEFPRINT(AST_Let, function(self, output) { + self._do_print(output, "let"); + }); + DEFPRINT(AST_Var, function(self, output) { + self._do_print(output, "var"); + }); + DEFPRINT(AST_Const, function(self, output) { + self._do_print(output, "const"); + }); + DEFPRINT(AST_Import, function(self, output) { + output.print("import"); + output.space(); + if (self.imported_name) { + self.imported_name.print(output); + } + if (self.imported_name && self.imported_names) { + output.print(","); + output.space(); + } + if (self.imported_names) { + if (self.imported_names.length === 1 && + self.imported_names[0].foreign_name.name === "*" && + !self.imported_names[0].foreign_name.quote) { + self.imported_names[0].print(output); + } else { + output.print("{"); + self.imported_names.forEach(function (name_import, i) { + output.space(); + name_import.print(output); + if (i < self.imported_names.length - 1) { + output.print(","); + } + }); + output.space(); + output.print("}"); + } + } + if (self.imported_name || self.imported_names) { + output.space(); + output.print("from"); + output.space(); + } + self.module_name.print(output); + if (self.assert_clause) { + output.print("assert"); + self.assert_clause.print(output); + } + output.semicolon(); + }); + DEFPRINT(AST_ImportMeta, function(self, output) { + output.print("import.meta"); + }); + + DEFPRINT(AST_NameMapping, function(self, output) { + var is_import = output.parent() instanceof AST_Import; + var definition = self.name.definition(); + var foreign_name = self.foreign_name; + var names_are_different = + (definition && definition.mangled_name || self.name.name) !== + foreign_name.name; + if (!names_are_different && + foreign_name.name === "*" && + foreign_name.quote != self.name.quote) { + // export * as "*" + names_are_different = true; + } + var foreign_name_is_name = foreign_name.quote == null; + if (names_are_different) { + if (is_import) { + if (foreign_name_is_name) { + output.print(foreign_name.name); + } else { + output.print_string(foreign_name.name, foreign_name.quote); + } + } else { + if (self.name.quote == null) { + self.name.print(output); + } else { + output.print_string(self.name.name, self.name.quote); + } + + } + output.space(); + output.print("as"); + output.space(); + if (is_import) { + self.name.print(output); + } else { + if (foreign_name_is_name) { + output.print(foreign_name.name); + } else { + output.print_string(foreign_name.name, foreign_name.quote); + } + } + } else { + if (self.name.quote == null) { + self.name.print(output); + } else { + output.print_string(self.name.name, self.name.quote); + } + } + }); + + DEFPRINT(AST_Export, function(self, output) { + output.print("export"); + output.space(); + if (self.is_default) { + output.print("default"); + output.space(); + } + if (self.exported_names) { + if (self.exported_names.length === 1 && + self.exported_names[0].name.name === "*" && + !self.exported_names[0].name.quote) { + self.exported_names[0].print(output); + } else { + output.print("{"); + self.exported_names.forEach(function(name_export, i) { + output.space(); + name_export.print(output); + if (i < self.exported_names.length - 1) { + output.print(","); + } + }); + output.space(); + output.print("}"); + } + } else if (self.exported_value) { + self.exported_value.print(output); + } else if (self.exported_definition) { + self.exported_definition.print(output); + if (self.exported_definition instanceof AST_Definitions) return; + } + if (self.module_name) { + output.space(); + output.print("from"); + output.space(); + self.module_name.print(output); + } + if (self.assert_clause) { + output.print("assert"); + self.assert_clause.print(output); + } + if (self.exported_value + && !(self.exported_value instanceof AST_Defun || + self.exported_value instanceof AST_Function || + self.exported_value instanceof AST_Class) + || self.module_name + || self.exported_names + ) { + output.semicolon(); + } + }); + + function parenthesize_for_noin(node, output, noin) { + var parens = false; + // need to take some precautions here: + // https://github.com/mishoo/UglifyJS2/issues/60 + if (noin) { + parens = walk(node, node => { + // Don't go into scopes -- except arrow functions: + // https://github.com/terser/terser/issues/1019#issuecomment-877642607 + if (node instanceof AST_Scope && !(node instanceof AST_Arrow)) { + return true; + } + if ( + node instanceof AST_Binary && node.operator == "in" + || node instanceof AST_PrivateIn + ) { + return walk_abort; // makes walk() return true + } + }); + } + node.print(output, parens); + } + + DEFPRINT(AST_VarDef, function(self, output) { + self.name.print(output); + if (self.value) { + output.space(); + output.print("="); + output.space(); + var p = output.parent(1); + var noin = p instanceof AST_For || p instanceof AST_ForIn; + parenthesize_for_noin(self.value, output, noin); + } + }); + + /* -----[ other expressions ]----- */ + DEFPRINT(AST_Call, function(self, output) { + self.expression.print(output); + if (self instanceof AST_New && self.args.length === 0) + return; + if (self.expression instanceof AST_Call || self.expression instanceof AST_Lambda) { + output.add_mapping(self.start); + } + if (self.optional) output.print("?."); + output.with_parens(function() { + self.args.forEach(function(expr, i) { + if (i) output.comma(); + expr.print(output); + }); + }); + }); + DEFPRINT(AST_New, function(self, output) { + output.print("new"); + output.space(); + AST_Call.prototype._codegen(self, output); + }); + + AST_Sequence.DEFMETHOD("_do_print", function(output) { + this.expressions.forEach(function(node, index) { + if (index > 0) { + output.comma(); + if (output.should_break()) { + output.newline(); + output.indent(); + } + } + node.print(output); + }); + }); + DEFPRINT(AST_Sequence, function(self, output) { + self._do_print(output); + // var p = output.parent(); + // if (p instanceof AST_Statement) { + // output.with_indent(output.next_indent(), function(){ + // self._do_print(output); + // }); + // } else { + // self._do_print(output); + // } + }); + DEFPRINT(AST_Dot, function(self, output) { + var expr = self.expression; + expr.print(output); + var prop = self.property; + var print_computed = ALL_RESERVED_WORDS.has(prop) + ? output.option("ie8") + : !is_identifier_string( + prop, + output.option("ecma") >= 2015 && !output.option("safari10") + ); + + if (self.optional) output.print("?."); + + if (print_computed) { + output.print("["); + output.add_mapping(self.end); + output.print_string(prop); + output.print("]"); + } else { + if (expr instanceof AST_Number && expr.getValue() >= 0) { + if (!/[xa-f.)]/i.test(output.last())) { + output.print("."); + } + } + if (!self.optional) output.print("."); + // the name after dot would be mapped about here. + output.add_mapping(self.end); + output.print_name(prop); + } + }); + DEFPRINT(AST_DotHash, function(self, output) { + var expr = self.expression; + expr.print(output); + var prop = self.property; + + if (self.optional) output.print("?"); + output.print(".#"); + output.add_mapping(self.end); + output.print_name(prop); + }); + DEFPRINT(AST_Sub, function(self, output) { + self.expression.print(output); + if (self.optional) output.print("?."); + output.print("["); + self.property.print(output); + output.print("]"); + }); + DEFPRINT(AST_Chain, function(self, output) { + self.expression.print(output); + }); + DEFPRINT(AST_UnaryPrefix, function(self, output) { + var op = self.operator; + if (op === "--" && output.last().endsWith("!")) { + // avoid printing " + output.print(" "); + } else { + // the space is optional depending on "beautify" + output.space(); + } + output.print(op); + output.space(); + self.right.print(output); + }); + DEFPRINT(AST_Conditional, function(self, output) { + self.condition.print(output); + output.space(); + output.print("?"); + output.space(); + self.consequent.print(output); + output.space(); + output.colon(); + self.alternative.print(output); + }); + + /* -----[ literals ]----- */ + DEFPRINT(AST_Array, function(self, output) { + output.with_square(function() { + var a = self.elements, len = a.length; + if (len > 0) output.space(); + a.forEach(function(exp, i) { + if (i) output.comma(); + exp.print(output); + // If the final element is a hole, we need to make sure it + // doesn't look like a trailing comma, by inserting an actual + // trailing comma. + if (i === len - 1 && exp instanceof AST_Hole) + output.comma(); + }); + if (len > 0) output.space(); + }); + }); + DEFPRINT(AST_Object, function(self, output) { + if (self.properties.length > 0) output.with_block(function() { + self.properties.forEach(function(prop, i) { + if (i) { + output.print(","); + output.newline(); + } + output.indent(); + prop.print(output); + }); + output.newline(); + }); + else print_braced_empty(self, output); + }); + DEFPRINT(AST_Class, function(self, output) { + output.print("class"); + output.space(); + if (self.name) { + self.name.print(output); + output.space(); + } + if (self.extends) { + var parens = ( + !(self.extends instanceof AST_SymbolRef) + && !(self.extends instanceof AST_PropAccess) + && !(self.extends instanceof AST_ClassExpression) + && !(self.extends instanceof AST_Function) + ); + output.print("extends"); + if (parens) { + output.print("("); + } else { + output.space(); + } + self.extends.print(output); + if (parens) { + output.print(")"); + } else { + output.space(); + } + } + if (self.properties.length > 0) output.with_block(function() { + self.properties.forEach(function(prop, i) { + if (i) { + output.newline(); + } + output.indent(); + prop.print(output); + }); + output.newline(); + }); + else output.print("{}"); + }); + DEFPRINT(AST_NewTarget, function(self, output) { + output.print("new.target"); + }); + + /** Prints a prop name. Returns whether it can be used as a shorthand. */ + function print_property_name(key, quote, output) { + if (output.option("quote_keys")) { + output.print_string(key); + return false; + } + if ("" + +key == key && key >= 0) { + if (output.option("keep_numbers")) { + output.print(key); + return false; + } + output.print(make_num(key)); + return false; + } + var print_string = ALL_RESERVED_WORDS.has(key) + ? output.option("ie8") + : ( + output.option("ecma") < 2015 || output.option("safari10") + ? !is_basic_identifier_string(key) + : !is_identifier_string(key, true) + ); + if (print_string || (quote && output.option("keep_quoted_props"))) { + output.print_string(key, quote); + return false; + } + output.print_name(key); + return true; + } + + DEFPRINT(AST_ObjectKeyVal, function(self, output) { + function get_name(self) { + var def = self.definition(); + return def ? def.mangled_name || def.name : self.name; + } + + const try_shorthand = output.option("shorthand") && !(self.key instanceof AST_Node); + if ( + try_shorthand + && self.value instanceof AST_Symbol + && get_name(self.value) === self.key + && !ALL_RESERVED_WORDS.has(self.key) + ) { + const was_shorthand = print_property_name(self.key, self.quote, output); + if (!was_shorthand) { + output.colon(); + self.value.print(output); + } + } else if ( + try_shorthand + && self.value instanceof AST_DefaultAssign + && self.value.left instanceof AST_Symbol + && get_name(self.value.left) === self.key + ) { + const was_shorthand = print_property_name(self.key, self.quote, output); + if (!was_shorthand) { + output.colon(); + self.value.left.print(output); + } + output.space(); + output.print("="); + output.space(); + self.value.right.print(output); + } else { + if (!(self.key instanceof AST_Node)) { + print_property_name(self.key, self.quote, output); + } else { + output.with_square(function() { + self.key.print(output); + }); + } + output.colon(); + self.value.print(output); + } + }); + DEFPRINT(AST_ClassPrivateProperty, (self, output) => { + if (self.static) { + output.print("static"); + output.space(); + } + + output.print("#"); + + print_property_name(self.key.name, self.quote, output); + + if (self.value) { + output.print("="); + self.value.print(output); + } + + output.semicolon(); + }); + DEFPRINT(AST_ClassProperty, (self, output) => { + if (self.static) { + output.print("static"); + output.space(); + } + + if (self.key instanceof AST_SymbolClassProperty) { + print_property_name(self.key.name, self.quote, output); + } else { + output.print("["); + self.key.print(output); + output.print("]"); + } + + if (self.value) { + output.print("="); + self.value.print(output); + } + + output.semicolon(); + }); + AST_ObjectProperty.DEFMETHOD("_print_getter_setter", function(type, is_private, output) { + var self = this; + if (self.static) { + output.print("static"); + output.space(); + } + if (type) { + output.print(type); + output.space(); + } + if (self.key instanceof AST_SymbolMethod) { + if (is_private) output.print("#"); + print_property_name(self.key.name, self.quote, output); + self.key.add_source_map(output); + } else { + output.with_square(function() { + self.key.print(output); + }); + } + self.value._do_print(output, true); + }); + DEFPRINT(AST_ObjectSetter, function(self, output) { + self._print_getter_setter("set", false, output); + }); + DEFPRINT(AST_ObjectGetter, function(self, output) { + self._print_getter_setter("get", false, output); + }); + DEFPRINT(AST_PrivateSetter, function(self, output) { + self._print_getter_setter("set", true, output); + }); + DEFPRINT(AST_PrivateGetter, function(self, output) { + self._print_getter_setter("get", true, output); + }); + DEFPRINT(AST_PrivateMethod, function(self, output) { + var type; + if (self.is_generator && self.async) { + type = "async*"; + } else if (self.is_generator) { + type = "*"; + } else if (self.async) { + type = "async"; + } + self._print_getter_setter(type, true, output); + }); + DEFPRINT(AST_PrivateIn, function(self, output) { + self.key.print(output); + output.space(); + output.print("in"); + output.space(); + self.value.print(output); + }); + DEFPRINT(AST_SymbolPrivateProperty, function(self, output) { + output.print("#" + self.name); + }); + DEFPRINT(AST_ConciseMethod, function(self, output) { + var type; + if (self.is_generator && self.async) { + type = "async*"; + } else if (self.is_generator) { + type = "*"; + } else if (self.async) { + type = "async"; + } + self._print_getter_setter(type, false, output); + }); + DEFPRINT(AST_ClassStaticBlock, function (self, output) { + output.print("static"); + output.space(); + print_braced(self, output); + }); + AST_Symbol.DEFMETHOD("_do_print", function(output) { + var def = this.definition(); + output.print_name(def ? def.mangled_name || def.name : this.name); + }); + DEFPRINT(AST_Symbol, function (self, output) { + self._do_print(output); + }); + DEFPRINT(AST_Hole, noop); + DEFPRINT(AST_This, function(self, output) { + output.print("this"); + }); + DEFPRINT(AST_Super, function(self, output) { + output.print("super"); + }); + DEFPRINT(AST_Constant, function(self, output) { + output.print(self.getValue()); + }); + DEFPRINT(AST_String, function(self, output) { + output.print_string(self.getValue(), self.quote, output.in_directive); + }); + DEFPRINT(AST_Number, function(self, output) { + if ((output.option("keep_numbers") || output.use_asm) && self.raw) { + output.print(self.raw); + } else { + output.print(make_num(self.getValue())); + } + }); + DEFPRINT(AST_BigInt, function(self, output) { + output.print(self.getValue() + "n"); + }); + + const r_slash_script = /(<\s*\/\s*script)/i; + const r_starts_with_script = /^\s*script/i; + const slash_script_replace = (_, $1) => $1.replace("/", "\\/"); + DEFPRINT(AST_RegExp, function(self, output) { + let { source, flags } = self.getValue(); + source = regexp_source_fix(source); + flags = flags ? sort_regexp_flags(flags) : ""; + + // Avoid outputting end of script tag + source = source.replace(r_slash_script, slash_script_replace); + if (r_starts_with_script.test(source) && output.last().endsWith("<")) { + output.print(" "); + } + + output.print(output.to_utf8(`/${source}/${flags}`, false, true)); + + const parent = output.parent(); + if ( + parent instanceof AST_Binary + && /^\w/.test(parent.operator) + && parent.left === self + ) { + output.print(" "); + } + }); + + /** if, for, while, may or may not have braces surrounding its body */ + function print_maybe_braced_body(stat, output) { + if (output.option("braces")) { + make_block(stat, output); + } else { + if (!stat || stat instanceof AST_EmptyStatement) + output.force_semicolon(); + else if (stat instanceof AST_Let || stat instanceof AST_Const || stat instanceof AST_Class) + make_block(stat, output); + else + stat.print(output); + } + } + + function best_of(a) { + var best = a[0], len = best.length; + for (var i = 1; i < a.length; ++i) { + if (a[i].length < len) { + best = a[i]; + len = best.length; + } + } + return best; + } + + function make_num(num) { + var str = num.toString(10).replace(/^0\./, ".").replace("e+", "e"); + var candidates = [ str ]; + if (Math.floor(num) === num) { + if (num < 0) { + candidates.push("-0x" + (-num).toString(16).toLowerCase()); + } else { + candidates.push("0x" + num.toString(16).toLowerCase()); + } + } + var match, len, digits; + if (match = /^\.0+/.exec(str)) { + len = match[0].length; + digits = str.slice(len); + candidates.push(digits + "e-" + (digits.length + len - 1)); + } else if (match = /0+$/.exec(str)) { + len = match[0].length; + candidates.push(str.slice(0, -len) + "e" + len); + } else if (match = /^(\d)\.(\d+)e(-?\d+)$/.exec(str)) { + candidates.push(match[1] + match[2] + "e" + (match[3] - match[2].length)); + } + return best_of(candidates); + } + + function make_block(stmt, output) { + if (!stmt || stmt instanceof AST_EmptyStatement) + output.print("{}"); + else if (stmt instanceof AST_BlockStatement) + stmt.print(output); + else output.with_block(function() { + output.indent(); + stmt.print(output); + output.newline(); + }); + } + + /* -----[ source map generators ]----- */ + + function DEFMAP(nodetype, generator) { + nodetype.forEach(function(nodetype) { + nodetype.DEFMETHOD("add_source_map", generator); + }); + } + + DEFMAP([ + // We could easily add info for ALL nodes, but it seems to me that + // would be quite wasteful, hence this noop in the base class. + AST_Node, + // since the label symbol will mark it + AST_LabeledStatement, + AST_Toplevel, + ], noop); + + // XXX: I'm not exactly sure if we need it for all of these nodes, + // or if we should add even more. + DEFMAP([ + AST_Array, + AST_BlockStatement, + AST_Catch, + AST_Class, + AST_Constant, + AST_Debugger, + AST_Definitions, + AST_Directive, + AST_Finally, + AST_Jump, + AST_Lambda, + AST_New, + AST_Object, + AST_StatementWithBody, + AST_Symbol, + AST_Switch, + AST_SwitchBranch, + AST_TemplateString, + AST_TemplateSegment, + AST_Try, + ], function(output) { + output.add_mapping(this.start); + }); + + DEFMAP([ + AST_ObjectGetter, + AST_ObjectSetter, + AST_PrivateGetter, + AST_PrivateSetter, + AST_ConciseMethod, + AST_PrivateMethod, + ], function(output) { + output.add_mapping(this.start, false /*name handled below*/); + }); + + DEFMAP([ + AST_SymbolMethod, + AST_SymbolPrivateProperty + ], function(output) { + const tok_type = this.end && this.end.type; + if (tok_type === "name" || tok_type === "privatename") { + output.add_mapping(this.end, this.name); + } else { + output.add_mapping(this.end); + } + }); + + DEFMAP([ AST_ObjectProperty ], function(output) { + output.add_mapping(this.start, this.key); + }); +})(); + +export { + OutputStream, +}; diff --git a/node_modules/terser/lib/parse.js b/node_modules/terser/lib/parse.js new file mode 100644 index 0000000..9ff28d4 --- /dev/null +++ b/node_modules/terser/lib/parse.js @@ -0,0 +1,3493 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + Parser based on parse-js (http://marijn.haverbeke.nl/parse-js/). + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +import { + characters, + defaults, + makePredicate, + set_annotation, +} from "./utils/index.js"; +import { + AST_Accessor, + AST_Array, + AST_Arrow, + AST_Assign, + AST_Await, + AST_BigInt, + AST_Binary, + AST_BlockStatement, + AST_Break, + AST_Call, + AST_Case, + AST_Catch, + AST_Chain, + AST_ClassExpression, + AST_ClassPrivateProperty, + AST_ClassProperty, + AST_ClassStaticBlock, + AST_ConciseMethod, + AST_PrivateIn, + AST_PrivateGetter, + AST_PrivateMethod, + AST_PrivateSetter, + AST_Conditional, + AST_Const, + AST_Continue, + AST_Debugger, + AST_Default, + AST_DefaultAssign, + AST_DefClass, + AST_Definitions, + AST_Defun, + AST_Destructuring, + AST_Directive, + AST_Do, + AST_Dot, + AST_DotHash, + AST_EmptyStatement, + AST_Expansion, + AST_Export, + AST_False, + AST_Finally, + AST_For, + AST_ForIn, + AST_ForOf, + AST_Function, + AST_Hole, + AST_If, + AST_Import, + AST_ImportMeta, + AST_IterationStatement, + AST_Label, + AST_LabeledStatement, + AST_LabelRef, + AST_Let, + AST_NameMapping, + AST_New, + AST_NewTarget, + AST_Node, + AST_Null, + AST_Number, + AST_Object, + AST_ObjectGetter, + AST_ObjectKeyVal, + AST_ObjectProperty, + AST_ObjectSetter, + AST_PrefixedTemplateString, + AST_PropAccess, + AST_RegExp, + AST_Return, + AST_Sequence, + AST_SimpleStatement, + AST_String, + AST_Sub, + AST_Super, + AST_Switch, + AST_SymbolCatch, + AST_SymbolClass, + AST_SymbolClassProperty, + AST_SymbolConst, + AST_SymbolDeclaration, + AST_SymbolDefClass, + AST_SymbolDefun, + AST_SymbolExport, + AST_SymbolExportForeign, + AST_SymbolFunarg, + AST_SymbolImport, + AST_SymbolImportForeign, + AST_SymbolLambda, + AST_SymbolLet, + AST_SymbolMethod, + AST_SymbolRef, + AST_SymbolVar, + AST_TemplateSegment, + AST_TemplateString, + AST_This, + AST_SymbolPrivateProperty, + AST_Throw, + AST_Token, + AST_Toplevel, + AST_True, + AST_Try, + AST_TryBlock, + AST_UnaryPostfix, + AST_UnaryPrefix, + AST_Var, + AST_VarDef, + AST_While, + AST_With, + AST_Yield, + _INLINE, + _NOINLINE, + _PURE, + _KEY, + _MANGLEPROP, +} from "./ast.js"; + +var LATEST_RAW = ""; // Only used for numbers and template strings +var TEMPLATE_RAWS = new Map(); // Raw template strings + +var KEYWORDS = "break case catch class const continue debugger default delete do else export extends finally for function if in instanceof let new return switch throw try typeof var void while with"; +var KEYWORDS_ATOM = "false null true"; +var RESERVED_WORDS = "enum import super this " + KEYWORDS_ATOM + " " + KEYWORDS; +var ALL_RESERVED_WORDS = "implements interface package private protected public static " + RESERVED_WORDS; +var KEYWORDS_BEFORE_EXPRESSION = "return new delete throw else case yield await"; + +KEYWORDS = makePredicate(KEYWORDS); +RESERVED_WORDS = makePredicate(RESERVED_WORDS); +KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION); +KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM); +ALL_RESERVED_WORDS = makePredicate(ALL_RESERVED_WORDS); + +var OPERATOR_CHARS = makePredicate(characters("+-*&%=<>!?|~^")); + +var RE_NUM_LITERAL = /[0-9a-f]/i; +var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i; +var RE_OCT_NUMBER = /^0[0-7]+$/; +var RE_ES6_OCT_NUMBER = /^0o[0-7]+$/i; +var RE_BIN_NUMBER = /^0b[01]+$/i; +var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i; +var RE_BIG_INT = /^(0[xob])?[0-9a-f]+n$/i; + +var OPERATORS = makePredicate([ + "in", + "instanceof", + "typeof", + "new", + "void", + "delete", + "++", + "--", + "+", + "-", + "!", + "~", + "&", + "|", + "^", + "*", + "**", + "/", + "%", + ">>", + "<<", + ">>>", + "<", + ">", + "<=", + ">=", + "==", + "===", + "!=", + "!==", + "?", + "=", + "+=", + "-=", + "||=", + "&&=", + "??=", + "/=", + "*=", + "**=", + "%=", + ">>=", + "<<=", + ">>>=", + "|=", + "^=", + "&=", + "&&", + "??", + "||", +]); + +var WHITESPACE_CHARS = makePredicate(characters(" \u00a0\n\r\t\f\u000b\u200b\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\uFEFF")); + +var NEWLINE_CHARS = makePredicate(characters("\n\r\u2028\u2029")); + +var PUNC_AFTER_EXPRESSION = makePredicate(characters(";]),:")); + +var PUNC_BEFORE_EXPRESSION = makePredicate(characters("[{(,;:")); + +var PUNC_CHARS = makePredicate(characters("[]{}(),;:")); + +/* -----[ Tokenizer ]----- */ + +// surrogate safe regexps adapted from https://github.com/mathiasbynens/unicode-8.0.0/tree/89b412d8a71ecca9ed593d9e9fa073ab64acfebe/Binary_Property +var UNICODE = { + ID_Start: /[$A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/, + ID_Continue: /(?:[$0-9A-Z_a-z\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0B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A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE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37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF])+/, +}; + +function get_full_char(str, pos) { + if (is_surrogate_pair_head(str.charCodeAt(pos))) { + if (is_surrogate_pair_tail(str.charCodeAt(pos + 1))) { + return str.charAt(pos) + str.charAt(pos + 1); + } + } else if (is_surrogate_pair_tail(str.charCodeAt(pos))) { + if (is_surrogate_pair_head(str.charCodeAt(pos - 1))) { + return str.charAt(pos - 1) + str.charAt(pos); + } + } + return str.charAt(pos); +} + +function get_full_char_code(str, pos) { + // https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates + if (is_surrogate_pair_head(str.charCodeAt(pos))) { + return 0x10000 + (str.charCodeAt(pos) - 0xd800 << 10) + str.charCodeAt(pos + 1) - 0xdc00; + } + return str.charCodeAt(pos); +} + +function get_full_char_length(str) { + var surrogates = 0; + + for (var i = 0; i < str.length; i++) { + if (is_surrogate_pair_head(str.charCodeAt(i)) && is_surrogate_pair_tail(str.charCodeAt(i + 1))) { + surrogates++; + i++; + } + } + + return str.length - surrogates; +} + +function from_char_code(code) { + // Based on https://github.com/mathiasbynens/String.fromCodePoint/blob/master/fromcodepoint.js + if (code > 0xFFFF) { + code -= 0x10000; + return (String.fromCharCode((code >> 10) + 0xD800) + + String.fromCharCode((code % 0x400) + 0xDC00)); + } + return String.fromCharCode(code); +} + +function is_surrogate_pair_head(code) { + return code >= 0xd800 && code <= 0xdbff; +} + +function is_surrogate_pair_tail(code) { + return code >= 0xdc00 && code <= 0xdfff; +} + +function is_digit(code) { + return code >= 48 && code <= 57; +} + +function is_identifier_start(ch) { + return UNICODE.ID_Start.test(ch); +} + +function is_identifier_char(ch) { + return UNICODE.ID_Continue.test(ch); +} + +const BASIC_IDENT = /^[a-z_$][a-z0-9_$]*$/i; + +function is_basic_identifier_string(str) { + return BASIC_IDENT.test(str); +} + +function is_identifier_string(str, allow_surrogates) { + if (BASIC_IDENT.test(str)) { + return true; + } + if (!allow_surrogates && /[\ud800-\udfff]/.test(str)) { + return false; + } + var match = UNICODE.ID_Start.exec(str); + if (!match || match.index !== 0) { + return false; + } + + str = str.slice(match[0].length); + if (!str) { + return true; + } + + match = UNICODE.ID_Continue.exec(str); + return !!match && match[0].length === str.length; +} + +function parse_js_number(num, allow_e = true) { + if (!allow_e && num.includes("e")) { + return NaN; + } + if (RE_HEX_NUMBER.test(num)) { + return parseInt(num.substr(2), 16); + } else if (RE_OCT_NUMBER.test(num)) { + return parseInt(num.substr(1), 8); + } else if (RE_ES6_OCT_NUMBER.test(num)) { + return parseInt(num.substr(2), 8); + } else if (RE_BIN_NUMBER.test(num)) { + return parseInt(num.substr(2), 2); + } else if (RE_DEC_NUMBER.test(num)) { + return parseFloat(num); + } else { + var val = parseFloat(num); + if (val == num) return val; + } +} + +class JS_Parse_Error extends Error { + constructor(message, filename, line, col, pos) { + super(); + + this.name = "SyntaxError"; + this.message = message; + this.filename = filename; + this.line = line; + this.col = col; + this.pos = pos; + } +} + +function js_error(message, filename, line, col, pos) { + throw new JS_Parse_Error(message, filename, line, col, pos); +} + +function is_token(token, type, val) { + return token.type == type && (val == null || token.value == val); +} + +var EX_EOF = {}; + +function tokenizer($TEXT, filename, html5_comments, shebang) { + var S = { + text : $TEXT, + filename : filename, + pos : 0, + tokpos : 0, + line : 1, + tokline : 0, + col : 0, + tokcol : 0, + newline_before : false, + regex_allowed : false, + brace_counter : 0, + template_braces : [], + comments_before : [], + directives : {}, + directive_stack : [] + }; + + function peek() { return get_full_char(S.text, S.pos); } + + // Used because parsing ?. involves a lookahead for a digit + function is_option_chain_op() { + const must_be_dot = S.text.charCodeAt(S.pos + 1) === 46; + if (!must_be_dot) return false; + + const cannot_be_digit = S.text.charCodeAt(S.pos + 2); + return cannot_be_digit < 48 || cannot_be_digit > 57; + } + + function next(signal_eof, in_string) { + var ch = get_full_char(S.text, S.pos++); + if (signal_eof && !ch) + throw EX_EOF; + if (NEWLINE_CHARS.has(ch)) { + S.newline_before = S.newline_before || !in_string; + ++S.line; + S.col = 0; + if (ch == "\r" && peek() == "\n") { + // treat a \r\n sequence as a single \n + ++S.pos; + ch = "\n"; + } + } else { + if (ch.length > 1) { + ++S.pos; + ++S.col; + } + ++S.col; + } + return ch; + } + + function forward(i) { + while (i--) next(); + } + + function looking_at(str) { + return S.text.substr(S.pos, str.length) == str; + } + + function find_eol() { + var text = S.text; + for (var i = S.pos, n = S.text.length; i < n; ++i) { + var ch = text[i]; + if (NEWLINE_CHARS.has(ch)) + return i; + } + return -1; + } + + function find(what, signal_eof) { + var pos = S.text.indexOf(what, S.pos); + if (signal_eof && pos == -1) throw EX_EOF; + return pos; + } + + function start_token() { + S.tokline = S.line; + S.tokcol = S.col; + S.tokpos = S.pos; + } + + var prev_was_dot = false; + var previous_token = null; + function token(type, value, is_comment) { + S.regex_allowed = ((type == "operator" && !UNARY_POSTFIX.has(value)) || + (type == "keyword" && KEYWORDS_BEFORE_EXPRESSION.has(value)) || + (type == "punc" && PUNC_BEFORE_EXPRESSION.has(value))) || + (type == "arrow"); + if (type == "punc" && (value == "." || value == "?.")) { + prev_was_dot = true; + } else if (!is_comment) { + prev_was_dot = false; + } + const line = S.tokline; + const col = S.tokcol; + const pos = S.tokpos; + const nlb = S.newline_before; + const file = filename; + let comments_before = []; + let comments_after = []; + + if (!is_comment) { + comments_before = S.comments_before; + comments_after = S.comments_before = []; + } + S.newline_before = false; + const tok = new AST_Token(type, value, line, col, pos, nlb, comments_before, comments_after, file); + + if (!is_comment) previous_token = tok; + return tok; + } + + function skip_whitespace() { + while (WHITESPACE_CHARS.has(peek())) + next(); + } + + function read_while(pred) { + var ret = "", ch, i = 0; + while ((ch = peek()) && pred(ch, i++)) + ret += next(); + return ret; + } + + function parse_error(err) { + js_error(err, filename, S.tokline, S.tokcol, S.tokpos); + } + + function read_num(prefix) { + var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".", is_big_int = false, numeric_separator = false; + var num = read_while(function(ch, i) { + if (is_big_int) return false; + + var code = ch.charCodeAt(0); + switch (code) { + case 95: // _ + return (numeric_separator = true); + case 98: case 66: // bB + return (has_x = true); // Can occur in hex sequence, don't return false yet + case 111: case 79: // oO + case 120: case 88: // xX + return has_x ? false : (has_x = true); + case 101: case 69: // eE + return has_x ? true : has_e ? false : (has_e = after_e = true); + case 45: // - + return after_e || (i == 0 && !prefix); + case 43: // + + return after_e; + case (after_e = false, 46): // . + return (!has_dot && !has_x && !has_e) ? (has_dot = true) : false; + } + + if (ch === "n") { + is_big_int = true; + + return true; + } + + return RE_NUM_LITERAL.test(ch); + }); + if (prefix) num = prefix + num; + + LATEST_RAW = num; + + if (RE_OCT_NUMBER.test(num) && next_token.has_directive("use strict")) { + parse_error("Legacy octal literals are not allowed in strict mode"); + } + if (numeric_separator) { + if (num.endsWith("_")) { + parse_error("Numeric separators are not allowed at the end of numeric literals"); + } else if (num.includes("__")) { + parse_error("Only one underscore is allowed as numeric separator"); + } + num = num.replace(/_/g, ""); + } + if (num.endsWith("n")) { + const without_n = num.slice(0, -1); + const allow_e = RE_HEX_NUMBER.test(without_n); + const valid = parse_js_number(without_n, allow_e); + if (!has_dot && RE_BIG_INT.test(num) && !isNaN(valid)) + return token("big_int", without_n); + parse_error("Invalid or unexpected token"); + } + var valid = parse_js_number(num); + if (!isNaN(valid)) { + return token("num", valid); + } else { + parse_error("Invalid syntax: " + num); + } + } + + function is_octal(ch) { + return ch >= "0" && ch <= "7"; + } + + function read_escaped_char(in_string, strict_hex, template_string) { + var ch = next(true, in_string); + switch (ch.charCodeAt(0)) { + case 110 : return "\n"; + case 114 : return "\r"; + case 116 : return "\t"; + case 98 : return "\b"; + case 118 : return "\u000b"; // \v + case 102 : return "\f"; + case 120 : return String.fromCharCode(hex_bytes(2, strict_hex)); // \x + case 117 : // \u + if (peek() == "{") { + next(true); + if (peek() === "}") + parse_error("Expecting hex-character between {}"); + while (peek() == "0") next(true); // No significance + var result, length = find("}", true) - S.pos; + // Avoid 32 bit integer overflow (1 << 32 === 1) + // We know first character isn't 0 and thus out of range anyway + if (length > 6 || (result = hex_bytes(length, strict_hex)) > 0x10FFFF) { + parse_error("Unicode reference out of bounds"); + } + next(true); + return from_char_code(result); + } + return String.fromCharCode(hex_bytes(4, strict_hex)); + case 10 : return ""; // newline + case 13 : // \r + if (peek() == "\n") { // DOS newline + next(true, in_string); + return ""; + } + } + if (is_octal(ch)) { + if (template_string && strict_hex) { + const represents_null_character = ch === "0" && !is_octal(peek()); + if (!represents_null_character) { + parse_error("Octal escape sequences are not allowed in template strings"); + } + } + return read_octal_escape_sequence(ch, strict_hex); + } + return ch; + } + + function read_octal_escape_sequence(ch, strict_octal) { + // Read + var p = peek(); + if (p >= "0" && p <= "7") { + ch += next(true); + if (ch[0] <= "3" && (p = peek()) >= "0" && p <= "7") + ch += next(true); + } + + // Parse + if (ch === "0") return "\0"; + if (ch.length > 0 && next_token.has_directive("use strict") && strict_octal) + parse_error("Legacy octal escape sequences are not allowed in strict mode"); + return String.fromCharCode(parseInt(ch, 8)); + } + + function hex_bytes(n, strict_hex) { + var num = 0; + for (; n > 0; --n) { + if (!strict_hex && isNaN(parseInt(peek(), 16))) { + return parseInt(num, 16) || ""; + } + var digit = next(true); + if (isNaN(parseInt(digit, 16))) + parse_error("Invalid hex-character pattern in string"); + num += digit; + } + return parseInt(num, 16); + } + + var read_string = with_eof_error("Unterminated string constant", function() { + const start_pos = S.pos; + var quote = next(), ret = []; + for (;;) { + var ch = next(true, true); + if (ch == "\\") ch = read_escaped_char(true, true); + else if (ch == "\r" || ch == "\n") parse_error("Unterminated string constant"); + else if (ch == quote) break; + ret.push(ch); + } + var tok = token("string", ret.join("")); + LATEST_RAW = S.text.slice(start_pos, S.pos); + tok.quote = quote; + return tok; + }); + + var read_template_characters = with_eof_error("Unterminated template", function(begin) { + if (begin) { + S.template_braces.push(S.brace_counter); + } + var content = "", raw = "", ch, tok; + next(true, true); + while ((ch = next(true, true)) != "`") { + if (ch == "\r") { + if (peek() == "\n") ++S.pos; + ch = "\n"; + } else if (ch == "$" && peek() == "{") { + next(true, true); + S.brace_counter++; + tok = token(begin ? "template_head" : "template_substitution", content); + TEMPLATE_RAWS.set(tok, raw); + tok.template_end = false; + return tok; + } + + raw += ch; + if (ch == "\\") { + var tmp = S.pos; + var prev_is_tag = previous_token && (previous_token.type === "name" || previous_token.type === "punc" && (previous_token.value === ")" || previous_token.value === "]")); + ch = read_escaped_char(true, !prev_is_tag, true); + raw += S.text.substr(tmp, S.pos - tmp); + } + + content += ch; + } + S.template_braces.pop(); + tok = token(begin ? "template_head" : "template_substitution", content); + TEMPLATE_RAWS.set(tok, raw); + tok.template_end = true; + return tok; + }); + + function skip_line_comment(type) { + var regex_allowed = S.regex_allowed; + var i = find_eol(), ret; + if (i == -1) { + ret = S.text.substr(S.pos); + S.pos = S.text.length; + } else { + ret = S.text.substring(S.pos, i); + S.pos = i; + } + S.col = S.tokcol + (S.pos - S.tokpos); + S.comments_before.push(token(type, ret, true)); + S.regex_allowed = regex_allowed; + return next_token; + } + + var skip_multiline_comment = with_eof_error("Unterminated multiline comment", function() { + var regex_allowed = S.regex_allowed; + var i = find("*/", true); + var text = S.text.substring(S.pos, i).replace(/\r\n|\r|\u2028|\u2029/g, "\n"); + // update stream position + forward(get_full_char_length(text) /* text length doesn't count \r\n as 2 char while S.pos - i does */ + 2); + S.comments_before.push(token("comment2", text, true)); + S.newline_before = S.newline_before || text.includes("\n"); + S.regex_allowed = regex_allowed; + return next_token; + }); + + var read_name = with_eof_error("Unterminated identifier name", function() { + var name = [], ch, escaped = false; + var read_escaped_identifier_char = function() { + escaped = true; + next(); + if (peek() !== "u") { + parse_error("Expecting UnicodeEscapeSequence -- uXXXX or u{XXXX}"); + } + return read_escaped_char(false, true); + }; + + // Read first character (ID_Start) + if ((ch = peek()) === "\\") { + ch = read_escaped_identifier_char(); + if (!is_identifier_start(ch)) { + parse_error("First identifier char is an invalid identifier char"); + } + } else if (is_identifier_start(ch)) { + next(); + } else { + return ""; + } + + name.push(ch); + + // Read ID_Continue + while ((ch = peek()) != null) { + if ((ch = peek()) === "\\") { + ch = read_escaped_identifier_char(); + if (!is_identifier_char(ch)) { + parse_error("Invalid escaped identifier char"); + } + } else { + if (!is_identifier_char(ch)) { + break; + } + next(); + } + name.push(ch); + } + const name_str = name.join(""); + if (RESERVED_WORDS.has(name_str) && escaped) { + parse_error("Escaped characters are not allowed in keywords"); + } + return name_str; + }); + + var read_regexp = with_eof_error("Unterminated regular expression", function(source) { + var prev_backslash = false, ch, in_class = false; + while ((ch = next(true))) if (NEWLINE_CHARS.has(ch)) { + parse_error("Unexpected line terminator"); + } else if (prev_backslash) { + if (/^[\u0000-\u007F]$/.test(ch)) { + source += "\\" + ch; + } else { + // Remove the useless slash before the escape, but only for characters that won't be added to regexp syntax + source += ch; + } + prev_backslash = false; + } else if (ch == "[") { + in_class = true; + source += ch; + } else if (ch == "]" && in_class) { + in_class = false; + source += ch; + } else if (ch == "/" && !in_class) { + break; + } else if (ch == "\\") { + prev_backslash = true; + } else { + source += ch; + } + const flags = read_name(); + return token("regexp", "/" + source + "/" + flags); + }); + + function read_operator(prefix) { + function grow(op) { + if (!peek()) return op; + var bigger = op + peek(); + if (OPERATORS.has(bigger)) { + next(); + return grow(bigger); + } else { + return op; + } + } + return token("operator", grow(prefix || next())); + } + + function handle_slash() { + next(); + switch (peek()) { + case "/": + next(); + return skip_line_comment("comment1"); + case "*": + next(); + return skip_multiline_comment(); + } + return S.regex_allowed ? read_regexp("") : read_operator("/"); + } + + function handle_eq_sign() { + next(); + if (peek() === ">") { + next(); + return token("arrow", "=>"); + } else { + return read_operator("="); + } + } + + function handle_dot() { + next(); + if (is_digit(peek().charCodeAt(0))) { + return read_num("."); + } + if (peek() === ".") { + next(); // Consume second dot + next(); // Consume third dot + return token("expand", "..."); + } + + return token("punc", "."); + } + + function read_word() { + var word = read_name(); + if (prev_was_dot) return token("name", word); + return KEYWORDS_ATOM.has(word) ? token("atom", word) + : !KEYWORDS.has(word) ? token("name", word) + : OPERATORS.has(word) ? token("operator", word) + : token("keyword", word); + } + + function read_private_word() { + next(); + return token("privatename", read_name()); + } + + function with_eof_error(eof_error, cont) { + return function(x) { + try { + return cont(x); + } catch(ex) { + if (ex === EX_EOF) parse_error(eof_error); + else throw ex; + } + }; + } + + function next_token(force_regexp) { + if (force_regexp != null) + return read_regexp(force_regexp); + if (shebang && S.pos == 0 && looking_at("#!")) { + start_token(); + forward(2); + skip_line_comment("comment5"); + } + for (;;) { + skip_whitespace(); + start_token(); + if (html5_comments) { + if (looking_at("") && S.newline_before) { + forward(3); + skip_line_comment("comment4"); + continue; + } + } + var ch = peek(); + if (!ch) return token("eof"); + var code = ch.charCodeAt(0); + switch (code) { + case 34: case 39: return read_string(); + case 46: return handle_dot(); + case 47: { + var tok = handle_slash(); + if (tok === next_token) continue; + return tok; + } + case 61: return handle_eq_sign(); + case 63: { + if (!is_option_chain_op()) break; // Handled below + + next(); // ? + next(); // . + + return token("punc", "?."); + } + case 96: return read_template_characters(true); + case 123: + S.brace_counter++; + break; + case 125: + S.brace_counter--; + if (S.template_braces.length > 0 + && S.template_braces[S.template_braces.length - 1] === S.brace_counter) + return read_template_characters(false); + break; + } + if (is_digit(code)) return read_num(); + if (PUNC_CHARS.has(ch)) return token("punc", next()); + if (OPERATOR_CHARS.has(ch)) return read_operator(); + if (code == 92 || is_identifier_start(ch)) return read_word(); + if (code == 35) return read_private_word(); + break; + } + parse_error("Unexpected character '" + ch + "'"); + } + + next_token.next = next; + next_token.peek = peek; + + next_token.context = function(nc) { + if (nc) S = nc; + return S; + }; + + next_token.add_directive = function(directive) { + S.directive_stack[S.directive_stack.length - 1].push(directive); + + if (S.directives[directive] === undefined) { + S.directives[directive] = 1; + } else { + S.directives[directive]++; + } + }; + + next_token.push_directives_stack = function() { + S.directive_stack.push([]); + }; + + next_token.pop_directives_stack = function() { + var directives = S.directive_stack[S.directive_stack.length - 1]; + + for (var i = 0; i < directives.length; i++) { + S.directives[directives[i]]--; + } + + S.directive_stack.pop(); + }; + + next_token.has_directive = function(directive) { + return S.directives[directive] > 0; + }; + + return next_token; + +} + +/* -----[ Parser (constants) ]----- */ + +var UNARY_PREFIX = makePredicate([ + "typeof", + "void", + "delete", + "--", + "++", + "!", + "~", + "-", + "+" +]); + +var UNARY_POSTFIX = makePredicate([ "--", "++" ]); + +var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "??=", "&&=", "||=", "/=", "*=", "**=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]); + +var LOGICAL_ASSIGNMENT = makePredicate([ "??=", "&&=", "||=" ]); + +var PRECEDENCE = (function(a, ret) { + for (var i = 0; i < a.length; ++i) { + for (const op of a[i]) { + ret[op] = i + 1; + } + } + return ret; +})( + [ + ["||"], + ["??"], + ["&&"], + ["|"], + ["^"], + ["&"], + ["==", "===", "!=", "!=="], + ["<", ">", "<=", ">=", "in", "instanceof"], + [">>", "<<", ">>>"], + ["+", "-"], + ["*", "/", "%"], + ["**"] + ], + {} +); + +var ATOMIC_START_TOKEN = makePredicate([ "atom", "num", "big_int", "string", "regexp", "name"]); + +/* -----[ Parser ]----- */ + +function parse($TEXT, options) { + // maps start tokens to count of comments found outside of their parens + // Example: /* I count */ ( /* I don't */ foo() ) + // Useful because comments_before property of call with parens outside + // contains both comments inside and outside these parens. Used to find the + // right #__PURE__ comments for an expression + const outer_comments_before_counts = new WeakMap(); + + options = defaults(options, { + bare_returns : false, + ecma : null, // Legacy + expression : false, + filename : null, + html5_comments : true, + module : false, + shebang : true, + strict : false, + toplevel : null, + }, true); + + var S = { + input : (typeof $TEXT == "string" + ? tokenizer($TEXT, options.filename, + options.html5_comments, options.shebang) + : $TEXT), + token : null, + prev : null, + peeked : null, + in_function : 0, + in_async : -1, + in_generator : -1, + in_directives : true, + in_loop : 0, + labels : [] + }; + + S.token = next(); + + function is(type, value) { + return is_token(S.token, type, value); + } + + function peek() { return S.peeked || (S.peeked = S.input()); } + + function next() { + S.prev = S.token; + + if (!S.peeked) peek(); + S.token = S.peeked; + S.peeked = null; + S.in_directives = S.in_directives && ( + S.token.type == "string" || is("punc", ";") + ); + return S.token; + } + + function prev() { + return S.prev; + } + + function croak(msg, line, col, pos) { + var ctx = S.input.context(); + js_error(msg, + ctx.filename, + line != null ? line : ctx.tokline, + col != null ? col : ctx.tokcol, + pos != null ? pos : ctx.tokpos); + } + + function token_error(token, msg) { + croak(msg, token.line, token.col); + } + + function unexpected(token) { + if (token == null) + token = S.token; + token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")"); + } + + function expect_token(type, val) { + if (is(type, val)) { + return next(); + } + token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»"); + } + + function expect(punc) { return expect_token("punc", punc); } + + function has_newline_before(token) { + return token.nlb || !token.comments_before.every((comment) => !comment.nlb); + } + + function can_insert_semicolon() { + return !options.strict + && (is("eof") || is("punc", "}") || has_newline_before(S.token)); + } + + function is_in_generator() { + return S.in_generator === S.in_function; + } + + function is_in_async() { + return S.in_async === S.in_function; + } + + function can_await() { + return ( + S.in_async === S.in_function + || S.in_function === 0 && S.input.has_directive("use strict") + ); + } + + function semicolon(optional) { + if (is("punc", ";")) next(); + else if (!optional && !can_insert_semicolon()) unexpected(); + } + + function parenthesised() { + expect("("); + var exp = expression(true); + expect(")"); + return exp; + } + + function embed_tokens(parser) { + return function _embed_tokens_wrapper(...args) { + const start = S.token; + const expr = parser(...args); + expr.start = start; + expr.end = prev(); + return expr; + }; + } + + function handle_regexp() { + if (is("operator", "/") || is("operator", "/=")) { + S.peeked = null; + S.token = S.input(S.token.value.substr(1)); // force regexp + } + } + + var statement = embed_tokens(function statement(is_export_default, is_for_body, is_if_body) { + handle_regexp(); + switch (S.token.type) { + case "string": + if (S.in_directives) { + var token = peek(); + if (!LATEST_RAW.includes("\\") + && (is_token(token, "punc", ";") + || is_token(token, "punc", "}") + || has_newline_before(token) + || is_token(token, "eof"))) { + S.input.add_directive(S.token.value); + } else { + S.in_directives = false; + } + } + var dir = S.in_directives, stat = simple_statement(); + return dir && stat.body instanceof AST_String ? new AST_Directive(stat.body) : stat; + case "template_head": + case "num": + case "big_int": + case "regexp": + case "operator": + case "atom": + return simple_statement(); + + case "name": + case "privatename": + if(is("privatename") && !S.in_class) + croak("Private field must be used in an enclosing class"); + + if (S.token.value == "async" && is_token(peek(), "keyword", "function")) { + next(); + next(); + if (is_for_body) { + croak("functions are not allowed as the body of a loop"); + } + return function_(AST_Defun, false, true, is_export_default); + } + if (S.token.value == "import" && !is_token(peek(), "punc", "(") && !is_token(peek(), "punc", ".")) { + next(); + var node = import_statement(); + semicolon(); + return node; + } + return is_token(peek(), "punc", ":") + ? labeled_statement() + : simple_statement(); + + case "punc": + switch (S.token.value) { + case "{": + return new AST_BlockStatement({ + start : S.token, + body : block_(), + end : prev() + }); + case "[": + case "(": + return simple_statement(); + case ";": + S.in_directives = false; + next(); + return new AST_EmptyStatement(); + default: + unexpected(); + } + + case "keyword": + switch (S.token.value) { + case "break": + next(); + return break_cont(AST_Break); + + case "continue": + next(); + return break_cont(AST_Continue); + + case "debugger": + next(); + semicolon(); + return new AST_Debugger(); + + case "do": + next(); + var body = in_loop(statement); + expect_token("keyword", "while"); + var condition = parenthesised(); + semicolon(true); + return new AST_Do({ + body : body, + condition : condition + }); + + case "while": + next(); + return new AST_While({ + condition : parenthesised(), + body : in_loop(function() { return statement(false, true); }) + }); + + case "for": + next(); + return for_(); + + case "class": + next(); + if (is_for_body) { + croak("classes are not allowed as the body of a loop"); + } + if (is_if_body) { + croak("classes are not allowed as the body of an if"); + } + return class_(AST_DefClass, is_export_default); + + case "function": + next(); + if (is_for_body) { + croak("functions are not allowed as the body of a loop"); + } + return function_(AST_Defun, false, false, is_export_default); + + case "if": + next(); + return if_(); + + case "return": + if (S.in_function == 0 && !options.bare_returns) + croak("'return' outside of function"); + next(); + var value = null; + if (is("punc", ";")) { + next(); + } else if (!can_insert_semicolon()) { + value = expression(true); + semicolon(); + } + return new AST_Return({ + value: value + }); + + case "switch": + next(); + return new AST_Switch({ + expression : parenthesised(), + body : in_loop(switch_body_) + }); + + case "throw": + next(); + if (has_newline_before(S.token)) + croak("Illegal newline after 'throw'"); + var value = expression(true); + semicolon(); + return new AST_Throw({ + value: value + }); + + case "try": + next(); + return try_(); + + case "var": + next(); + var node = var_(); + semicolon(); + return node; + + case "let": + next(); + var node = let_(); + semicolon(); + return node; + + case "const": + next(); + var node = const_(); + semicolon(); + return node; + + case "with": + if (S.input.has_directive("use strict")) { + croak("Strict mode may not include a with statement"); + } + next(); + return new AST_With({ + expression : parenthesised(), + body : statement() + }); + + case "export": + if (!is_token(peek(), "punc", "(")) { + next(); + var node = export_statement(); + if (is("punc", ";")) semicolon(); + return node; + } + } + } + unexpected(); + }); + + function labeled_statement() { + var label = as_symbol(AST_Label); + if (label.name === "await" && is_in_async()) { + token_error(S.prev, "await cannot be used as label inside async function"); + } + if (S.labels.some((l) => l.name === label.name)) { + // ECMA-262, 12.12: An ECMAScript program is considered + // syntactically incorrect if it contains a + // LabelledStatement that is enclosed by a + // LabelledStatement with the same Identifier as label. + croak("Label " + label.name + " defined twice"); + } + expect(":"); + S.labels.push(label); + var stat = statement(); + S.labels.pop(); + if (!(stat instanceof AST_IterationStatement)) { + // check for `continue` that refers to this label. + // those should be reported as syntax errors. + // https://github.com/mishoo/UglifyJS2/issues/287 + label.references.forEach(function(ref) { + if (ref instanceof AST_Continue) { + ref = ref.label.start; + croak("Continue label `" + label.name + "` refers to non-IterationStatement.", + ref.line, ref.col, ref.pos); + } + }); + } + return new AST_LabeledStatement({ body: stat, label: label }); + } + + function simple_statement(tmp) { + return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) }); + } + + function break_cont(type) { + var label = null, ldef; + if (!can_insert_semicolon()) { + label = as_symbol(AST_LabelRef, true); + } + if (label != null) { + ldef = S.labels.find((l) => l.name === label.name); + if (!ldef) + croak("Undefined label " + label.name); + label.thedef = ldef; + } else if (S.in_loop == 0) + croak(type.TYPE + " not inside a loop or switch"); + semicolon(); + var stat = new type({ label: label }); + if (ldef) ldef.references.push(stat); + return stat; + } + + function for_() { + var for_await_error = "`for await` invalid in this context"; + var await_tok = S.token; + if (await_tok.type == "name" && await_tok.value == "await") { + if (!can_await()) { + token_error(await_tok, for_await_error); + } + next(); + } else { + await_tok = false; + } + expect("("); + var init = null; + if (!is("punc", ";")) { + init = + is("keyword", "var") ? (next(), var_(true)) : + is("keyword", "let") ? (next(), let_(true)) : + is("keyword", "const") ? (next(), const_(true)) : + expression(true, true); + var is_in = is("operator", "in"); + var is_of = is("name", "of"); + if (await_tok && !is_of) { + token_error(await_tok, for_await_error); + } + if (is_in || is_of) { + if (init instanceof AST_Definitions) { + if (init.definitions.length > 1) + token_error(init.start, "Only one variable declaration allowed in for..in loop"); + } else if (!(is_assignable(init) || (init = to_destructuring(init)) instanceof AST_Destructuring)) { + token_error(init.start, "Invalid left-hand side in for..in loop"); + } + next(); + if (is_in) { + return for_in(init); + } else { + return for_of(init, !!await_tok); + } + } + } else if (await_tok) { + token_error(await_tok, for_await_error); + } + return regular_for(init); + } + + function regular_for(init) { + expect(";"); + var test = is("punc", ";") ? null : expression(true); + expect(";"); + var step = is("punc", ")") ? null : expression(true); + expect(")"); + return new AST_For({ + init : init, + condition : test, + step : step, + body : in_loop(function() { return statement(false, true); }) + }); + } + + function for_of(init, is_await) { + var lhs = init instanceof AST_Definitions ? init.definitions[0].name : null; + var obj = expression(true); + expect(")"); + return new AST_ForOf({ + await : is_await, + init : init, + name : lhs, + object : obj, + body : in_loop(function() { return statement(false, true); }) + }); + } + + function for_in(init) { + var obj = expression(true); + expect(")"); + return new AST_ForIn({ + init : init, + object : obj, + body : in_loop(function() { return statement(false, true); }) + }); + } + + var arrow_function = function(start, argnames, is_async) { + if (has_newline_before(S.token)) { + croak("Unexpected newline before arrow (=>)"); + } + + expect_token("arrow", "=>"); + + var body = _function_body(is("punc", "{"), false, is_async); + + var end = + body instanceof Array && body.length ? body[body.length - 1].end : + body instanceof Array ? start : + body.end; + + return new AST_Arrow({ + start : start, + end : end, + async : is_async, + argnames : argnames, + body : body + }); + }; + + var function_ = function(ctor, is_generator_property, is_async, is_export_default) { + var in_statement = ctor === AST_Defun; + var is_generator = is("operator", "*"); + if (is_generator) { + next(); + } + + var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null; + if (in_statement && !name) { + if (is_export_default) { + ctor = AST_Function; + } else { + unexpected(); + } + } + + if (name && ctor !== AST_Accessor && !(name instanceof AST_SymbolDeclaration)) + unexpected(prev()); + + var args = []; + var body = _function_body(true, is_generator || is_generator_property, is_async, name, args); + return new ctor({ + start : args.start, + end : body.end, + is_generator: is_generator, + async : is_async, + name : name, + argnames: args, + body : body + }); + }; + + class UsedParametersTracker { + constructor(is_parameter, strict, duplicates_ok = false) { + this.is_parameter = is_parameter; + this.duplicates_ok = duplicates_ok; + this.parameters = new Set(); + this.duplicate = null; + this.default_assignment = false; + this.spread = false; + this.strict_mode = !!strict; + } + add_parameter(token) { + if (this.parameters.has(token.value)) { + if (this.duplicate === null) { + this.duplicate = token; + } + this.check_strict(); + } else { + this.parameters.add(token.value); + if (this.is_parameter) { + switch (token.value) { + case "arguments": + case "eval": + case "yield": + if (this.strict_mode) { + token_error(token, "Unexpected " + token.value + " identifier as parameter inside strict mode"); + } + break; + default: + if (RESERVED_WORDS.has(token.value)) { + unexpected(); + } + } + } + } + } + mark_default_assignment(token) { + if (this.default_assignment === false) { + this.default_assignment = token; + } + } + mark_spread(token) { + if (this.spread === false) { + this.spread = token; + } + } + mark_strict_mode() { + this.strict_mode = true; + } + is_strict() { + return this.default_assignment !== false || this.spread !== false || this.strict_mode; + } + check_strict() { + if (this.is_strict() && this.duplicate !== null && !this.duplicates_ok) { + token_error(this.duplicate, "Parameter " + this.duplicate.value + " was used already"); + } + } + } + + function parameters(params) { + var used_parameters = new UsedParametersTracker(true, S.input.has_directive("use strict")); + + expect("("); + + while (!is("punc", ")")) { + var param = parameter(used_parameters); + params.push(param); + + if (!is("punc", ")")) { + expect(","); + } + + if (param instanceof AST_Expansion) { + break; + } + } + + next(); + } + + function parameter(used_parameters, symbol_type) { + var param; + var expand = false; + if (used_parameters === undefined) { + used_parameters = new UsedParametersTracker(true, S.input.has_directive("use strict")); + } + if (is("expand", "...")) { + expand = S.token; + used_parameters.mark_spread(S.token); + next(); + } + param = binding_element(used_parameters, symbol_type); + + if (is("operator", "=") && expand === false) { + used_parameters.mark_default_assignment(S.token); + next(); + param = new AST_DefaultAssign({ + start: param.start, + left: param, + operator: "=", + right: expression(false), + end: S.token + }); + } + + if (expand !== false) { + if (!is("punc", ")")) { + unexpected(); + } + param = new AST_Expansion({ + start: expand, + expression: param, + end: expand + }); + } + used_parameters.check_strict(); + + return param; + } + + function binding_element(used_parameters, symbol_type) { + var elements = []; + var first = true; + var is_expand = false; + var expand_token; + var first_token = S.token; + if (used_parameters === undefined) { + const strict = S.input.has_directive("use strict"); + const duplicates_ok = symbol_type === AST_SymbolVar; + used_parameters = new UsedParametersTracker(false, strict, duplicates_ok); + } + symbol_type = symbol_type === undefined ? AST_SymbolFunarg : symbol_type; + if (is("punc", "[")) { + next(); + while (!is("punc", "]")) { + if (first) { + first = false; + } else { + expect(","); + } + + if (is("expand", "...")) { + is_expand = true; + expand_token = S.token; + used_parameters.mark_spread(S.token); + next(); + } + if (is("punc")) { + switch (S.token.value) { + case ",": + elements.push(new AST_Hole({ + start: S.token, + end: S.token + })); + continue; + case "]": // Trailing comma after last element + break; + case "[": + case "{": + elements.push(binding_element(used_parameters, symbol_type)); + break; + default: + unexpected(); + } + } else if (is("name")) { + used_parameters.add_parameter(S.token); + elements.push(as_symbol(symbol_type)); + } else { + croak("Invalid function parameter"); + } + if (is("operator", "=") && is_expand === false) { + used_parameters.mark_default_assignment(S.token); + next(); + elements[elements.length - 1] = new AST_DefaultAssign({ + start: elements[elements.length - 1].start, + left: elements[elements.length - 1], + operator: "=", + right: expression(false), + end: S.token + }); + } + if (is_expand) { + if (!is("punc", "]")) { + croak("Rest element must be last element"); + } + elements[elements.length - 1] = new AST_Expansion({ + start: expand_token, + expression: elements[elements.length - 1], + end: expand_token + }); + } + } + expect("]"); + used_parameters.check_strict(); + return new AST_Destructuring({ + start: first_token, + names: elements, + is_array: true, + end: prev() + }); + } else if (is("punc", "{")) { + next(); + while (!is("punc", "}")) { + if (first) { + first = false; + } else { + expect(","); + } + if (is("expand", "...")) { + is_expand = true; + expand_token = S.token; + used_parameters.mark_spread(S.token); + next(); + } + if (is("name") && (is_token(peek(), "punc") || is_token(peek(), "operator")) && [",", "}", "="].includes(peek().value)) { + used_parameters.add_parameter(S.token); + var start = prev(); + var value = as_symbol(symbol_type); + if (is_expand) { + elements.push(new AST_Expansion({ + start: expand_token, + expression: value, + end: value.end, + })); + } else { + elements.push(new AST_ObjectKeyVal({ + start: start, + key: value.name, + value: value, + end: value.end, + })); + } + } else if (is("punc", "}")) { + continue; // Allow trailing hole + } else { + var property_token = S.token; + var property = as_property_name(); + if (property === null) { + unexpected(prev()); + } else if (prev().type === "name" && !is("punc", ":")) { + elements.push(new AST_ObjectKeyVal({ + start: prev(), + key: property, + value: new symbol_type({ + start: prev(), + name: property, + end: prev() + }), + end: prev() + })); + } else { + expect(":"); + elements.push(new AST_ObjectKeyVal({ + start: property_token, + quote: property_token.quote, + key: property, + value: binding_element(used_parameters, symbol_type), + end: prev() + })); + } + } + if (is_expand) { + if (!is("punc", "}")) { + croak("Rest element must be last element"); + } + } else if (is("operator", "=")) { + used_parameters.mark_default_assignment(S.token); + next(); + elements[elements.length - 1].value = new AST_DefaultAssign({ + start: elements[elements.length - 1].value.start, + left: elements[elements.length - 1].value, + operator: "=", + right: expression(false), + end: S.token + }); + } + } + expect("}"); + used_parameters.check_strict(); + return new AST_Destructuring({ + start: first_token, + names: elements, + is_array: false, + end: prev() + }); + } else if (is("name")) { + used_parameters.add_parameter(S.token); + return as_symbol(symbol_type); + } else { + croak("Invalid function parameter"); + } + } + + function params_or_seq_(allow_arrows, maybe_sequence) { + var spread_token; + var invalid_sequence; + var trailing_comma; + var a = []; + expect("("); + while (!is("punc", ")")) { + if (spread_token) unexpected(spread_token); + if (is("expand", "...")) { + spread_token = S.token; + if (maybe_sequence) invalid_sequence = S.token; + next(); + a.push(new AST_Expansion({ + start: prev(), + expression: expression(), + end: S.token, + })); + } else { + a.push(expression()); + } + if (!is("punc", ")")) { + expect(","); + if (is("punc", ")")) { + trailing_comma = prev(); + if (maybe_sequence) invalid_sequence = trailing_comma; + } + } + } + expect(")"); + if (allow_arrows && is("arrow", "=>")) { + if (spread_token && trailing_comma) unexpected(trailing_comma); + } else if (invalid_sequence) { + unexpected(invalid_sequence); + } + return a; + } + + function _function_body(block, generator, is_async, name, args) { + var loop = S.in_loop; + var labels = S.labels; + var current_generator = S.in_generator; + var current_async = S.in_async; + ++S.in_function; + if (generator) + S.in_generator = S.in_function; + if (is_async) + S.in_async = S.in_function; + if (args) parameters(args); + if (block) + S.in_directives = true; + S.in_loop = 0; + S.labels = []; + if (block) { + S.input.push_directives_stack(); + var a = block_(); + if (name) _verify_symbol(name); + if (args) args.forEach(_verify_symbol); + S.input.pop_directives_stack(); + } else { + var a = [new AST_Return({ + start: S.token, + value: expression(false), + end: S.token + })]; + } + --S.in_function; + S.in_loop = loop; + S.labels = labels; + S.in_generator = current_generator; + S.in_async = current_async; + return a; + } + + function _await_expression() { + // Previous token must be "await" and not be interpreted as an identifier + if (!can_await()) { + croak("Unexpected await expression outside async function", + S.prev.line, S.prev.col, S.prev.pos); + } + // the await expression is parsed as a unary expression in Babel + return new AST_Await({ + start: prev(), + end: S.token, + expression : maybe_unary(true), + }); + } + + function _yield_expression() { + // Previous token must be keyword yield and not be interpret as an identifier + if (!is_in_generator()) { + croak("Unexpected yield expression outside generator function", + S.prev.line, S.prev.col, S.prev.pos); + } + var start = S.token; + var star = false; + var has_expression = true; + + // Attempt to get expression or star (and then the mandatory expression) + // behind yield on the same line. + // + // If nothing follows on the same line of the yieldExpression, + // it should default to the value `undefined` for yield to return. + // In that case, the `undefined` stored as `null` in ast. + // + // Note 1: It isn't allowed for yield* to close without an expression + // Note 2: If there is a nlb between yield and star, it is interpret as + // yield * + if (can_insert_semicolon() || + (is("punc") && PUNC_AFTER_EXPRESSION.has(S.token.value))) { + has_expression = false; + + } else if (is("operator", "*")) { + star = true; + next(); + } + + return new AST_Yield({ + start : start, + is_star : star, + expression : has_expression ? expression() : null, + end : prev() + }); + } + + function if_() { + var cond = parenthesised(), body = statement(false, false, true), belse = null; + if (is("keyword", "else")) { + next(); + belse = statement(false, false, true); + } + return new AST_If({ + condition : cond, + body : body, + alternative : belse + }); + } + + function block_() { + expect("{"); + var a = []; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + a.push(statement()); + } + next(); + return a; + } + + function switch_body_() { + expect("{"); + var a = [], cur = null, branch = null, tmp; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + if (is("keyword", "case")) { + if (branch) branch.end = prev(); + cur = []; + branch = new AST_Case({ + start : (tmp = S.token, next(), tmp), + expression : expression(true), + body : cur + }); + a.push(branch); + expect(":"); + } else if (is("keyword", "default")) { + if (branch) branch.end = prev(); + cur = []; + branch = new AST_Default({ + start : (tmp = S.token, next(), expect(":"), tmp), + body : cur + }); + a.push(branch); + } else { + if (!cur) unexpected(); + cur.push(statement()); + } + } + if (branch) branch.end = prev(); + next(); + return a; + } + + function try_() { + var body, bcatch = null, bfinally = null; + body = new AST_TryBlock({ + start : S.token, + body : block_(), + end : prev(), + }); + if (is("keyword", "catch")) { + var start = S.token; + next(); + if (is("punc", "{")) { + var name = null; + } else { + expect("("); + var name = parameter(undefined, AST_SymbolCatch); + expect(")"); + } + bcatch = new AST_Catch({ + start : start, + argname : name, + body : block_(), + end : prev() + }); + } + if (is("keyword", "finally")) { + var start = S.token; + next(); + bfinally = new AST_Finally({ + start : start, + body : block_(), + end : prev() + }); + } + if (!bcatch && !bfinally) + croak("Missing catch/finally blocks"); + return new AST_Try({ + body : body, + bcatch : bcatch, + bfinally : bfinally + }); + } + + /** + * var + * vardef1 = 2, + * vardef2 = 3; + */ + function vardefs(no_in, kind) { + var var_defs = []; + var def; + for (;;) { + var sym_type = + kind === "var" ? AST_SymbolVar : + kind === "const" ? AST_SymbolConst : + kind === "let" ? AST_SymbolLet : null; + // var { a } = b + if (is("punc", "{") || is("punc", "[")) { + def = new AST_VarDef({ + start: S.token, + name: binding_element(undefined, sym_type), + value: is("operator", "=") ? (expect_token("operator", "="), expression(false, no_in)) : null, + end: prev() + }); + } else { + def = new AST_VarDef({ + start : S.token, + name : as_symbol(sym_type), + value : is("operator", "=") + ? (next(), expression(false, no_in)) + : !no_in && kind === "const" + ? croak("Missing initializer in const declaration") : null, + end : prev() + }); + if (def.name.name == "import") croak("Unexpected token: import"); + } + var_defs.push(def); + if (!is("punc", ",")) + break; + next(); + } + return var_defs; + } + + var var_ = function(no_in) { + return new AST_Var({ + start : prev(), + definitions : vardefs(no_in, "var"), + end : prev() + }); + }; + + var let_ = function(no_in) { + return new AST_Let({ + start : prev(), + definitions : vardefs(no_in, "let"), + end : prev() + }); + }; + + var const_ = function(no_in) { + return new AST_Const({ + start : prev(), + definitions : vardefs(no_in, "const"), + end : prev() + }); + }; + + var new_ = function(allow_calls) { + var start = S.token; + expect_token("operator", "new"); + if (is("punc", ".")) { + next(); + expect_token("name", "target"); + return subscripts(new AST_NewTarget({ + start : start, + end : prev() + }), allow_calls); + } + var newexp = expr_atom(false), args; + if (is("punc", "(")) { + next(); + args = expr_list(")", true); + } else { + args = []; + } + var call = new AST_New({ + start : start, + expression : newexp, + args : args, + end : prev() + }); + annotate(call); + return subscripts(call, allow_calls); + }; + + function as_atom_node() { + var tok = S.token, ret; + switch (tok.type) { + case "name": + ret = _make_symbol(AST_SymbolRef); + break; + case "num": + ret = new AST_Number({ + start: tok, + end: tok, + value: tok.value, + raw: LATEST_RAW + }); + break; + case "big_int": + ret = new AST_BigInt({ start: tok, end: tok, value: tok.value }); + break; + case "string": + ret = new AST_String({ + start : tok, + end : tok, + value : tok.value, + quote : tok.quote + }); + annotate(ret); + break; + case "regexp": + const [_, source, flags] = tok.value.match(/^\/(.*)\/(\w*)$/); + + ret = new AST_RegExp({ start: tok, end: tok, value: { source, flags } }); + break; + case "atom": + switch (tok.value) { + case "false": + ret = new AST_False({ start: tok, end: tok }); + break; + case "true": + ret = new AST_True({ start: tok, end: tok }); + break; + case "null": + ret = new AST_Null({ start: tok, end: tok }); + break; + } + break; + } + next(); + return ret; + } + + function to_fun_args(ex, default_seen_above) { + var insert_default = function(ex, default_value) { + if (default_value) { + return new AST_DefaultAssign({ + start: ex.start, + left: ex, + operator: "=", + right: default_value, + end: default_value.end + }); + } + return ex; + }; + if (ex instanceof AST_Object) { + return insert_default(new AST_Destructuring({ + start: ex.start, + end: ex.end, + is_array: false, + names: ex.properties.map(prop => to_fun_args(prop)) + }), default_seen_above); + } else if (ex instanceof AST_ObjectKeyVal) { + ex.value = to_fun_args(ex.value); + return insert_default(ex, default_seen_above); + } else if (ex instanceof AST_Hole) { + return ex; + } else if (ex instanceof AST_Destructuring) { + ex.names = ex.names.map(name => to_fun_args(name)); + return insert_default(ex, default_seen_above); + } else if (ex instanceof AST_SymbolRef) { + return insert_default(new AST_SymbolFunarg({ + name: ex.name, + start: ex.start, + end: ex.end + }), default_seen_above); + } else if (ex instanceof AST_Expansion) { + ex.expression = to_fun_args(ex.expression); + return insert_default(ex, default_seen_above); + } else if (ex instanceof AST_Array) { + return insert_default(new AST_Destructuring({ + start: ex.start, + end: ex.end, + is_array: true, + names: ex.elements.map(elm => to_fun_args(elm)) + }), default_seen_above); + } else if (ex instanceof AST_Assign) { + return insert_default(to_fun_args(ex.left, ex.right), default_seen_above); + } else if (ex instanceof AST_DefaultAssign) { + ex.left = to_fun_args(ex.left); + return ex; + } else { + croak("Invalid function parameter", ex.start.line, ex.start.col); + } + } + + var expr_atom = function(allow_calls, allow_arrows) { + if (is("operator", "new")) { + return new_(allow_calls); + } + if (is("name", "import") && is_token(peek(), "punc", ".")) { + return import_meta(allow_calls); + } + var start = S.token; + var peeked; + var async = is("name", "async") + && (peeked = peek()).value != "[" + && peeked.type != "arrow" + && as_atom_node(); + if (is("punc")) { + switch (S.token.value) { + case "(": + if (async && !allow_calls) break; + var exprs = params_or_seq_(allow_arrows, !async); + if (allow_arrows && is("arrow", "=>")) { + return arrow_function(start, exprs.map(e => to_fun_args(e)), !!async); + } + var ex = async ? new AST_Call({ + expression: async, + args: exprs + }) : to_expr_or_sequence(start, exprs); + if (ex.start) { + const outer_comments_before = start.comments_before.length; + outer_comments_before_counts.set(start, outer_comments_before); + ex.start.comments_before.unshift(...start.comments_before); + start.comments_before = ex.start.comments_before; + if (outer_comments_before == 0 && start.comments_before.length > 0) { + var comment = start.comments_before[0]; + if (!comment.nlb) { + comment.nlb = start.nlb; + start.nlb = false; + } + } + start.comments_after = ex.start.comments_after; + } + ex.start = start; + var end = prev(); + if (ex.end) { + end.comments_before = ex.end.comments_before; + ex.end.comments_after.push(...end.comments_after); + end.comments_after = ex.end.comments_after; + } + ex.end = end; + if (ex instanceof AST_Call) annotate(ex); + return subscripts(ex, allow_calls); + case "[": + return subscripts(array_(), allow_calls); + case "{": + return subscripts(object_or_destructuring_(), allow_calls); + } + if (!async) unexpected(); + } + if (allow_arrows && is("name") && is_token(peek(), "arrow")) { + var param = new AST_SymbolFunarg({ + name: S.token.value, + start: start, + end: start, + }); + next(); + return arrow_function(start, [param], !!async); + } + if (is("keyword", "function")) { + next(); + var func = function_(AST_Function, false, !!async); + func.start = start; + func.end = prev(); + return subscripts(func, allow_calls); + } + if (async) return subscripts(async, allow_calls); + if (is("keyword", "class")) { + next(); + var cls = class_(AST_ClassExpression); + cls.start = start; + cls.end = prev(); + return subscripts(cls, allow_calls); + } + if (is("template_head")) { + return subscripts(template_string(), allow_calls); + } + if (ATOMIC_START_TOKEN.has(S.token.type)) { + return subscripts(as_atom_node(), allow_calls); + } + unexpected(); + }; + + function template_string() { + var segments = [], start = S.token; + + segments.push(new AST_TemplateSegment({ + start: S.token, + raw: TEMPLATE_RAWS.get(S.token), + value: S.token.value, + end: S.token + })); + + while (!S.token.template_end) { + next(); + handle_regexp(); + segments.push(expression(true)); + + segments.push(new AST_TemplateSegment({ + start: S.token, + raw: TEMPLATE_RAWS.get(S.token), + value: S.token.value, + end: S.token + })); + } + next(); + + return new AST_TemplateString({ + start: start, + segments: segments, + end: S.token + }); + } + + function expr_list(closing, allow_trailing_comma, allow_empty) { + var first = true, a = []; + while (!is("punc", closing)) { + if (first) first = false; else expect(","); + if (allow_trailing_comma && is("punc", closing)) break; + if (is("punc", ",") && allow_empty) { + a.push(new AST_Hole({ start: S.token, end: S.token })); + } else if (is("expand", "...")) { + next(); + a.push(new AST_Expansion({start: prev(), expression: expression(),end: S.token})); + } else { + a.push(expression(false)); + } + } + next(); + return a; + } + + var array_ = embed_tokens(function() { + expect("["); + return new AST_Array({ + elements: expr_list("]", !options.strict, true) + }); + }); + + var create_accessor = embed_tokens((is_generator, is_async) => { + return function_(AST_Accessor, is_generator, is_async); + }); + + var object_or_destructuring_ = embed_tokens(function object_or_destructuring_() { + var start = S.token, first = true, a = []; + expect("{"); + while (!is("punc", "}")) { + if (first) first = false; else expect(","); + if (!options.strict && is("punc", "}")) + // allow trailing comma + break; + + start = S.token; + if (start.type == "expand") { + next(); + a.push(new AST_Expansion({ + start: start, + expression: expression(false), + end: prev(), + })); + continue; + } + if(is("privatename")) { + croak("private fields are not allowed in an object"); + } + var name = as_property_name(); + var value; + + // Check property and fetch value + if (!is("punc", ":")) { + var concise = concise_method_or_getset(name, start); + if (concise) { + a.push(concise); + continue; + } + + value = new AST_SymbolRef({ + start: prev(), + name: name, + end: prev() + }); + } else if (name === null) { + unexpected(prev()); + } else { + next(); // `:` - see first condition + value = expression(false); + } + + // Check for default value and alter value accordingly if necessary + if (is("operator", "=")) { + next(); + value = new AST_Assign({ + start: start, + left: value, + operator: "=", + right: expression(false), + logical: false, + end: prev() + }); + } + + // Create property + const kv = new AST_ObjectKeyVal({ + start: start, + quote: start.quote, + key: name instanceof AST_Node ? name : "" + name, + value: value, + end: prev() + }); + a.push(annotate(kv)); + } + next(); + return new AST_Object({ properties: a }); + }); + + function class_(KindOfClass, is_export_default) { + var start, method, class_name, extends_, a = []; + + S.input.push_directives_stack(); // Push directive stack, but not scope stack + S.input.add_directive("use strict"); + + if (S.token.type == "name" && S.token.value != "extends") { + class_name = as_symbol(KindOfClass === AST_DefClass ? AST_SymbolDefClass : AST_SymbolClass); + } + + if (KindOfClass === AST_DefClass && !class_name) { + if (is_export_default) { + KindOfClass = AST_ClassExpression; + } else { + unexpected(); + } + } + + if (S.token.value == "extends") { + next(); + extends_ = expression(true); + } + + expect("{"); + // mark in class feild, + const save_in_class = S.in_class; + S.in_class = true; + while (is("punc", ";")) { next(); } // Leading semicolons are okay in class bodies. + while (!is("punc", "}")) { + start = S.token; + method = concise_method_or_getset(as_property_name(), start, true); + if (!method) { unexpected(); } + a.push(method); + while (is("punc", ";")) { next(); } + } + // mark in class feild, + S.in_class = save_in_class; + + S.input.pop_directives_stack(); + + next(); + + return new KindOfClass({ + start: start, + name: class_name, + extends: extends_, + properties: a, + end: prev(), + }); + } + + function concise_method_or_getset(name, start, is_class) { + const get_symbol_ast = (name, SymbolClass = AST_SymbolMethod) => { + if (typeof name === "string" || typeof name === "number") { + return new SymbolClass({ + start, + name: "" + name, + end: prev() + }); + } else if (name === null) { + unexpected(); + } + return name; + }; + + const is_not_method_start = () => + !is("punc", "(") && !is("punc", ",") && !is("punc", "}") && !is("punc", ";") && !is("operator", "="); + + var is_async = false; + var is_static = false; + var is_generator = false; + var is_private = false; + var accessor_type = null; + + if (is_class && name === "static" && is_not_method_start()) { + const static_block = class_static_block(); + if (static_block != null) { + return static_block; + } + is_static = true; + name = as_property_name(); + } + if (name === "async" && is_not_method_start()) { + is_async = true; + name = as_property_name(); + } + if (prev().type === "operator" && prev().value === "*") { + is_generator = true; + name = as_property_name(); + } + if ((name === "get" || name === "set") && is_not_method_start()) { + accessor_type = name; + name = as_property_name(); + } + if (prev().type === "privatename") { + is_private = true; + } + + const property_token = prev(); + + if (accessor_type != null) { + if (!is_private) { + const AccessorClass = accessor_type === "get" + ? AST_ObjectGetter + : AST_ObjectSetter; + + name = get_symbol_ast(name); + return annotate(new AccessorClass({ + start, + static: is_static, + key: name, + quote: name instanceof AST_SymbolMethod ? property_token.quote : undefined, + value: create_accessor(), + end: prev() + })); + } else { + const AccessorClass = accessor_type === "get" + ? AST_PrivateGetter + : AST_PrivateSetter; + + return annotate(new AccessorClass({ + start, + static: is_static, + key: get_symbol_ast(name), + value: create_accessor(), + end: prev(), + })); + } + } + + if (is("punc", "(")) { + name = get_symbol_ast(name); + const AST_MethodVariant = is_private + ? AST_PrivateMethod + : AST_ConciseMethod; + var node = new AST_MethodVariant({ + start : start, + static : is_static, + is_generator: is_generator, + async : is_async, + key : name, + quote : name instanceof AST_SymbolMethod ? + property_token.quote : undefined, + value : create_accessor(is_generator, is_async), + end : prev() + }); + return annotate(node); + } + + if (is_class) { + const key = get_symbol_ast(name, AST_SymbolClassProperty); + const quote = key instanceof AST_SymbolClassProperty + ? property_token.quote + : undefined; + const AST_ClassPropertyVariant = is_private + ? AST_ClassPrivateProperty + : AST_ClassProperty; + if (is("operator", "=")) { + next(); + return annotate( + new AST_ClassPropertyVariant({ + start, + static: is_static, + quote, + key, + value: expression(false), + end: prev() + }) + ); + } else if ( + is("name") + || is("privatename") + || is("operator", "*") + || is("punc", ";") + || is("punc", "}") + ) { + return annotate( + new AST_ClassPropertyVariant({ + start, + static: is_static, + quote, + key, + end: prev() + }) + ); + } + } + } + + function class_static_block() { + if (!is("punc", "{")) { + return null; + } + + const start = S.token; + const body = []; + + next(); + + while (!is("punc", "}")) { + body.push(statement()); + } + + next(); + + return new AST_ClassStaticBlock({ start, body, end: prev() }); + } + + function maybe_import_assertion() { + if (is("name", "assert") && !has_newline_before(S.token)) { + next(); + return object_or_destructuring_(); + } + return null; + } + + function import_statement() { + var start = prev(); + + var imported_name; + var imported_names; + if (is("name")) { + imported_name = as_symbol(AST_SymbolImport); + } + + if (is("punc", ",")) { + next(); + } + + imported_names = map_names(true); + + if (imported_names || imported_name) { + expect_token("name", "from"); + } + var mod_str = S.token; + if (mod_str.type !== "string") { + unexpected(); + } + next(); + + const assert_clause = maybe_import_assertion(); + + return new AST_Import({ + start, + imported_name, + imported_names, + module_name: new AST_String({ + start: mod_str, + value: mod_str.value, + quote: mod_str.quote, + end: mod_str, + }), + assert_clause, + end: S.token, + }); + } + + function import_meta(allow_calls) { + var start = S.token; + expect_token("name", "import"); + expect_token("punc", "."); + expect_token("name", "meta"); + return subscripts(new AST_ImportMeta({ + start: start, + end: prev() + }), allow_calls); + } + + function map_name(is_import) { + function make_symbol(type, quote) { + return new type({ + name: as_property_name(), + quote: quote || undefined, + start: prev(), + end: prev() + }); + } + + var foreign_type = is_import ? AST_SymbolImportForeign : AST_SymbolExportForeign; + var type = is_import ? AST_SymbolImport : AST_SymbolExport; + var start = S.token; + var foreign_name; + var name; + + if (is_import) { + foreign_name = make_symbol(foreign_type, start.quote); + } else { + name = make_symbol(type, start.quote); + } + if (is("name", "as")) { + next(); // The "as" word + if (is_import) { + name = make_symbol(type); + } else { + foreign_name = make_symbol(foreign_type, S.token.quote); + } + } else if (is_import) { + name = new type(foreign_name); + } else { + foreign_name = new foreign_type(name); + } + + return new AST_NameMapping({ + start: start, + foreign_name: foreign_name, + name: name, + end: prev(), + }); + } + + function map_nameAsterisk(is_import, import_or_export_foreign_name) { + var foreign_type = is_import ? AST_SymbolImportForeign : AST_SymbolExportForeign; + var type = is_import ? AST_SymbolImport : AST_SymbolExport; + var start = S.token; + var name, foreign_name; + var end = prev(); + + if (is_import) { + name = import_or_export_foreign_name; + } else { + foreign_name = import_or_export_foreign_name; + } + + name = name || new type({ + start: start, + name: "*", + end: end, + }); + + foreign_name = foreign_name || new foreign_type({ + start: start, + name: "*", + end: end, + }); + + return new AST_NameMapping({ + start: start, + foreign_name: foreign_name, + name: name, + end: end, + }); + } + + function map_names(is_import) { + var names; + if (is("punc", "{")) { + next(); + names = []; + while (!is("punc", "}")) { + names.push(map_name(is_import)); + if (is("punc", ",")) { + next(); + } + } + next(); + } else if (is("operator", "*")) { + var name; + next(); + if (is("name", "as")) { + next(); // The "as" word + name = is_import ? as_symbol(AST_SymbolImport) : as_symbol_or_string(AST_SymbolExportForeign); + } + names = [map_nameAsterisk(is_import, name)]; + } + return names; + } + + function export_statement() { + var start = S.token; + var is_default; + var exported_names; + + if (is("keyword", "default")) { + is_default = true; + next(); + } else if (exported_names = map_names(false)) { + if (is("name", "from")) { + next(); + + var mod_str = S.token; + if (mod_str.type !== "string") { + unexpected(); + } + next(); + + const assert_clause = maybe_import_assertion(); + + return new AST_Export({ + start: start, + is_default: is_default, + exported_names: exported_names, + module_name: new AST_String({ + start: mod_str, + value: mod_str.value, + quote: mod_str.quote, + end: mod_str, + }), + end: prev(), + assert_clause + }); + } else { + return new AST_Export({ + start: start, + is_default: is_default, + exported_names: exported_names, + end: prev(), + }); + } + } + + var node; + var exported_value; + var exported_definition; + if (is("punc", "{") + || is_default + && (is("keyword", "class") || is("keyword", "function")) + && is_token(peek(), "punc")) { + exported_value = expression(false); + semicolon(); + } else if ((node = statement(is_default)) instanceof AST_Definitions && is_default) { + unexpected(node.start); + } else if ( + node instanceof AST_Definitions + || node instanceof AST_Defun + || node instanceof AST_DefClass + ) { + exported_definition = node; + } else if ( + node instanceof AST_ClassExpression + || node instanceof AST_Function + ) { + exported_value = node; + } else if (node instanceof AST_SimpleStatement) { + exported_value = node.body; + } else { + unexpected(node.start); + } + + return new AST_Export({ + start: start, + is_default: is_default, + exported_value: exported_value, + exported_definition: exported_definition, + end: prev(), + assert_clause: null + }); + } + + function as_property_name() { + var tmp = S.token; + switch (tmp.type) { + case "punc": + if (tmp.value === "[") { + next(); + var ex = expression(false); + expect("]"); + return ex; + } else unexpected(tmp); + case "operator": + if (tmp.value === "*") { + next(); + return null; + } + if (!["delete", "in", "instanceof", "new", "typeof", "void"].includes(tmp.value)) { + unexpected(tmp); + } + /* falls through */ + case "name": + case "privatename": + case "string": + case "num": + case "big_int": + case "keyword": + case "atom": + next(); + return tmp.value; + default: + unexpected(tmp); + } + } + + function as_name() { + var tmp = S.token; + if (tmp.type != "name" && tmp.type != "privatename") unexpected(); + next(); + return tmp.value; + } + + function _make_symbol(type) { + var name = S.token.value; + return new (name == "this" ? AST_This : + name == "super" ? AST_Super : + type)({ + name : String(name), + start : S.token, + end : S.token + }); + } + + function _verify_symbol(sym) { + var name = sym.name; + if (is_in_generator() && name == "yield") { + token_error(sym.start, "Yield cannot be used as identifier inside generators"); + } + if (S.input.has_directive("use strict")) { + if (name == "yield") { + token_error(sym.start, "Unexpected yield identifier inside strict mode"); + } + if (sym instanceof AST_SymbolDeclaration && (name == "arguments" || name == "eval")) { + token_error(sym.start, "Unexpected " + name + " in strict mode"); + } + } + } + + function as_symbol(type, noerror) { + if (!is("name")) { + if (!noerror) croak("Name expected"); + return null; + } + var sym = _make_symbol(type); + _verify_symbol(sym); + next(); + return sym; + } + + function as_symbol_or_string(type) { + if (!is("name")) { + if (!is("string")) { + croak("Name or string expected"); + } + var tok = S.token; + var ret = new type({ + start : tok, + end : tok, + name : tok.value, + quote : tok.quote + }); + next(); + return ret; + } + var sym = _make_symbol(type); + _verify_symbol(sym); + next(); + return sym; + } + + // Annotate AST_Call, AST_Lambda or AST_New with the special comments + function annotate(node, before_token = node.start) { + var comments = before_token.comments_before; + const comments_outside_parens = outer_comments_before_counts.get(before_token); + var i = comments_outside_parens != null ? comments_outside_parens : comments.length; + while (--i >= 0) { + var comment = comments[i]; + if (/[@#]__/.test(comment.value)) { + if (/[@#]__PURE__/.test(comment.value)) { + set_annotation(node, _PURE); + break; + } + if (/[@#]__INLINE__/.test(comment.value)) { + set_annotation(node, _INLINE); + break; + } + if (/[@#]__NOINLINE__/.test(comment.value)) { + set_annotation(node, _NOINLINE); + break; + } + if (/[@#]__KEY__/.test(comment.value)) { + set_annotation(node, _KEY); + break; + } + if (/[@#]__MANGLE_PROP__/.test(comment.value)) { + set_annotation(node, _MANGLEPROP); + break; + } + } + } + return node; + } + + var subscripts = function(expr, allow_calls, is_chain) { + var start = expr.start; + if (is("punc", ".")) { + next(); + if(is("privatename") && !S.in_class) + croak("Private field must be used in an enclosing class"); + const AST_DotVariant = is("privatename") ? AST_DotHash : AST_Dot; + return annotate(subscripts(new AST_DotVariant({ + start : start, + expression : expr, + optional : false, + property : as_name(), + end : prev() + }), allow_calls, is_chain)); + } + if (is("punc", "[")) { + next(); + var prop = expression(true); + expect("]"); + return annotate(subscripts(new AST_Sub({ + start : start, + expression : expr, + optional : false, + property : prop, + end : prev() + }), allow_calls, is_chain)); + } + if (allow_calls && is("punc", "(")) { + next(); + var call = new AST_Call({ + start : start, + expression : expr, + optional : false, + args : call_args(), + end : prev() + }); + annotate(call); + return subscripts(call, true, is_chain); + } + + if (is("punc", "?.")) { + next(); + + let chain_contents; + + if (allow_calls && is("punc", "(")) { + next(); + + const call = new AST_Call({ + start, + optional: true, + expression: expr, + args: call_args(), + end: prev() + }); + annotate(call); + + chain_contents = subscripts(call, true, true); + } else if (is("name") || is("privatename")) { + if(is("privatename") && !S.in_class) + croak("Private field must be used in an enclosing class"); + const AST_DotVariant = is("privatename") ? AST_DotHash : AST_Dot; + chain_contents = annotate(subscripts(new AST_DotVariant({ + start, + expression: expr, + optional: true, + property: as_name(), + end: prev() + }), allow_calls, true)); + } else if (is("punc", "[")) { + next(); + const property = expression(true); + expect("]"); + chain_contents = annotate(subscripts(new AST_Sub({ + start, + expression: expr, + optional: true, + property, + end: prev() + }), allow_calls, true)); + } + + if (!chain_contents) unexpected(); + + if (chain_contents instanceof AST_Chain) return chain_contents; + + return new AST_Chain({ + start, + expression: chain_contents, + end: prev() + }); + } + + if (is("template_head")) { + if (is_chain) { + // a?.b`c` is a syntax error + unexpected(); + } + + return subscripts(new AST_PrefixedTemplateString({ + start: start, + prefix: expr, + template_string: template_string(), + end: prev() + }), allow_calls); + } + return expr; + }; + + function call_args() { + var args = []; + while (!is("punc", ")")) { + if (is("expand", "...")) { + next(); + args.push(new AST_Expansion({ + start: prev(), + expression: expression(false), + end: prev() + })); + } else { + args.push(expression(false)); + } + if (!is("punc", ")")) { + expect(","); + } + } + next(); + return args; + } + + var maybe_unary = function(allow_calls, allow_arrows) { + var start = S.token; + if (start.type == "name" && start.value == "await" && can_await()) { + next(); + return _await_expression(); + } + if (is("operator") && UNARY_PREFIX.has(start.value)) { + next(); + handle_regexp(); + var ex = make_unary(AST_UnaryPrefix, start, maybe_unary(allow_calls)); + ex.start = start; + ex.end = prev(); + return ex; + } + var val = expr_atom(allow_calls, allow_arrows); + while (is("operator") && UNARY_POSTFIX.has(S.token.value) && !has_newline_before(S.token)) { + if (val instanceof AST_Arrow) unexpected(); + val = make_unary(AST_UnaryPostfix, S.token, val); + val.start = start; + val.end = S.token; + next(); + } + return val; + }; + + function make_unary(ctor, token, expr) { + var op = token.value; + switch (op) { + case "++": + case "--": + if (!is_assignable(expr)) + croak("Invalid use of " + op + " operator", token.line, token.col, token.pos); + break; + case "delete": + if (expr instanceof AST_SymbolRef && S.input.has_directive("use strict")) + croak("Calling delete on expression not allowed in strict mode", expr.start.line, expr.start.col, expr.start.pos); + break; + } + return new ctor({ operator: op, expression: expr }); + } + + var expr_op = function(left, min_prec, no_in) { + var op = is("operator") ? S.token.value : null; + if (op == "in" && no_in) op = null; + if (op == "**" && left instanceof AST_UnaryPrefix + /* unary token in front not allowed - parenthesis required */ + && !is_token(left.start, "punc", "(") + && left.operator !== "--" && left.operator !== "++") + unexpected(left.start); + var prec = op != null ? PRECEDENCE[op] : null; + if (prec != null && (prec > min_prec || (op === "**" && min_prec === prec))) { + next(); + var right = expr_ops(no_in, prec, true); + return expr_op(new AST_Binary({ + start : left.start, + left : left, + operator : op, + right : right, + end : right.end + }), min_prec, no_in); + } + return left; + }; + + function expr_ops(no_in, min_prec, allow_calls, allow_arrows) { + // maybe_unary won't return us a AST_SymbolPrivateProperty + if (!no_in && min_prec < PRECEDENCE["in"] && is("privatename")) { + if(!S.in_class) { + croak("Private field must be used in an enclosing class"); + } + + const start = S.token; + const key = new AST_SymbolPrivateProperty({ + start, + name: start.value, + end: start + }); + next(); + expect_token("operator", "in"); + + const private_in = new AST_PrivateIn({ + start, + key, + value: expr_ops(no_in, PRECEDENCE["in"], true), + end: prev() + }); + + return expr_op(private_in, 0, no_in); + } else { + return expr_op(maybe_unary(allow_calls, allow_arrows), min_prec, no_in); + } + } + + var maybe_conditional = function(no_in) { + var start = S.token; + var expr = expr_ops(no_in, 0, true, true); + if (is("operator", "?")) { + next(); + var yes = expression(false); + expect(":"); + return new AST_Conditional({ + start : start, + condition : expr, + consequent : yes, + alternative : expression(false, no_in), + end : prev() + }); + } + return expr; + }; + + function is_assignable(expr) { + return expr instanceof AST_PropAccess || expr instanceof AST_SymbolRef; + } + + function to_destructuring(node) { + if (node instanceof AST_Object) { + node = new AST_Destructuring({ + start: node.start, + names: node.properties.map(to_destructuring), + is_array: false, + end: node.end + }); + } else if (node instanceof AST_Array) { + var names = []; + + for (var i = 0; i < node.elements.length; i++) { + // Only allow expansion as last element + if (node.elements[i] instanceof AST_Expansion) { + if (i + 1 !== node.elements.length) { + token_error(node.elements[i].start, "Spread must the be last element in destructuring array"); + } + node.elements[i].expression = to_destructuring(node.elements[i].expression); + } + + names.push(to_destructuring(node.elements[i])); + } + + node = new AST_Destructuring({ + start: node.start, + names: names, + is_array: true, + end: node.end + }); + } else if (node instanceof AST_ObjectProperty) { + node.value = to_destructuring(node.value); + } else if (node instanceof AST_Assign) { + node = new AST_DefaultAssign({ + start: node.start, + left: node.left, + operator: "=", + right: node.right, + end: node.end + }); + } + return node; + } + + // In ES6, AssignmentExpression can also be an ArrowFunction + var maybe_assign = function(no_in) { + handle_regexp(); + var start = S.token; + + if (start.type == "name" && start.value == "yield") { + if (is_in_generator()) { + next(); + return _yield_expression(); + } else if (S.input.has_directive("use strict")) { + token_error(S.token, "Unexpected yield identifier inside strict mode"); + } + } + + var left = maybe_conditional(no_in); + var val = S.token.value; + + if (is("operator") && ASSIGNMENT.has(val)) { + if (is_assignable(left) || (left = to_destructuring(left)) instanceof AST_Destructuring) { + next(); + + return new AST_Assign({ + start : start, + left : left, + operator : val, + right : maybe_assign(no_in), + logical : LOGICAL_ASSIGNMENT.has(val), + end : prev() + }); + } + croak("Invalid assignment"); + } + return left; + }; + + var to_expr_or_sequence = function(start, exprs) { + if (exprs.length === 1) { + return exprs[0]; + } else if (exprs.length > 1) { + return new AST_Sequence({ start, expressions: exprs, end: peek() }); + } else { + croak("Invalid parenthesized expression"); + } + }; + + var expression = function(commas, no_in) { + var start = S.token; + var exprs = []; + while (true) { + exprs.push(maybe_assign(no_in)); + if (!commas || !is("punc", ",")) break; + next(); + commas = true; + } + return to_expr_or_sequence(start, exprs); + }; + + function in_loop(cont) { + ++S.in_loop; + var ret = cont(); + --S.in_loop; + return ret; + } + + if (options.expression) { + return expression(true); + } + + return (function parse_toplevel() { + var start = S.token; + var body = []; + S.input.push_directives_stack(); + if (options.module) S.input.add_directive("use strict"); + while (!is("eof")) { + body.push(statement()); + } + S.input.pop_directives_stack(); + var end = prev(); + var toplevel = options.toplevel; + if (toplevel) { + toplevel.body = toplevel.body.concat(body); + toplevel.end = end; + } else { + toplevel = new AST_Toplevel({ start: start, body: body, end: end }); + } + TEMPLATE_RAWS = new Map(); + return toplevel; + })(); + +} + +export { + get_full_char_code, + get_full_char, + is_identifier_char, + is_basic_identifier_string, + is_identifier_string, + is_surrogate_pair_head, + is_surrogate_pair_tail, + js_error, + JS_Parse_Error, + parse, + PRECEDENCE, + ALL_RESERVED_WORDS, + tokenizer, +}; diff --git a/node_modules/terser/lib/propmangle.js b/node_modules/terser/lib/propmangle.js new file mode 100644 index 0000000..e895705 --- /dev/null +++ b/node_modules/terser/lib/propmangle.js @@ -0,0 +1,432 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; +/* global global, self */ + +import { + defaults, + push_uniq, + has_annotation, + clear_annotation, +} from "./utils/index.js"; +import { base54 } from "./scope.js"; +import { + AST_Binary, + AST_Call, + AST_ClassPrivateProperty, + AST_Conditional, + AST_Dot, + AST_DotHash, + AST_ObjectKeyVal, + AST_ObjectProperty, + AST_PrivateMethod, + AST_PrivateGetter, + AST_PrivateSetter, + AST_PrivateIn, + AST_Sequence, + AST_String, + AST_Sub, + TreeTransformer, + TreeWalker, + _KEY, + _MANGLEPROP, + + walk, +} from "./ast.js"; +import { domprops } from "../tools/domprops.js"; + +function find_builtins(reserved) { + domprops.forEach(add); + + // Compatibility fix for some standard defined globals not defined on every js environment + var new_globals = ["Symbol", "Map", "Promise", "Proxy", "Reflect", "Set", "WeakMap", "WeakSet"]; + var objects = {}; + var global_ref = typeof global === "object" ? global : self; + + new_globals.forEach(function (new_global) { + objects[new_global] = global_ref[new_global] || function() {}; + }); + + [ + "null", + "true", + "false", + "NaN", + "Infinity", + "-Infinity", + "undefined", + ].forEach(add); + [ Object, Array, Function, Number, + String, Boolean, Error, Math, + Date, RegExp, objects.Symbol, ArrayBuffer, + DataView, decodeURI, decodeURIComponent, + encodeURI, encodeURIComponent, eval, EvalError, + Float32Array, Float64Array, Int8Array, Int16Array, + Int32Array, isFinite, isNaN, JSON, objects.Map, parseFloat, + parseInt, objects.Promise, objects.Proxy, RangeError, ReferenceError, + objects.Reflect, objects.Set, SyntaxError, TypeError, Uint8Array, + Uint8ClampedArray, Uint16Array, Uint32Array, URIError, + objects.WeakMap, objects.WeakSet + ].forEach(function(ctor) { + Object.getOwnPropertyNames(ctor).map(add); + if (ctor.prototype) { + Object.getOwnPropertyNames(ctor.prototype).map(add); + } + }); + function add(name) { + reserved.add(name); + } +} + +function reserve_quoted_keys(ast, reserved) { + function add(name) { + push_uniq(reserved, name); + } + + ast.walk(new TreeWalker(function(node) { + if (node instanceof AST_ObjectKeyVal && node.quote) { + add(node.key); + } else if (node instanceof AST_ObjectProperty && node.quote) { + add(node.key.name); + } else if (node instanceof AST_Sub) { + addStrings(node.property, add); + } + })); +} + +function addStrings(node, add) { + node.walk(new TreeWalker(function(node) { + if (node instanceof AST_Sequence) { + addStrings(node.tail_node(), add); + } else if (node instanceof AST_String) { + add(node.value); + } else if (node instanceof AST_Conditional) { + addStrings(node.consequent, add); + addStrings(node.alternative, add); + } + return true; + })); +} + +function mangle_private_properties(ast, options) { + var cprivate = -1; + var private_cache = new Map(); + var nth_identifier = options.nth_identifier || base54; + + ast = ast.transform(new TreeTransformer(function(node) { + if ( + node instanceof AST_ClassPrivateProperty + || node instanceof AST_PrivateMethod + || node instanceof AST_PrivateGetter + || node instanceof AST_PrivateSetter + || node instanceof AST_PrivateIn + ) { + node.key.name = mangle_private(node.key.name); + } else if (node instanceof AST_DotHash) { + node.property = mangle_private(node.property); + } + })); + return ast; + + function mangle_private(name) { + let mangled = private_cache.get(name); + if (!mangled) { + mangled = nth_identifier.get(++cprivate); + private_cache.set(name, mangled); + } + + return mangled; + } +} + +function find_annotated_props(ast) { + var annotated_props = new Set(); + walk(ast, node => { + if ( + node instanceof AST_ClassPrivateProperty + || node instanceof AST_PrivateMethod + || node instanceof AST_PrivateGetter + || node instanceof AST_PrivateSetter + || node instanceof AST_DotHash + ) { + // handled by mangle_private_properties + } else if (node instanceof AST_ObjectKeyVal) { + if (typeof node.key == "string" && has_annotation(node, _MANGLEPROP)) { + annotated_props.add(node.key); + } + } else if (node instanceof AST_ObjectProperty) { + // setter or getter, since KeyVal is handled above + if (has_annotation(node, _MANGLEPROP)) { + annotated_props.add(node.key.name); + } + } else if (node instanceof AST_Dot) { + if (has_annotation(node, _MANGLEPROP)) { + annotated_props.add(node.property); + } + } else if (node instanceof AST_Sub) { + if (node.property instanceof AST_String && has_annotation(node, _MANGLEPROP)) { + annotated_props.add(node.property.value); + } + } + }); + return annotated_props; +} + +function mangle_properties(ast, options, annotated_props = find_annotated_props(ast)) { + options = defaults(options, { + builtins: false, + cache: null, + debug: false, + keep_quoted: false, + nth_identifier: base54, + only_cache: false, + regex: null, + reserved: null, + undeclared: false, + only_annotated: false, + }, true); + + var nth_identifier = options.nth_identifier; + + var reserved_option = options.reserved; + if (!Array.isArray(reserved_option)) reserved_option = [reserved_option]; + var reserved = new Set(reserved_option); + if (!options.builtins) find_builtins(reserved); + + var cname = -1; + + var cache; + if (options.cache) { + cache = options.cache.props; + } else { + cache = new Map(); + } + + var only_annotated = options.only_annotated; + var regex = options.regex && new RegExp(options.regex); + + // note debug is either false (disabled), or a string of the debug suffix to use (enabled). + // note debug may be enabled as an empty string, which is falsey. Also treat passing 'true' + // the same as passing an empty string. + var debug = options.debug !== false; + var debug_name_suffix; + if (debug) { + debug_name_suffix = (options.debug === true ? "" : options.debug); + } + + var names_to_mangle = new Set(); + var unmangleable = new Set(); + // Track each already-mangled name to prevent nth_identifier from generating + // the same name. + cache.forEach((mangled_name) => unmangleable.add(mangled_name)); + + var keep_quoted = !!options.keep_quoted; + + // step 1: find candidates to mangle + ast.walk(new TreeWalker(function(node) { + if ( + node instanceof AST_ClassPrivateProperty + || node instanceof AST_PrivateMethod + || node instanceof AST_PrivateGetter + || node instanceof AST_PrivateSetter + || node instanceof AST_DotHash + ) { + // handled by mangle_private_properties + } else if (node instanceof AST_ObjectKeyVal) { + if (typeof node.key == "string" && (!keep_quoted || !node.quote)) { + add(node.key); + } + } else if (node instanceof AST_ObjectProperty) { + // setter or getter, since KeyVal is handled above + if (!keep_quoted || !node.quote) { + add(node.key.name); + } + } else if (node instanceof AST_Dot) { + var declared = !!options.undeclared; + if (!declared) { + var root = node; + while (root.expression) { + root = root.expression; + } + declared = !(root.thedef && root.thedef.undeclared); + } + if (declared && + (!keep_quoted || !node.quote)) { + add(node.property); + } + } else if (node instanceof AST_Sub) { + if (!keep_quoted) { + addStrings(node.property, add); + } + } else if (node instanceof AST_Call + && node.expression.print_to_string() == "Object.defineProperty") { + addStrings(node.args[1], add); + } else if (node instanceof AST_Binary && node.operator === "in") { + addStrings(node.left, add); + } else if (node instanceof AST_String && has_annotation(node, _KEY)) { + add(node.value); + } + })); + + // step 2: transform the tree, renaming properties + return ast.transform(new TreeTransformer(function(node) { + if ( + node instanceof AST_ClassPrivateProperty + || node instanceof AST_PrivateMethod + || node instanceof AST_PrivateGetter + || node instanceof AST_PrivateSetter + || node instanceof AST_DotHash + ) { + // handled by mangle_private_properties + } else if (node instanceof AST_ObjectKeyVal) { + if (typeof node.key == "string" && (!keep_quoted || !node.quote)) { + node.key = mangle(node.key); + } + } else if (node instanceof AST_ObjectProperty) { + // setter, getter, method or class field + if (!keep_quoted || !node.quote) { + node.key.name = mangle(node.key.name); + } + } else if (node instanceof AST_Dot) { + if (!keep_quoted || !node.quote) { + node.property = mangle(node.property); + } + } else if (!keep_quoted && node instanceof AST_Sub) { + node.property = mangleStrings(node.property); + } else if (node instanceof AST_Call + && node.expression.print_to_string() == "Object.defineProperty") { + node.args[1] = mangleStrings(node.args[1]); + } else if (node instanceof AST_Binary && node.operator === "in") { + node.left = mangleStrings(node.left); + } else if (node instanceof AST_String && has_annotation(node, _KEY)) { + // Clear _KEY annotation to prevent double mangling + clear_annotation(node, _KEY); + node.value = mangle(node.value); + } + })); + + // only function declarations after this line + + function can_mangle(name) { + if (unmangleable.has(name)) return false; + if (reserved.has(name)) return false; + if (options.only_cache) { + return cache.has(name); + } + if (/^-?[0-9]+(\.[0-9]+)?(e[+-][0-9]+)?$/.test(name)) return false; + return true; + } + + function should_mangle(name) { + if (only_annotated && !annotated_props.has(name)) return false; + if (regex && !regex.test(name)) { + return annotated_props.has(name); + } + if (reserved.has(name)) return false; + return cache.has(name) + || names_to_mangle.has(name); + } + + function add(name) { + if (can_mangle(name)) { + names_to_mangle.add(name); + } + + if (!should_mangle(name)) { + unmangleable.add(name); + } + } + + function mangle(name) { + if (!should_mangle(name)) { + return name; + } + + var mangled = cache.get(name); + if (!mangled) { + if (debug) { + // debug mode: use a prefix and suffix to preserve readability, e.g. o.foo -> o._$foo$NNN_. + var debug_mangled = "_$" + name + "$" + debug_name_suffix + "_"; + + if (can_mangle(debug_mangled)) { + mangled = debug_mangled; + } + } + + // either debug mode is off, or it is on and we could not use the mangled name + if (!mangled) { + do { + mangled = nth_identifier.get(++cname); + } while (!can_mangle(mangled)); + } + + cache.set(name, mangled); + } + return mangled; + } + + function mangleStrings(node) { + return node.transform(new TreeTransformer(function(node) { + if (node instanceof AST_Sequence) { + var last = node.expressions.length - 1; + node.expressions[last] = mangleStrings(node.expressions[last]); + } else if (node instanceof AST_String) { + // Clear _KEY annotation to prevent double mangling + clear_annotation(node, _KEY); + node.value = mangle(node.value); + } else if (node instanceof AST_Conditional) { + node.consequent = mangleStrings(node.consequent); + node.alternative = mangleStrings(node.alternative); + } + return node; + })); + } +} + +export { + reserve_quoted_keys, + mangle_properties, + mangle_private_properties, + find_annotated_props, +}; diff --git a/node_modules/terser/lib/scope.js b/node_modules/terser/lib/scope.js new file mode 100644 index 0000000..f8a22a5 --- /dev/null +++ b/node_modules/terser/lib/scope.js @@ -0,0 +1,1066 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +import { + defaults, + keep_name, + mergeSort, + push_uniq, + make_node, + return_false, + return_this, + return_true, + string_template, +} from "./utils/index.js"; +import { + AST_Arrow, + AST_Block, + AST_Call, + AST_Class, + AST_Conditional, + AST_DefClass, + AST_Defun, + AST_Destructuring, + AST_Dot, + AST_DotHash, + AST_Export, + AST_For, + AST_ForIn, + AST_ForOf, + AST_Function, + AST_Import, + AST_IterationStatement, + AST_Label, + AST_LabeledStatement, + AST_LabelRef, + AST_Lambda, + AST_LoopControl, + AST_NameMapping, + AST_Node, + AST_Scope, + AST_Sequence, + AST_String, + AST_Sub, + AST_Switch, + AST_SwitchBranch, + AST_Symbol, + AST_SymbolBlockDeclaration, + AST_SymbolCatch, + AST_SymbolClass, + AST_SymbolConst, + AST_SymbolDefClass, + AST_SymbolDefun, + AST_SymbolExport, + AST_SymbolFunarg, + AST_SymbolImport, + AST_SymbolLambda, + AST_SymbolLet, + AST_SymbolMethod, + AST_SymbolRef, + AST_SymbolVar, + AST_Toplevel, + AST_VarDef, + AST_With, + TreeWalker, + walk, + walk_abort +} from "./ast.js"; +import { + ALL_RESERVED_WORDS, + js_error, +} from "./parse.js"; + +const MASK_EXPORT_DONT_MANGLE = 1 << 0; +const MASK_EXPORT_WANT_MANGLE = 1 << 1; + +let function_defs = null; +let unmangleable_names = null; +/** + * When defined, there is a function declaration somewhere that's inside of a block. + * See https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html#sec-block-level-function-declarations-web-legacy-compatibility-semantics +*/ +let scopes_with_block_defuns = null; + +class SymbolDef { + constructor(scope, orig, init) { + this.name = orig.name; + this.orig = [ orig ]; + this.init = init; + this.eliminated = 0; + this.assignments = 0; + this.scope = scope; + this.replaced = 0; + this.global = false; + this.export = 0; + this.mangled_name = null; + this.undeclared = false; + this.id = SymbolDef.next_id++; + this.chained = false; + this.direct_access = false; + this.escaped = 0; + this.recursive_refs = 0; + this.references = []; + this.should_replace = undefined; + this.single_use = false; + this.fixed = false; + Object.seal(this); + } + fixed_value() { + if (!this.fixed || this.fixed instanceof AST_Node) return this.fixed; + return this.fixed(); + } + unmangleable(options) { + if (!options) options = {}; + + if ( + function_defs && + function_defs.has(this.id) && + keep_name(options.keep_fnames, this.orig[0].name) + ) return true; + + return this.global && !options.toplevel + || (this.export & MASK_EXPORT_DONT_MANGLE) + || this.undeclared + || !options.eval && this.scope.pinned() + || (this.orig[0] instanceof AST_SymbolLambda + || this.orig[0] instanceof AST_SymbolDefun) && keep_name(options.keep_fnames, this.orig[0].name) + || this.orig[0] instanceof AST_SymbolMethod + || (this.orig[0] instanceof AST_SymbolClass + || this.orig[0] instanceof AST_SymbolDefClass) && keep_name(options.keep_classnames, this.orig[0].name); + } + mangle(options) { + const cache = options.cache && options.cache.props; + if (this.global && cache && cache.has(this.name)) { + this.mangled_name = cache.get(this.name); + } else if (!this.mangled_name && !this.unmangleable(options)) { + var s = this.scope; + var sym = this.orig[0]; + if (options.ie8 && sym instanceof AST_SymbolLambda) + s = s.parent_scope; + const redefinition = redefined_catch_def(this); + this.mangled_name = redefinition + ? redefinition.mangled_name || redefinition.name + : s.next_mangled(options, this); + if (this.global && cache) { + cache.set(this.name, this.mangled_name); + } + } + } +} + +SymbolDef.next_id = 1; + +function redefined_catch_def(def) { + if (def.orig[0] instanceof AST_SymbolCatch + && def.scope.is_block_scope() + ) { + return def.scope.get_defun_scope().variables.get(def.name); + } +} + +AST_Scope.DEFMETHOD("figure_out_scope", function(options, { parent_scope = null, toplevel = this } = {}) { + options = defaults(options, { + cache: null, + ie8: false, + safari10: false, + module: false, + }); + + if (!(toplevel instanceof AST_Toplevel)) { + throw new Error("Invalid toplevel scope"); + } + + // pass 1: setup scope chaining and handle definitions + var scope = this.parent_scope = parent_scope; + var labels = new Map(); + var defun = null; + var in_destructuring = null; + var for_scopes = []; + var tw = new TreeWalker((node, descend) => { + if (node.is_block_scope()) { + const save_scope = scope; + node.block_scope = scope = new AST_Scope(node); + scope._block_scope = true; + scope.init_scope_vars(save_scope); + scope.uses_with = save_scope.uses_with; + scope.uses_eval = save_scope.uses_eval; + + if (options.safari10) { + if (node instanceof AST_For || node instanceof AST_ForIn || node instanceof AST_ForOf) { + for_scopes.push(scope); + } + } + + if (node instanceof AST_Switch) { + // XXX: HACK! Ensure the switch expression gets the correct scope (the parent scope) and the body gets the contained scope + // AST_Switch has a scope within the body, but it itself "is a block scope" + // This means the switched expression has to belong to the outer scope + // while the body inside belongs to the switch itself. + // This is pretty nasty and warrants an AST change + const the_block_scope = scope; + scope = save_scope; + node.expression.walk(tw); + scope = the_block_scope; + for (let i = 0; i < node.body.length; i++) { + node.body[i].walk(tw); + } + } else { + descend(); + } + scope = save_scope; + return true; + } + if (node instanceof AST_Destructuring) { + const save_destructuring = in_destructuring; + in_destructuring = node; + descend(); + in_destructuring = save_destructuring; + return true; + } + if (node instanceof AST_Scope) { + node.init_scope_vars(scope); + var save_scope = scope; + var save_defun = defun; + var save_labels = labels; + defun = scope = node; + labels = new Map(); + descend(); + scope = save_scope; + defun = save_defun; + labels = save_labels; + return true; // don't descend again in TreeWalker + } + if (node instanceof AST_LabeledStatement) { + var l = node.label; + if (labels.has(l.name)) { + throw new Error(string_template("Label {name} defined twice", l)); + } + labels.set(l.name, l); + descend(); + labels.delete(l.name); + return true; // no descend again + } + if (node instanceof AST_With) { + for (var s = scope; s; s = s.parent_scope) + s.uses_with = true; + return; + } + if (node instanceof AST_Symbol) { + node.scope = scope; + } + if (node instanceof AST_Label) { + node.thedef = node; + node.references = []; + } + if (node instanceof AST_SymbolLambda) { + defun.def_function(node, node.name == "arguments" ? undefined : defun); + } else if (node instanceof AST_SymbolDefun) { + // Careful here, the scope where this should be defined is + // the parent scope. The reason is that we enter a new + // scope when we encounter the AST_Defun node (which is + // instanceof AST_Scope) but we get to the symbol a bit + // later. + const closest_scope = defun.parent_scope; + + // In strict mode, function definitions are block-scoped + node.scope = tw.directives["use strict"] + ? closest_scope + : closest_scope.get_defun_scope(); + + mark_export(node.scope.def_function(node, defun), 1); + } else if (node instanceof AST_SymbolClass) { + mark_export(defun.def_variable(node, defun), 1); + } else if (node instanceof AST_SymbolImport) { + scope.def_variable(node); + } else if (node instanceof AST_SymbolDefClass) { + // This deals with the name of the class being available + // inside the class. + mark_export((node.scope = defun.parent_scope).def_function(node, defun), 1); + } else if ( + node instanceof AST_SymbolVar + || node instanceof AST_SymbolLet + || node instanceof AST_SymbolConst + || node instanceof AST_SymbolCatch + ) { + var def; + if (node instanceof AST_SymbolBlockDeclaration) { + def = scope.def_variable(node, null); + } else { + def = defun.def_variable(node, node.TYPE == "SymbolVar" ? null : undefined); + } + if (!def.orig.every((sym) => { + if (sym === node) return true; + if (node instanceof AST_SymbolBlockDeclaration) { + return sym instanceof AST_SymbolLambda; + } + return !(sym instanceof AST_SymbolLet || sym instanceof AST_SymbolConst); + })) { + js_error( + `"${node.name}" is redeclared`, + node.start.file, + node.start.line, + node.start.col, + node.start.pos + ); + } + if (!(node instanceof AST_SymbolFunarg)) mark_export(def, 2); + if (defun !== scope) { + node.mark_enclosed(); + var def = scope.find_variable(node); + if (node.thedef !== def) { + node.thedef = def; + node.reference(); + } + } + } else if (node instanceof AST_LabelRef) { + var sym = labels.get(node.name); + if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", { + name: node.name, + line: node.start.line, + col: node.start.col + })); + node.thedef = sym; + } + if (!(scope instanceof AST_Toplevel) && (node instanceof AST_Export || node instanceof AST_Import)) { + js_error( + `"${node.TYPE}" statement may only appear at the top level`, + node.start.file, + node.start.line, + node.start.col, + node.start.pos + ); + } + }); + + if (options.module) { + tw.directives["use strict"] = true; + } + + this.walk(tw); + + function mark_export(def, level) { + if (in_destructuring) { + var i = 0; + do { + level++; + } while (tw.parent(i++) !== in_destructuring); + } + var node = tw.parent(level); + if (def.export = node instanceof AST_Export ? MASK_EXPORT_DONT_MANGLE : 0) { + var exported = node.exported_definition; + if ((exported instanceof AST_Defun || exported instanceof AST_DefClass) && node.is_default) { + def.export = MASK_EXPORT_WANT_MANGLE; + } + } + } + + // pass 2: find back references and eval + const is_toplevel = this instanceof AST_Toplevel; + if (is_toplevel) { + this.globals = new Map(); + } + + var tw = new TreeWalker(node => { + if (node instanceof AST_LoopControl && node.label) { + node.label.thedef.references.push(node); + return true; + } + if (node instanceof AST_SymbolRef) { + var name = node.name; + if (name == "eval" && tw.parent() instanceof AST_Call) { + for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) { + s.uses_eval = true; + } + } + var sym; + if (tw.parent() instanceof AST_NameMapping && tw.parent(1).module_name + || !(sym = node.scope.find_variable(name))) { + + sym = toplevel.def_global(node); + if (node instanceof AST_SymbolExport) sym.export = MASK_EXPORT_DONT_MANGLE; + } else if (sym.scope instanceof AST_Lambda && name == "arguments") { + sym.scope.get_defun_scope().uses_arguments = true; + } + node.thedef = sym; + node.reference(); + if (node.scope.is_block_scope() + && !(sym.orig[0] instanceof AST_SymbolBlockDeclaration)) { + node.scope = node.scope.get_defun_scope(); + } + return true; + } + // ensure mangling works if catch reuses a scope variable + var def; + if (node instanceof AST_SymbolCatch && (def = redefined_catch_def(node.definition()))) { + var s = node.scope; + while (s) { + push_uniq(s.enclosed, def); + if (s === def.scope) break; + s = s.parent_scope; + } + } + }); + this.walk(tw); + + // pass 3: work around IE8 and Safari catch scope bugs + if (options.ie8 || options.safari10) { + walk(this, node => { + if (node instanceof AST_SymbolCatch) { + var name = node.name; + var refs = node.thedef.references; + var scope = node.scope.get_defun_scope(); + var def = scope.find_variable(name) + || toplevel.globals.get(name) + || scope.def_variable(node); + refs.forEach(function(ref) { + ref.thedef = def; + ref.reference(); + }); + node.thedef = def; + node.reference(); + return true; + } + }); + } + + // pass 4: add symbol definitions to loop scopes + // Safari/Webkit bug workaround - loop init let variable shadowing argument. + // https://github.com/mishoo/UglifyJS2/issues/1753 + // https://bugs.webkit.org/show_bug.cgi?id=171041 + if (options.safari10) { + for (const scope of for_scopes) { + scope.parent_scope.variables.forEach(function(def) { + push_uniq(scope.enclosed, def); + }); + } + } +}); + +AST_Toplevel.DEFMETHOD("def_global", function(node) { + var globals = this.globals, name = node.name; + if (globals.has(name)) { + return globals.get(name); + } else { + var g = new SymbolDef(this, node); + g.undeclared = true; + g.global = true; + globals.set(name, g); + return g; + } +}); + +AST_Scope.DEFMETHOD("init_scope_vars", function(parent_scope) { + this.variables = new Map(); // map name to AST_SymbolVar (variables defined in this scope; includes functions) + this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement + this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval` + this.parent_scope = parent_scope; // the parent scope + this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes + this.cname = -1; // the current index for mangling functions/variables +}); + +AST_Scope.DEFMETHOD("conflicting_def", function (name) { + return ( + this.enclosed.find(def => def.name === name) + || this.variables.has(name) + || (this.parent_scope && this.parent_scope.conflicting_def(name)) + ); +}); + +AST_Scope.DEFMETHOD("conflicting_def_shallow", function (name) { + return ( + this.enclosed.find(def => def.name === name) + || this.variables.has(name) + ); +}); + +AST_Scope.DEFMETHOD("add_child_scope", function (scope) { + // `scope` is going to be moved into `this` right now. + // Update the required scopes' information + + if (scope.parent_scope === this) return; + + scope.parent_scope = this; + + // Propagate to this.uses_arguments from arrow functions + if ((scope instanceof AST_Arrow) && !this.uses_arguments) { + this.uses_arguments = walk(scope, node => { + if ( + node instanceof AST_SymbolRef + && node.scope instanceof AST_Lambda + && node.name === "arguments" + ) { + return walk_abort; + } + + if (node instanceof AST_Lambda && !(node instanceof AST_Arrow)) { + return true; + } + }); + } + + this.uses_with = this.uses_with || scope.uses_with; + this.uses_eval = this.uses_eval || scope.uses_eval; + + const scope_ancestry = (() => { + const ancestry = []; + let cur = this; + do { + ancestry.push(cur); + } while ((cur = cur.parent_scope)); + ancestry.reverse(); + return ancestry; + })(); + + const new_scope_enclosed_set = new Set(scope.enclosed); + const to_enclose = []; + for (const scope_topdown of scope_ancestry) { + to_enclose.forEach(e => push_uniq(scope_topdown.enclosed, e)); + for (const def of scope_topdown.variables.values()) { + if (new_scope_enclosed_set.has(def)) { + push_uniq(to_enclose, def); + push_uniq(scope_topdown.enclosed, def); + } + } + } +}); + +function find_scopes_visible_from(scopes) { + const found_scopes = new Set(); + + for (const scope of new Set(scopes)) { + (function bubble_up(scope) { + if (scope == null || found_scopes.has(scope)) return; + + found_scopes.add(scope); + + bubble_up(scope.parent_scope); + })(scope); + } + + return [...found_scopes]; +} + +// Creates a symbol during compression +AST_Scope.DEFMETHOD("create_symbol", function(SymClass, { + source, + tentative_name, + scope, + conflict_scopes = [scope], + init = null +} = {}) { + let symbol_name; + + conflict_scopes = find_scopes_visible_from(conflict_scopes); + + if (tentative_name) { + // Implement hygiene (no new names are conflicting with existing names) + tentative_name = + symbol_name = + tentative_name.replace(/(?:^[^a-z_$]|[^a-z0-9_$])/ig, "_"); + + let i = 0; + while (conflict_scopes.find(s => s.conflicting_def_shallow(symbol_name))) { + symbol_name = tentative_name + "$" + i++; + } + } + + if (!symbol_name) { + throw new Error("No symbol name could be generated in create_symbol()"); + } + + const symbol = make_node(SymClass, source, { + name: symbol_name, + scope + }); + + this.def_variable(symbol, init || null); + + symbol.mark_enclosed(); + + return symbol; +}); + + +AST_Node.DEFMETHOD("is_block_scope", return_false); +AST_Class.DEFMETHOD("is_block_scope", return_false); +AST_Lambda.DEFMETHOD("is_block_scope", return_false); +AST_Toplevel.DEFMETHOD("is_block_scope", return_false); +AST_SwitchBranch.DEFMETHOD("is_block_scope", return_false); +AST_Block.DEFMETHOD("is_block_scope", return_true); +AST_Scope.DEFMETHOD("is_block_scope", function () { + return this._block_scope || false; +}); +AST_IterationStatement.DEFMETHOD("is_block_scope", return_true); + +AST_Lambda.DEFMETHOD("init_scope_vars", function() { + AST_Scope.prototype.init_scope_vars.apply(this, arguments); + this.uses_arguments = false; + this.def_variable(new AST_SymbolFunarg({ + name: "arguments", + start: this.start, + end: this.end + })); +}); + +AST_Arrow.DEFMETHOD("init_scope_vars", function() { + AST_Scope.prototype.init_scope_vars.apply(this, arguments); + this.uses_arguments = false; +}); + +AST_Symbol.DEFMETHOD("mark_enclosed", function() { + var def = this.definition(); + var s = this.scope; + while (s) { + push_uniq(s.enclosed, def); + if (s === def.scope) break; + s = s.parent_scope; + } +}); + +AST_Symbol.DEFMETHOD("reference", function() { + this.definition().references.push(this); + this.mark_enclosed(); +}); + +AST_Scope.DEFMETHOD("find_variable", function(name) { + if (name instanceof AST_Symbol) name = name.name; + return this.variables.get(name) + || (this.parent_scope && this.parent_scope.find_variable(name)); +}); + +AST_Scope.DEFMETHOD("def_function", function(symbol, init) { + var def = this.def_variable(symbol, init); + if (!def.init || def.init instanceof AST_Defun) def.init = init; + return def; +}); + +AST_Scope.DEFMETHOD("def_variable", function(symbol, init) { + var def = this.variables.get(symbol.name); + if (def) { + def.orig.push(symbol); + if (def.init && (def.scope !== symbol.scope || def.init instanceof AST_Function)) { + def.init = init; + } + } else { + def = new SymbolDef(this, symbol, init); + this.variables.set(symbol.name, def); + def.global = !this.parent_scope; + } + return symbol.thedef = def; +}); + +function next_mangled(scope, options) { + let defun_scope; + if ( + scopes_with_block_defuns + && (defun_scope = scope.get_defun_scope()) + && scopes_with_block_defuns.has(defun_scope) + ) { + scope = defun_scope; + } + + var ext = scope.enclosed; + var nth_identifier = options.nth_identifier; + out: while (true) { + var m = nth_identifier.get(++scope.cname); + if (ALL_RESERVED_WORDS.has(m)) continue; // skip over "do" + + // https://github.com/mishoo/UglifyJS2/issues/242 -- do not + // shadow a name reserved from mangling. + if (options.reserved.has(m)) continue; + + // Functions with short names might collide with base54 output + // and therefore cause collisions when keep_fnames is true. + if (unmangleable_names && unmangleable_names.has(m)) continue out; + + // we must ensure that the mangled name does not shadow a name + // from some parent scope that is referenced in this or in + // inner scopes. + for (let i = ext.length; --i >= 0;) { + const def = ext[i]; + const name = def.mangled_name || (def.unmangleable(options) && def.name); + if (m == name) continue out; + } + return m; + } +} + +AST_Scope.DEFMETHOD("next_mangled", function(options) { + return next_mangled(this, options); +}); + +AST_Toplevel.DEFMETHOD("next_mangled", function(options) { + let name; + const mangled_names = this.mangled_names; + do { + name = next_mangled(this, options); + } while (mangled_names.has(name)); + return name; +}); + +AST_Function.DEFMETHOD("next_mangled", function(options, def) { + // #179, #326 + // in Safari strict mode, something like (function x(x){...}) is a syntax error; + // a function expression's argument cannot shadow the function expression's name + + var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition(); + + // the function's mangled_name is null when keep_fnames is true + var tricky_name = tricky_def ? tricky_def.mangled_name || tricky_def.name : null; + + while (true) { + var name = next_mangled(this, options); + if (!tricky_name || tricky_name != name) + return name; + } +}); + +AST_Symbol.DEFMETHOD("unmangleable", function(options) { + var def = this.definition(); + return !def || def.unmangleable(options); +}); + +// labels are always mangleable +AST_Label.DEFMETHOD("unmangleable", return_false); + +AST_Symbol.DEFMETHOD("unreferenced", function() { + return !this.definition().references.length && !this.scope.pinned(); +}); + +AST_Symbol.DEFMETHOD("definition", function() { + return this.thedef; +}); + +AST_Symbol.DEFMETHOD("global", function() { + return this.thedef.global; +}); + +/** + * Format the mangler options (if any) into their appropriate types + */ +export function format_mangler_options(options) { + options = defaults(options, { + eval : false, + nth_identifier : base54, + ie8 : false, + keep_classnames: false, + keep_fnames : false, + module : false, + reserved : [], + toplevel : false, + }); + if (options.module) options.toplevel = true; + if (!Array.isArray(options.reserved) + && !(options.reserved instanceof Set) + ) { + options.reserved = []; + } + options.reserved = new Set(options.reserved); + // Never mangle arguments + options.reserved.add("arguments"); + return options; +} + +AST_Toplevel.DEFMETHOD("mangle_names", function(options) { + options = format_mangler_options(options); + var nth_identifier = options.nth_identifier; + + // We only need to mangle declaration nodes. Special logic wired + // into the code generator will display the mangled name if it's + // present (and for AST_SymbolRef-s it'll use the mangled name of + // the AST_SymbolDeclaration that it points to). + var lname = -1; + var to_mangle = []; + + if (options.keep_fnames) { + function_defs = new Set(); + } + + const mangled_names = this.mangled_names = new Set(); + unmangleable_names = new Set(); + + if (options.cache) { + this.globals.forEach(collect); + if (options.cache.props) { + options.cache.props.forEach(function(mangled_name) { + mangled_names.add(mangled_name); + }); + } + } + + var tw = new TreeWalker(function(node, descend) { + if (node instanceof AST_LabeledStatement) { + // lname is incremented when we get to the AST_Label + var save_nesting = lname; + descend(); + lname = save_nesting; + return true; // don't descend again in TreeWalker + } + if ( + node instanceof AST_Defun + && !(tw.parent() instanceof AST_Scope) + ) { + scopes_with_block_defuns = scopes_with_block_defuns || new Set(); + scopes_with_block_defuns.add(node.parent_scope.get_defun_scope()); + } + if (node instanceof AST_Scope) { + node.variables.forEach(collect); + return; + } + if (node.is_block_scope()) { + node.block_scope.variables.forEach(collect); + return; + } + if ( + function_defs + && node instanceof AST_VarDef + && node.value instanceof AST_Lambda + && !node.value.name + && keep_name(options.keep_fnames, node.name.name) + ) { + function_defs.add(node.name.definition().id); + return; + } + if (node instanceof AST_Label) { + let name; + do { + name = nth_identifier.get(++lname); + } while (ALL_RESERVED_WORDS.has(name)); + node.mangled_name = name; + return true; + } + if (!(options.ie8 || options.safari10) && node instanceof AST_SymbolCatch) { + to_mangle.push(node.definition()); + return; + } + }); + + this.walk(tw); + + if (options.keep_fnames || options.keep_classnames) { + // Collect a set of short names which are unmangleable, + // for use in avoiding collisions in next_mangled. + to_mangle.forEach(def => { + if (def.name.length < 6 && def.unmangleable(options)) { + unmangleable_names.add(def.name); + } + }); + } + + to_mangle.forEach(def => { def.mangle(options); }); + + function_defs = null; + unmangleable_names = null; + scopes_with_block_defuns = null; + + function collect(symbol) { + if (symbol.export & MASK_EXPORT_DONT_MANGLE) { + unmangleable_names.add(symbol.name); + } else if (!options.reserved.has(symbol.name)) { + to_mangle.push(symbol); + } + } +}); + +AST_Toplevel.DEFMETHOD("find_colliding_names", function(options) { + const cache = options.cache && options.cache.props; + const avoid = new Set(); + options.reserved.forEach(to_avoid); + this.globals.forEach(add_def); + this.walk(new TreeWalker(function(node) { + if (node instanceof AST_Scope) node.variables.forEach(add_def); + if (node instanceof AST_SymbolCatch) add_def(node.definition()); + })); + return avoid; + + function to_avoid(name) { + avoid.add(name); + } + + function add_def(def) { + var name = def.name; + if (def.global && cache && cache.has(name)) name = cache.get(name); + else if (!def.unmangleable(options)) return; + to_avoid(name); + } +}); + +AST_Toplevel.DEFMETHOD("expand_names", function(options) { + options = format_mangler_options(options); + var nth_identifier = options.nth_identifier; + if (nth_identifier.reset && nth_identifier.sort) { + nth_identifier.reset(); + nth_identifier.sort(); + } + var avoid = this.find_colliding_names(options); + var cname = 0; + this.globals.forEach(rename); + this.walk(new TreeWalker(function(node) { + if (node instanceof AST_Scope) node.variables.forEach(rename); + if (node instanceof AST_SymbolCatch) rename(node.definition()); + })); + + function next_name() { + var name; + do { + name = nth_identifier.get(cname++); + } while (avoid.has(name) || ALL_RESERVED_WORDS.has(name)); + return name; + } + + function rename(def) { + if (def.global && options.cache) return; + if (def.unmangleable(options)) return; + if (options.reserved.has(def.name)) return; + const redefinition = redefined_catch_def(def); + const name = def.name = redefinition ? redefinition.name : next_name(); + def.orig.forEach(function(sym) { + sym.name = name; + }); + def.references.forEach(function(sym) { + sym.name = name; + }); + } +}); + +AST_Node.DEFMETHOD("tail_node", return_this); +AST_Sequence.DEFMETHOD("tail_node", function() { + return this.expressions[this.expressions.length - 1]; +}); + +AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options) { + options = format_mangler_options(options); + var nth_identifier = options.nth_identifier; + if (!nth_identifier.reset || !nth_identifier.consider || !nth_identifier.sort) { + // If the identifier mangler is invariant, skip computing character frequency. + return; + } + nth_identifier.reset(); + + try { + AST_Node.prototype.print = function(stream, force_parens) { + this._print(stream, force_parens); + if (this instanceof AST_Symbol && !this.unmangleable(options)) { + nth_identifier.consider(this.name, -1); + } else if (options.properties) { + if (this instanceof AST_DotHash) { + nth_identifier.consider("#" + this.property, -1); + } else if (this instanceof AST_Dot) { + nth_identifier.consider(this.property, -1); + } else if (this instanceof AST_Sub) { + skip_string(this.property); + } + } + }; + nth_identifier.consider(this.print_to_string(), 1); + } finally { + AST_Node.prototype.print = AST_Node.prototype._print; + } + nth_identifier.sort(); + + function skip_string(node) { + if (node instanceof AST_String) { + nth_identifier.consider(node.value, -1); + } else if (node instanceof AST_Conditional) { + skip_string(node.consequent); + skip_string(node.alternative); + } else if (node instanceof AST_Sequence) { + skip_string(node.tail_node()); + } + } +}); + +const base54 = (() => { + const leading = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_".split(""); + const digits = "0123456789".split(""); + let chars; + let frequency; + function reset() { + frequency = new Map(); + leading.forEach(function(ch) { + frequency.set(ch, 0); + }); + digits.forEach(function(ch) { + frequency.set(ch, 0); + }); + } + function consider(str, delta) { + for (var i = str.length; --i >= 0;) { + frequency.set(str[i], frequency.get(str[i]) + delta); + } + } + function compare(a, b) { + return frequency.get(b) - frequency.get(a); + } + function sort() { + chars = mergeSort(leading, compare).concat(mergeSort(digits, compare)); + } + // Ensure this is in a usable initial state. + reset(); + sort(); + function base54(num) { + var ret = "", base = 54; + num++; + do { + num--; + ret += chars[num % base]; + num = Math.floor(num / base); + base = 64; + } while (num > 0); + return ret; + } + + return { + get: base54, + consider, + reset, + sort + }; +})(); + +export { + base54, + SymbolDef, +}; diff --git a/node_modules/terser/lib/size.js b/node_modules/terser/lib/size.js new file mode 100644 index 0000000..3a178c5 --- /dev/null +++ b/node_modules/terser/lib/size.js @@ -0,0 +1,495 @@ +import { + AST_Accessor, + AST_Array, + AST_Arrow, + AST_Await, + AST_BigInt, + AST_Binary, + AST_Block, + AST_Break, + AST_Call, + AST_Case, + AST_Class, + AST_ClassStaticBlock, + AST_ClassPrivateProperty, + AST_ClassProperty, + AST_ConciseMethod, + AST_Conditional, + AST_Const, + AST_Continue, + AST_Debugger, + AST_Default, + AST_Defun, + AST_Destructuring, + AST_Directive, + AST_Do, + AST_Dot, + AST_DotHash, + AST_EmptyStatement, + AST_Expansion, + AST_Export, + AST_False, + AST_For, + AST_ForIn, + AST_Function, + AST_Hole, + AST_If, + AST_Import, + AST_ImportMeta, + AST_Infinity, + AST_LabeledStatement, + AST_Let, + AST_NameMapping, + AST_NaN, + AST_New, + AST_NewTarget, + AST_Node, + AST_Null, + AST_Number, + AST_Object, + AST_ObjectKeyVal, + AST_ObjectGetter, + AST_ObjectSetter, + AST_PrivateGetter, + AST_PrivateMethod, + AST_PrivateSetter, + AST_PrivateIn, + AST_RegExp, + AST_Return, + AST_Sequence, + AST_String, + AST_Sub, + AST_Super, + AST_Switch, + AST_Symbol, + AST_SymbolClassProperty, + AST_SymbolExportForeign, + AST_SymbolImportForeign, + AST_SymbolRef, + AST_SymbolDeclaration, + AST_TemplateSegment, + AST_TemplateString, + AST_This, + AST_Throw, + AST_Toplevel, + AST_True, + AST_Try, + AST_Catch, + AST_Finally, + AST_Unary, + AST_Undefined, + AST_Var, + AST_VarDef, + AST_While, + AST_With, + AST_Yield, + walk_parent +} from "./ast.js"; +import { first_in_statement } from "./utils/first_in_statement.js"; + +let mangle_options = undefined; +AST_Node.prototype.size = function (compressor, stack) { + mangle_options = compressor && compressor._mangle_options; + + let size = 0; + walk_parent(this, (node, info) => { + size += node._size(info); + + // Braceless arrow functions have fake "return" statements + if (node instanceof AST_Arrow && node.is_braceless()) { + size += node.body[0].value._size(info); + return true; + } + }, stack || (compressor && compressor.stack)); + + // just to save a bit of memory + mangle_options = undefined; + + return size; +}; + +AST_Node.prototype._size = () => 0; + +AST_Debugger.prototype._size = () => 8; + +AST_Directive.prototype._size = function () { + // TODO string encoding stuff + return 2 + this.value.length; +}; + +/** Count commas/semicolons necessary to show a list of expressions/statements */ +const list_overhead = (array) => array.length && array.length - 1; + +AST_Block.prototype._size = function () { + return 2 + list_overhead(this.body); +}; + +AST_Toplevel.prototype._size = function() { + return list_overhead(this.body); +}; + +AST_EmptyStatement.prototype._size = () => 1; + +AST_LabeledStatement.prototype._size = () => 2; // x: + +AST_Do.prototype._size = () => 9; + +AST_While.prototype._size = () => 7; + +AST_For.prototype._size = () => 8; + +AST_ForIn.prototype._size = () => 8; +// AST_ForOf inherits ^ + +AST_With.prototype._size = () => 6; + +AST_Expansion.prototype._size = () => 3; + +const lambda_modifiers = func => + (func.is_generator ? 1 : 0) + (func.async ? 6 : 0); + +AST_Accessor.prototype._size = function () { + return lambda_modifiers(this) + 4 + list_overhead(this.argnames) + list_overhead(this.body); +}; + +AST_Function.prototype._size = function (info) { + const first = !!first_in_statement(info); + return (first * 2) + lambda_modifiers(this) + 12 + list_overhead(this.argnames) + list_overhead(this.body); +}; + +AST_Defun.prototype._size = function () { + return lambda_modifiers(this) + 13 + list_overhead(this.argnames) + list_overhead(this.body); +}; + +AST_Arrow.prototype._size = function () { + let args_and_arrow = 2 + list_overhead(this.argnames); + + if ( + !( + this.argnames.length === 1 + && this.argnames[0] instanceof AST_Symbol + ) + ) { + args_and_arrow += 2; // parens around the args + } + + const body_overhead = this.is_braceless() ? 0 : list_overhead(this.body) + 2; + + return lambda_modifiers(this) + args_and_arrow + body_overhead; +}; + +AST_Destructuring.prototype._size = () => 2; + +AST_TemplateString.prototype._size = function () { + return 2 + (Math.floor(this.segments.length / 2) * 3); /* "${}" */ +}; + +AST_TemplateSegment.prototype._size = function () { + return this.value.length; +}; + +AST_Return.prototype._size = function () { + return this.value ? 7 : 6; +}; + +AST_Throw.prototype._size = () => 6; + +AST_Break.prototype._size = function () { + return this.label ? 6 : 5; +}; + +AST_Continue.prototype._size = function () { + return this.label ? 9 : 8; +}; + +AST_If.prototype._size = () => 4; + +AST_Switch.prototype._size = function () { + return 8 + list_overhead(this.body); +}; + +AST_Case.prototype._size = function () { + return 5 + list_overhead(this.body); +}; + +AST_Default.prototype._size = function () { + return 8 + list_overhead(this.body); +}; + +AST_Try.prototype._size = () => 3; + +AST_Catch.prototype._size = function () { + let size = 7 + list_overhead(this.body); + if (this.argname) { + size += 2; + } + return size; +}; + +AST_Finally.prototype._size = function () { + return 7 + list_overhead(this.body); +}; + +AST_Var.prototype._size = function () { + return 4 + list_overhead(this.definitions); +}; + +AST_Let.prototype._size = function () { + return 4 + list_overhead(this.definitions); +}; + +AST_Const.prototype._size = function () { + return 6 + list_overhead(this.definitions); +}; + +AST_VarDef.prototype._size = function () { + return this.value ? 1 : 0; +}; + +AST_NameMapping.prototype._size = function () { + // foreign name isn't mangled + return this.name ? 4 : 0; +}; + +AST_Import.prototype._size = function () { + // import + let size = 6; + + if (this.imported_name) size += 1; + + // from + if (this.imported_name || this.imported_names) size += 5; + + // braces, and the commas + if (this.imported_names) { + size += 2 + list_overhead(this.imported_names); + } + + return size; +}; + +AST_ImportMeta.prototype._size = () => 11; + +AST_Export.prototype._size = function () { + let size = 7 + (this.is_default ? 8 : 0); + + if (this.exported_value) { + size += this.exported_value._size(); + } + + if (this.exported_names) { + // Braces and commas + size += 2 + list_overhead(this.exported_names); + } + + if (this.module_name) { + // "from " + size += 5; + } + + return size; +}; + +AST_Call.prototype._size = function () { + if (this.optional) { + return 4 + list_overhead(this.args); + } + return 2 + list_overhead(this.args); +}; + +AST_New.prototype._size = function () { + return 6 + list_overhead(this.args); +}; + +AST_Sequence.prototype._size = function () { + return list_overhead(this.expressions); +}; + +AST_Dot.prototype._size = function () { + if (this.optional) { + return this.property.length + 2; + } + return this.property.length + 1; +}; + +AST_DotHash.prototype._size = function () { + if (this.optional) { + return this.property.length + 3; + } + return this.property.length + 2; +}; + +AST_Sub.prototype._size = function () { + return this.optional ? 4 : 2; +}; + +AST_Unary.prototype._size = function () { + if (this.operator === "typeof") return 7; + if (this.operator === "void") return 5; + return this.operator.length; +}; + +AST_Binary.prototype._size = function (info) { + if (this.operator === "in") return 4; + + let size = this.operator.length; + + if ( + (this.operator === "+" || this.operator === "-") + && this.right instanceof AST_Unary && this.right.operator === this.operator + ) { + // 1+ +a > needs space between the + + size += 1; + } + + if (this.needs_parens(info)) { + size += 2; + } + + return size; +}; + +AST_Conditional.prototype._size = () => 3; + +AST_Array.prototype._size = function () { + return 2 + list_overhead(this.elements); +}; + +AST_Object.prototype._size = function (info) { + let base = 2; + if (first_in_statement(info)) { + base += 2; // parens + } + return base + list_overhead(this.properties); +}; + +/*#__INLINE__*/ +const key_size = key => + typeof key === "string" ? key.length : 0; + +AST_ObjectKeyVal.prototype._size = function () { + return key_size(this.key) + 1; +}; + +/*#__INLINE__*/ +const static_size = is_static => is_static ? 7 : 0; + +AST_ObjectGetter.prototype._size = function () { + return 5 + static_size(this.static) + key_size(this.key); +}; + +AST_ObjectSetter.prototype._size = function () { + return 5 + static_size(this.static) + key_size(this.key); +}; + +AST_ConciseMethod.prototype._size = function () { + return static_size(this.static) + key_size(this.key) + lambda_modifiers(this); +}; + +AST_PrivateMethod.prototype._size = function () { + return AST_ConciseMethod.prototype._size.call(this) + 1; +}; + +AST_PrivateGetter.prototype._size = AST_PrivateSetter.prototype._size = function () { + return AST_ConciseMethod.prototype._size.call(this) + 4; +}; + +AST_PrivateIn.prototype._size = function () { + return 5; // "#", and " in " +}; + +AST_Class.prototype._size = function () { + return ( + (this.name ? 8 : 7) + + (this.extends ? 8 : 0) + ); +}; + +AST_ClassStaticBlock.prototype._size = function () { + // "static{}" + semicolons + return 8 + list_overhead(this.body); +}; + +AST_ClassProperty.prototype._size = function () { + return ( + static_size(this.static) + + (typeof this.key === "string" ? this.key.length + 2 : 0) + + (this.value ? 1 : 0) + ); +}; + +AST_ClassPrivateProperty.prototype._size = function () { + return AST_ClassProperty.prototype._size.call(this) + 1; +}; + +AST_Symbol.prototype._size = function () { + if (!(mangle_options && this.thedef && !this.thedef.unmangleable(mangle_options))) { + return this.name.length; + } else { + return 1; + } +}; + +// TODO take propmangle into account +AST_SymbolClassProperty.prototype._size = function () { + return this.name.length; +}; + +AST_SymbolRef.prototype._size = AST_SymbolDeclaration.prototype._size = function () { + if (this.name === "arguments") return 9; + + return AST_Symbol.prototype._size.call(this); +}; + +AST_NewTarget.prototype._size = () => 10; + +AST_SymbolImportForeign.prototype._size = function () { + return this.name.length; +}; + +AST_SymbolExportForeign.prototype._size = function () { + return this.name.length; +}; + +AST_This.prototype._size = () => 4; + +AST_Super.prototype._size = () => 5; + +AST_String.prototype._size = function () { + return this.value.length + 2; +}; + +AST_Number.prototype._size = function () { + const { value } = this; + if (value === 0) return 1; + if (value > 0 && Math.floor(value) === value) { + return Math.floor(Math.log10(value) + 1); + } + return value.toString().length; +}; + +AST_BigInt.prototype._size = function () { + return this.value.length; +}; + +AST_RegExp.prototype._size = function () { + return this.value.toString().length; +}; + +AST_Null.prototype._size = () => 4; + +AST_NaN.prototype._size = () => 3; + +AST_Undefined.prototype._size = () => 6; // "void 0" + +AST_Hole.prototype._size = () => 0; // comma is taken into account by list_overhead() + +AST_Infinity.prototype._size = () => 8; + +AST_True.prototype._size = () => 4; + +AST_False.prototype._size = () => 5; + +AST_Await.prototype._size = () => 6; + +AST_Yield.prototype._size = () => 6; diff --git a/node_modules/terser/lib/sourcemap.js b/node_modules/terser/lib/sourcemap.js new file mode 100644 index 0000000..101c748 --- /dev/null +++ b/node_modules/terser/lib/sourcemap.js @@ -0,0 +1,148 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +import {SourceMapConsumer, SourceMapGenerator} from "@jridgewell/source-map"; +import {defaults, HOP} from "./utils/index.js"; + +// a small wrapper around source-map and @jridgewell/source-map +function* SourceMap(options) { + options = defaults(options, { + file : null, + root : null, + orig : null, + files: {}, + }); + + var orig_map; + var generator = new SourceMapGenerator({ + file : options.file, + sourceRoot : options.root + }); + + let sourcesContent = {__proto__: null}; + let files = options.files; + for (var name in files) if (HOP(files, name)) { + sourcesContent[name] = files[name]; + } + if (options.orig) { + // We support both @jridgewell/source-map (which has a sync + // SourceMapConsumer) and source-map (which has an async + // SourceMapConsumer). + orig_map = yield new SourceMapConsumer(options.orig); + if (orig_map.sourcesContent) { + orig_map.sources.forEach(function(source, i) { + var content = orig_map.sourcesContent[i]; + if (content) { + sourcesContent[source] = content; + } + }); + } + } + + function add(source, gen_line, gen_col, orig_line, orig_col, name) { + let generatedPos = { line: gen_line, column: gen_col }; + + if (orig_map) { + var info = orig_map.originalPositionFor({ + line: orig_line, + column: orig_col + }); + if (info.source === null) { + generator.addMapping({ + generated: generatedPos, + original: null, + source: null, + name: null + }); + return; + } + source = info.source; + orig_line = info.line; + orig_col = info.column; + name = info.name || name; + } + generator.addMapping({ + generated : generatedPos, + original : { line: orig_line, column: orig_col }, + source : source, + name : name + }); + generator.setSourceContent(source, sourcesContent[source]); + } + + function clean(map) { + const allNull = map.sourcesContent && map.sourcesContent.every(c => c == null); + if (allNull) delete map.sourcesContent; + if (map.file === undefined) delete map.file; + if (map.sourceRoot === undefined) delete map.sourceRoot; + return map; + } + + function getDecoded() { + if (!generator.toDecodedMap) return null; + return clean(generator.toDecodedMap()); + } + + function getEncoded() { + return clean(generator.toJSON()); + } + + function destroy() { + // @jridgewell/source-map's SourceMapConsumer does not need to be + // manually freed. + if (orig_map && orig_map.destroy) orig_map.destroy(); + } + + return { + add, + getDecoded, + getEncoded, + destroy, + }; +} + +export { + SourceMap, +}; diff --git a/node_modules/terser/lib/transform.js b/node_modules/terser/lib/transform.js new file mode 100644 index 0000000..7dd880a --- /dev/null +++ b/node_modules/terser/lib/transform.js @@ -0,0 +1,323 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +import { + AST_Array, + AST_Await, + AST_Binary, + AST_PrivateIn, + AST_Block, + AST_Call, + AST_Case, + AST_Catch, + AST_Chain, + AST_Class, + AST_ClassStaticBlock, + AST_Conditional, + AST_Definitions, + AST_Destructuring, + AST_Do, + AST_Exit, + AST_Expansion, + AST_Export, + AST_For, + AST_ForIn, + AST_If, + AST_Import, + AST_LabeledStatement, + AST_Lambda, + AST_LoopControl, + AST_NameMapping, + AST_Node, + AST_Number, + AST_Object, + AST_ObjectProperty, + AST_PrefixedTemplateString, + AST_PropAccess, + AST_Sequence, + AST_SimpleStatement, + AST_Sub, + AST_Switch, + AST_TemplateString, + AST_Try, + AST_Unary, + AST_VarDef, + AST_While, + AST_With, + AST_Yield, +} from "./ast.js"; +import { + MAP as do_list, + noop, +} from "./utils/index.js"; + +function def_transform(node, descend) { + node.DEFMETHOD("transform", function(tw, in_list) { + let transformed = undefined; + tw.push(this); + if (tw.before) transformed = tw.before(this, descend, in_list); + if (transformed === undefined) { + transformed = this; + descend(transformed, tw); + if (tw.after) { + const after_ret = tw.after(transformed, in_list); + if (after_ret !== undefined) transformed = after_ret; + } + } + tw.pop(); + return transformed; + }); +} + +def_transform(AST_Node, noop); + +def_transform(AST_LabeledStatement, function(self, tw) { + self.label = self.label.transform(tw); + self.body = self.body.transform(tw); +}); + +def_transform(AST_SimpleStatement, function(self, tw) { + self.body = self.body.transform(tw); +}); + +def_transform(AST_Block, function(self, tw) { + self.body = do_list(self.body, tw); +}); + +def_transform(AST_Do, function(self, tw) { + self.body = self.body.transform(tw); + self.condition = self.condition.transform(tw); +}); + +def_transform(AST_While, function(self, tw) { + self.condition = self.condition.transform(tw); + self.body = self.body.transform(tw); +}); + +def_transform(AST_For, function(self, tw) { + if (self.init) self.init = self.init.transform(tw); + if (self.condition) self.condition = self.condition.transform(tw); + if (self.step) self.step = self.step.transform(tw); + self.body = self.body.transform(tw); +}); + +def_transform(AST_ForIn, function(self, tw) { + self.init = self.init.transform(tw); + self.object = self.object.transform(tw); + self.body = self.body.transform(tw); +}); + +def_transform(AST_With, function(self, tw) { + self.expression = self.expression.transform(tw); + self.body = self.body.transform(tw); +}); + +def_transform(AST_Exit, function(self, tw) { + if (self.value) self.value = self.value.transform(tw); +}); + +def_transform(AST_LoopControl, function(self, tw) { + if (self.label) self.label = self.label.transform(tw); +}); + +def_transform(AST_If, function(self, tw) { + self.condition = self.condition.transform(tw); + self.body = self.body.transform(tw); + if (self.alternative) self.alternative = self.alternative.transform(tw); +}); + +def_transform(AST_Switch, function(self, tw) { + self.expression = self.expression.transform(tw); + self.body = do_list(self.body, tw); +}); + +def_transform(AST_Case, function(self, tw) { + self.expression = self.expression.transform(tw); + self.body = do_list(self.body, tw); +}); + +def_transform(AST_Try, function(self, tw) { + self.body = self.body.transform(tw); + if (self.bcatch) self.bcatch = self.bcatch.transform(tw); + if (self.bfinally) self.bfinally = self.bfinally.transform(tw); +}); + +def_transform(AST_Catch, function(self, tw) { + if (self.argname) self.argname = self.argname.transform(tw); + self.body = do_list(self.body, tw); +}); + +def_transform(AST_Definitions, function(self, tw) { + self.definitions = do_list(self.definitions, tw); +}); + +def_transform(AST_VarDef, function(self, tw) { + self.name = self.name.transform(tw); + if (self.value) self.value = self.value.transform(tw); +}); + +def_transform(AST_Destructuring, function(self, tw) { + self.names = do_list(self.names, tw); +}); + +def_transform(AST_Lambda, function(self, tw) { + if (self.name) self.name = self.name.transform(tw); + self.argnames = do_list(self.argnames, tw, /* allow_splicing */ false); + if (self.body instanceof AST_Node) { + self.body = self.body.transform(tw); + } else { + self.body = do_list(self.body, tw); + } +}); + +def_transform(AST_Call, function(self, tw) { + self.expression = self.expression.transform(tw); + self.args = do_list(self.args, tw, /* allow_splicing */ false); +}); + +def_transform(AST_Sequence, function(self, tw) { + const result = do_list(self.expressions, tw); + self.expressions = result.length + ? result + : [new AST_Number({ value: 0 })]; +}); + +def_transform(AST_PropAccess, function(self, tw) { + self.expression = self.expression.transform(tw); +}); + +def_transform(AST_Sub, function(self, tw) { + self.expression = self.expression.transform(tw); + self.property = self.property.transform(tw); +}); + +def_transform(AST_Chain, function(self, tw) { + self.expression = self.expression.transform(tw); +}); + +def_transform(AST_Yield, function(self, tw) { + if (self.expression) self.expression = self.expression.transform(tw); +}); + +def_transform(AST_Await, function(self, tw) { + self.expression = self.expression.transform(tw); +}); + +def_transform(AST_Unary, function(self, tw) { + self.expression = self.expression.transform(tw); +}); + +def_transform(AST_Binary, function(self, tw) { + self.left = self.left.transform(tw); + self.right = self.right.transform(tw); +}); + +def_transform(AST_PrivateIn, function(self, tw) { + self.key = self.key.transform(tw); + self.value = self.value.transform(tw); +}); + +def_transform(AST_Conditional, function(self, tw) { + self.condition = self.condition.transform(tw); + self.consequent = self.consequent.transform(tw); + self.alternative = self.alternative.transform(tw); +}); + +def_transform(AST_Array, function(self, tw) { + self.elements = do_list(self.elements, tw); +}); + +def_transform(AST_Object, function(self, tw) { + self.properties = do_list(self.properties, tw); +}); + +def_transform(AST_ObjectProperty, function(self, tw) { + if (self.key instanceof AST_Node) { + self.key = self.key.transform(tw); + } + if (self.value) self.value = self.value.transform(tw); +}); + +def_transform(AST_Class, function(self, tw) { + if (self.name) self.name = self.name.transform(tw); + if (self.extends) self.extends = self.extends.transform(tw); + self.properties = do_list(self.properties, tw); +}); + +def_transform(AST_ClassStaticBlock, function(self, tw) { + self.body = do_list(self.body, tw); +}); + +def_transform(AST_Expansion, function(self, tw) { + self.expression = self.expression.transform(tw); +}); + +def_transform(AST_NameMapping, function(self, tw) { + self.foreign_name = self.foreign_name.transform(tw); + self.name = self.name.transform(tw); +}); + +def_transform(AST_Import, function(self, tw) { + if (self.imported_name) self.imported_name = self.imported_name.transform(tw); + if (self.imported_names) do_list(self.imported_names, tw); + self.module_name = self.module_name.transform(tw); +}); + +def_transform(AST_Export, function(self, tw) { + if (self.exported_definition) self.exported_definition = self.exported_definition.transform(tw); + if (self.exported_value) self.exported_value = self.exported_value.transform(tw); + if (self.exported_names) do_list(self.exported_names, tw); + if (self.module_name) self.module_name = self.module_name.transform(tw); +}); + +def_transform(AST_TemplateString, function(self, tw) { + self.segments = do_list(self.segments, tw); +}); + +def_transform(AST_PrefixedTemplateString, function(self, tw) { + self.prefix = self.prefix.transform(tw); + self.template_string = self.template_string.transform(tw); +}); + diff --git a/node_modules/terser/lib/utils/first_in_statement.js b/node_modules/terser/lib/utils/first_in_statement.js new file mode 100644 index 0000000..6aa4628 --- /dev/null +++ b/node_modules/terser/lib/utils/first_in_statement.js @@ -0,0 +1,53 @@ +import { + AST_Binary, + AST_Conditional, + AST_Chain, + AST_Dot, + AST_Object, + AST_Sequence, + AST_Statement, + AST_Sub, + AST_UnaryPostfix, + AST_PrefixedTemplateString +} from "../ast.js"; + +// return true if the node at the top of the stack (that means the +// innermost node in the current output) is lexically the first in +// a statement. +function first_in_statement(stack) { + let node = stack.parent(-1); + for (let i = 0, p; p = stack.parent(i); i++) { + if (p instanceof AST_Statement && p.body === node) + return true; + if ((p instanceof AST_Sequence && p.expressions[0] === node) || + (p.TYPE === "Call" && p.expression === node) || + (p instanceof AST_PrefixedTemplateString && p.prefix === node) || + (p instanceof AST_Dot && p.expression === node) || + (p instanceof AST_Sub && p.expression === node) || + (p instanceof AST_Chain && p.expression === node) || + (p instanceof AST_Conditional && p.condition === node) || + (p instanceof AST_Binary && p.left === node) || + (p instanceof AST_UnaryPostfix && p.expression === node) + ) { + node = p; + } else { + return false; + } + } +} + +// Returns whether the leftmost item in the expression is an object +function left_is_object(node) { + if (node instanceof AST_Object) return true; + if (node instanceof AST_Sequence) return left_is_object(node.expressions[0]); + if (node.TYPE === "Call") return left_is_object(node.expression); + if (node instanceof AST_PrefixedTemplateString) return left_is_object(node.prefix); + if (node instanceof AST_Dot || node instanceof AST_Sub) return left_is_object(node.expression); + if (node instanceof AST_Chain) return left_is_object(node.expression); + if (node instanceof AST_Conditional) return left_is_object(node.condition); + if (node instanceof AST_Binary) return left_is_object(node.left); + if (node instanceof AST_UnaryPostfix) return left_is_object(node.expression); + return false; +} + +export { first_in_statement, left_is_object }; diff --git a/node_modules/terser/lib/utils/index.js b/node_modules/terser/lib/utils/index.js new file mode 100644 index 0000000..65fa989 --- /dev/null +++ b/node_modules/terser/lib/utils/index.js @@ -0,0 +1,295 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +import { AST_Node } from "../ast.js"; + +function characters(str) { + return str.split(""); +} + +function member(name, array) { + return array.includes(name); +} + +class DefaultsError extends Error { + constructor(msg, defs) { + super(); + + this.name = "DefaultsError"; + this.message = msg; + this.defs = defs; + } +} + +function defaults(args, defs, croak) { + if (args === true) { + args = {}; + } else if (args != null && typeof args === "object") { + args = {...args}; + } + + const ret = args || {}; + + if (croak) for (const i in ret) if (HOP(ret, i) && !HOP(defs, i)) { + throw new DefaultsError("`" + i + "` is not a supported option", defs); + } + + for (const i in defs) if (HOP(defs, i)) { + if (!args || !HOP(args, i)) { + ret[i] = defs[i]; + } else if (i === "ecma") { + let ecma = args[i] | 0; + if (ecma > 5 && ecma < 2015) ecma += 2009; + ret[i] = ecma; + } else { + ret[i] = (args && HOP(args, i)) ? args[i] : defs[i]; + } + } + + return ret; +} + +function noop() {} +function return_false() { return false; } +function return_true() { return true; } +function return_this() { return this; } +function return_null() { return null; } + +var MAP = (function() { + function MAP(a, tw, allow_splicing = true) { + const new_a = []; + + for (let i = 0; i < a.length; ++i) { + let item = a[i]; + let ret = item.transform(tw, allow_splicing); + + if (ret instanceof AST_Node) { + new_a.push(ret); + } else if (ret instanceof Splice) { + new_a.push(...ret.v); + } + } + + return new_a; + } + + MAP.splice = function(val) { return new Splice(val); }; + MAP.skip = {}; + function Splice(val) { this.v = val; } + return MAP; +})(); + +function make_node(ctor, orig, props) { + if (!props) props = {}; + if (orig) { + if (!props.start) props.start = orig.start; + if (!props.end) props.end = orig.end; + } + return new ctor(props); +} + +function push_uniq(array, el) { + if (!array.includes(el)) + array.push(el); +} + +function string_template(text, props) { + return text.replace(/{(.+?)}/g, function(str, p) { + return props && props[p]; + }); +} + +function remove(array, el) { + for (var i = array.length; --i >= 0;) { + if (array[i] === el) array.splice(i, 1); + } +} + +function mergeSort(array, cmp) { + if (array.length < 2) return array.slice(); + function merge(a, b) { + var r = [], ai = 0, bi = 0, i = 0; + while (ai < a.length && bi < b.length) { + cmp(a[ai], b[bi]) <= 0 + ? r[i++] = a[ai++] + : r[i++] = b[bi++]; + } + if (ai < a.length) r.push.apply(r, a.slice(ai)); + if (bi < b.length) r.push.apply(r, b.slice(bi)); + return r; + } + function _ms(a) { + if (a.length <= 1) + return a; + var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m); + left = _ms(left); + right = _ms(right); + return merge(left, right); + } + return _ms(array); +} + +function makePredicate(words) { + if (!Array.isArray(words)) words = words.split(" "); + + return new Set(words.sort()); +} + +function map_add(map, key, value) { + if (map.has(key)) { + map.get(key).push(value); + } else { + map.set(key, [ value ]); + } +} + +function map_from_object(obj) { + var map = new Map(); + for (var key in obj) { + if (HOP(obj, key) && key.charAt(0) === "$") { + map.set(key.substr(1), obj[key]); + } + } + return map; +} + +function map_to_object(map) { + var obj = Object.create(null); + map.forEach(function (value, key) { + obj["$" + key] = value; + }); + return obj; +} + +function HOP(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +function keep_name(keep_setting, name) { + return keep_setting === true + || (keep_setting instanceof RegExp && keep_setting.test(name)); +} + +var lineTerminatorEscape = { + "\0": "0", + "\n": "n", + "\r": "r", + "\u2028": "u2028", + "\u2029": "u2029", +}; +function regexp_source_fix(source) { + // V8 does not escape line terminators in regexp patterns in node 12 + // We'll also remove literal \0 + return source.replace(/[\0\n\r\u2028\u2029]/g, function (match, offset) { + var escaped = source[offset - 1] == "\\" + && (source[offset - 2] != "\\" + || /(?:^|[^\\])(?:\\{2})*$/.test(source.slice(0, offset - 1))); + return (escaped ? "" : "\\") + lineTerminatorEscape[match]; + }); +} + +// Subset of regexps that is not going to cause regexp based DDOS +// https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS +const re_safe_regexp = /^[\\/|\0\s\w^$.[\]()]*$/; + +/** Check if the regexp is safe for Terser to create without risking a RegExp DOS */ +export const regexp_is_safe = (source) => re_safe_regexp.test(source); + +const all_flags = "dgimsuyv"; +function sort_regexp_flags(flags) { + const existing_flags = new Set(flags.split("")); + let out = ""; + for (const flag of all_flags) { + if (existing_flags.has(flag)) { + out += flag; + existing_flags.delete(flag); + } + } + if (existing_flags.size) { + // Flags Terser doesn't know about + existing_flags.forEach(flag => { out += flag; }); + } + return out; +} + +function has_annotation(node, annotation) { + return node._annotations & annotation; +} + +function set_annotation(node, annotation) { + node._annotations |= annotation; +} + +function clear_annotation(node, annotation) { + node._annotations &= ~annotation; +} + +export { + characters, + defaults, + HOP, + keep_name, + make_node, + makePredicate, + map_add, + map_from_object, + map_to_object, + MAP, + member, + mergeSort, + noop, + push_uniq, + regexp_source_fix, + remove, + return_false, + return_null, + return_this, + return_true, + sort_regexp_flags, + string_template, + has_annotation, + set_annotation, + clear_annotation, +}; diff --git a/node_modules/terser/main.js b/node_modules/terser/main.js new file mode 100644 index 0000000..56ab363 --- /dev/null +++ b/node_modules/terser/main.js @@ -0,0 +1,27 @@ +import "./lib/transform.js"; +import "./lib/mozilla-ast.js"; +import { minify } from "./lib/minify.js"; + +export { minify, minify_sync } from "./lib/minify.js"; +export { run_cli as _run_cli } from "./lib/cli.js"; + +export async function _default_options() { + const defs = {}; + + Object.keys(infer_options({ 0: 0 })).forEach((component) => { + const options = infer_options({ + [component]: {0: 0} + }); + + if (options) defs[component] = options; + }); + return defs; +} + +async function infer_options(options) { + try { + await minify("", options); + } catch (error) { + return error.defs; + } +} diff --git a/node_modules/terser/package.json b/node_modules/terser/package.json new file mode 100644 index 0000000..af9d9a2 --- /dev/null +++ b/node_modules/terser/package.json @@ -0,0 +1,153 @@ +{ + "name": "terser", + "description": "JavaScript parser, mangler/compressor and beautifier toolkit for ES6+", + "homepage": "https://terser.org", + "author": "Mihai Bazon (http://lisperator.net/)", + "license": "BSD-2-Clause", + "version": "5.33.0", + "engines": { + "node": ">=10" + }, + "maintainers": [ + "Fábio Santos " + ], + "repository": "https://github.com/terser/terser", + "main": "dist/bundle.min.js", + "type": "module", + "module": "./main.js", + "exports": { + ".": [ + { + "types": "./tools/terser.d.ts", + "import": "./main.js", + "require": "./dist/bundle.min.js" + }, + "./dist/bundle.min.js" + ], + "./package": "./package.json", + "./package.json": "./package.json", + "./bin/terser": "./bin/terser" + }, + "types": "tools/terser.d.ts", + "bin": { + "terser": "bin/terser" + }, + "files": [ + "bin", + "dist", + "lib", + "tools", + "LICENSE", + "README.md", + "CHANGELOG.md", + "PATRONS.md", + "main.js" + ], + "dependencies": { + "@jridgewell/source-map": "^0.3.3", + "acorn": "^8.8.2", + "commander": "^2.20.0", + "source-map-support": "~0.5.20" + }, + "devDependencies": { + "@ls-lint/ls-lint": "^1.11.2", + "astring": "^1.8.5", + "eslint": "^7.32.0", + "eslump": "^3.0.0", + "esm": "^3.2.25", + "mocha": "^9.2.0", + "pre-commit": "^1.2.2", + "rollup": "^2.56.3", + "semver": "^7.5.1", + "source-map": "~0.8.0-beta.0" + }, + "scripts": { + "test": "node test/compress.js && mocha test/mocha", + "test:compress": "node test/compress.js", + "test:mocha": "mocha test/mocha", + "lint": "eslint lib", + "lint-fix": "eslint --fix lib", + "ls-lint": "ls-lint", + "build": "rollup --config --silent", + "prepare": "npm run build", + "postversion": "echo 'Remember to update the changelog!'" + }, + "keywords": [ + "uglify", + "terser", + "uglify-es", + "uglify-js", + "minify", + "minifier", + "javascript", + "ecmascript", + "es5", + "es6", + "es7", + "es8", + "es2015", + "es2016", + "es2017", + "async", + "await" + ], + "eslintConfig": { + "parserOptions": { + "sourceType": "module", + "ecmaVersion": 2020 + }, + "env": { + "node": true, + "browser": true, + "es2020": true + }, + "globals": { + "describe": false, + "it": false, + "require": false, + "before": false, + "after": false, + "global": false, + "process": false + }, + "rules": { + "brace-style": [ + "error", + "1tbs", + { + "allowSingleLine": true + } + ], + "quotes": [ + "error", + "double", + "avoid-escape" + ], + "no-debugger": "error", + "no-undef": "error", + "no-unused-vars": [ + "error", + { + "varsIgnorePattern": "^_" + } + ], + "no-tabs": "error", + "semi": [ + "error", + "always" + ], + "no-extra-semi": "error", + "no-irregular-whitespace": "error", + "space-before-blocks": [ + "error", + "always" + ] + } + }, + "pre-commit": [ + "build", + "lint-fix", + "ls-lint", + "test" + ] +} diff --git a/node_modules/terser/tools/domprops.js b/node_modules/terser/tools/domprops.js new file mode 100644 index 0000000..aca453e --- /dev/null +++ b/node_modules/terser/tools/domprops.js @@ -0,0 +1,8731 @@ +export var domprops = [ + "$&", + "$'", + "$*", + "$+", + "$1", + "$2", + "$3", + "$4", + "$5", + "$6", + "$7", + "$8", + "$9", + "$_", + "$`", + "$input", + "-moz-animation", + "-moz-animation-delay", + "-moz-animation-direction", + "-moz-animation-duration", + "-moz-animation-fill-mode", + "-moz-animation-iteration-count", + "-moz-animation-name", + "-moz-animation-play-state", + "-moz-animation-timing-function", + "-moz-appearance", + "-moz-backface-visibility", + "-moz-border-end", + "-moz-border-end-color", + "-moz-border-end-style", + "-moz-border-end-width", + "-moz-border-image", + "-moz-border-start", + "-moz-border-start-color", + "-moz-border-start-style", + "-moz-border-start-width", + "-moz-box-align", + "-moz-box-direction", + "-moz-box-flex", + "-moz-box-ordinal-group", + "-moz-box-orient", + "-moz-box-pack", + "-moz-box-sizing", + "-moz-float-edge", + "-moz-font-feature-settings", + "-moz-font-language-override", + "-moz-force-broken-image-icon", + "-moz-hyphens", + "-moz-image-region", + "-moz-margin-end", + "-moz-margin-start", + "-moz-orient", + "-moz-osx-font-smoothing", + "-moz-outline-radius", + "-moz-outline-radius-bottomleft", + "-moz-outline-radius-bottomright", + "-moz-outline-radius-topleft", + "-moz-outline-radius-topright", + "-moz-padding-end", + "-moz-padding-start", + "-moz-perspective", + "-moz-perspective-origin", + "-moz-tab-size", + "-moz-text-size-adjust", + "-moz-transform", + "-moz-transform-origin", + "-moz-transform-style", + "-moz-transition", + "-moz-transition-delay", + "-moz-transition-duration", + "-moz-transition-property", + "-moz-transition-timing-function", + "-moz-user-focus", + "-moz-user-input", + "-moz-user-modify", + "-moz-user-select", + "-moz-window-dragging", + "-webkit-align-content", + "-webkit-align-items", + "-webkit-align-self", + "-webkit-animation", + "-webkit-animation-delay", + "-webkit-animation-direction", + "-webkit-animation-duration", + "-webkit-animation-fill-mode", + "-webkit-animation-iteration-count", + "-webkit-animation-name", + "-webkit-animation-play-state", + "-webkit-animation-timing-function", + "-webkit-appearance", + "-webkit-backface-visibility", + "-webkit-background-clip", + "-webkit-background-origin", + "-webkit-background-size", + "-webkit-border-bottom-left-radius", + "-webkit-border-bottom-right-radius", + "-webkit-border-image", + "-webkit-border-radius", + "-webkit-border-top-left-radius", + "-webkit-border-top-right-radius", + "-webkit-box-align", + "-webkit-box-direction", + "-webkit-box-flex", + "-webkit-box-ordinal-group", + "-webkit-box-orient", + "-webkit-box-pack", + "-webkit-box-shadow", + "-webkit-box-sizing", + "-webkit-clip-path", + "-webkit-filter", + "-webkit-flex", + "-webkit-flex-basis", + "-webkit-flex-direction", + "-webkit-flex-flow", + "-webkit-flex-grow", + "-webkit-flex-shrink", + "-webkit-flex-wrap", + "-webkit-justify-content", + "-webkit-line-clamp", + "-webkit-mask", + "-webkit-mask-clip", + "-webkit-mask-composite", + "-webkit-mask-image", + "-webkit-mask-origin", + "-webkit-mask-position", + "-webkit-mask-position-x", + "-webkit-mask-position-y", + "-webkit-mask-repeat", + "-webkit-mask-size", + "-webkit-order", + "-webkit-perspective", + "-webkit-perspective-origin", + "-webkit-text-fill-color", + "-webkit-text-security", + "-webkit-text-size-adjust", + "-webkit-text-stroke", + "-webkit-text-stroke-color", + "-webkit-text-stroke-width", + "-webkit-transform", + "-webkit-transform-origin", + "-webkit-transform-style", + "-webkit-transition", + "-webkit-transition-delay", + "-webkit-transition-duration", + "-webkit-transition-property", + "-webkit-transition-timing-function", + "-webkit-user-select", + "0", + "1", + "10", + "11", + "12", + "13", + "14", + "15", + "16", + "17", + "18", + "19", + "2", + "20", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "@@iterator", + "ABORT_ERR", + "ACTIVE", + "ACTIVE_ATTRIBUTES", + "ACTIVE_TEXTURE", + "ACTIVE_UNIFORMS", + "ACTIVE_UNIFORM_BLOCKS", + "ADDITION", + "ALIASED_LINE_WIDTH_RANGE", + "ALIASED_POINT_SIZE_RANGE", + "ALL", + "ALLOW_KEYBOARD_INPUT", + "ALLPASS", + "ALPHA", + "ALPHA_BITS", + "ALREADY_SIGNALED", + "ALT_MASK", + "ALWAYS", + "ANY_SAMPLES_PASSED", + "ANY_SAMPLES_PASSED_CONSERVATIVE", + "ANY_TYPE", + "ANY_UNORDERED_NODE_TYPE", + "ARRAY_BUFFER", + "ARRAY_BUFFER_BINDING", + "ATTACHED_SHADERS", + "ATTRIBUTE_NODE", + "AT_TARGET", + "AbortController", + "AbortSignal", + "AbsoluteOrientationSensor", + "AbstractRange", + "Accelerometer", + "AddSearchProvider", + "AggregateError", + "AnalyserNode", + "Animation", + "AnimationEffect", + "AnimationEvent", + "AnimationPlaybackEvent", + "AnimationTimeline", + "AnonXMLHttpRequest", + "Any", + "ApplicationCache", + "ApplicationCacheErrorEvent", + "Array", + "ArrayBuffer", + "ArrayType", + "Atomics", + "Attr", + "Audio", + "AudioBuffer", + "AudioBufferSourceNode", + "AudioContext", + "AudioData", + "AudioDecoder", + "AudioDestinationNode", + "AudioEncoder", + "AudioListener", + "AudioNode", + "AudioParam", + "AudioParamMap", + "AudioProcessingEvent", + "AudioScheduledSourceNode", + "AudioSinkInfo", + "AudioStreamTrack", + "AudioWorklet", + "AudioWorkletNode", + "AuthenticatorAssertionResponse", + "AuthenticatorAttestationResponse", + "AuthenticatorResponse", + "AutocompleteErrorEvent", + "BACK", + "BAD_BOUNDARYPOINTS_ERR", + "BAD_REQUEST", + "BANDPASS", + "BLEND", + "BLEND_COLOR", + "BLEND_DST_ALPHA", + "BLEND_DST_RGB", + "BLEND_EQUATION", + "BLEND_EQUATION_ALPHA", + "BLEND_EQUATION_RGB", + "BLEND_SRC_ALPHA", + "BLEND_SRC_RGB", + "BLUE", + "BLUE_BITS", + "BLUR", + "BOOL", + "BOOLEAN_TYPE", + "BOOL_VEC2", + "BOOL_VEC3", + "BOOL_VEC4", + "BOTH", + "BROWSER_DEFAULT_WEBGL", + "BUBBLING_PHASE", + "BUFFER_SIZE", + "BUFFER_USAGE", + "BYTE", + "BYTES_PER_ELEMENT", + "BackgroundFetchManager", + "BackgroundFetchRecord", + "BackgroundFetchRegistration", + "BarProp", + "BarcodeDetector", + "BaseAudioContext", + "BaseHref", + "BatteryManager", + "BeforeInstallPromptEvent", + "BeforeLoadEvent", + "BeforeUnloadEvent", + "BigInt", + "BigInt64Array", + "BigUint64Array", + "BiquadFilterNode", + "Blob", + "BlobEvent", + "Bluetooth", + "BluetoothCharacteristicProperties", + "BluetoothDevice", + "BluetoothRemoteGATTCharacteristic", + "BluetoothRemoteGATTDescriptor", + "BluetoothRemoteGATTServer", + "BluetoothRemoteGATTService", + "BluetoothUUID", + "Boolean", + "BroadcastChannel", + "BrowserCaptureMediaStreamTrack", + "ByteLengthQueuingStrategy", + "CAPTURING_PHASE", + "CCW", + "CDATASection", + "CDATA_SECTION_NODE", + "CHANGE", + "CHARSET_RULE", + "CHECKING", + "CLAMP_TO_EDGE", + "CLICK", + "CLOSED", + "CLOSING", + "COLOR", + "COLOR_ATTACHMENT0", + "COLOR_ATTACHMENT1", + "COLOR_ATTACHMENT10", + "COLOR_ATTACHMENT11", + "COLOR_ATTACHMENT12", + "COLOR_ATTACHMENT13", + "COLOR_ATTACHMENT14", + "COLOR_ATTACHMENT15", + "COLOR_ATTACHMENT2", + "COLOR_ATTACHMENT3", + "COLOR_ATTACHMENT4", + "COLOR_ATTACHMENT5", + "COLOR_ATTACHMENT6", + "COLOR_ATTACHMENT7", + "COLOR_ATTACHMENT8", + "COLOR_ATTACHMENT9", + "COLOR_BUFFER_BIT", + "COLOR_CLEAR_VALUE", + "COLOR_WRITEMASK", + "COMMENT_NODE", + "COMPARE_REF_TO_TEXTURE", + "COMPILE_STATUS", + "COMPLETION_STATUS_KHR", + "COMPRESSED_RGBA_S3TC_DXT1_EXT", + "COMPRESSED_RGBA_S3TC_DXT3_EXT", + "COMPRESSED_RGBA_S3TC_DXT5_EXT", + "COMPRESSED_RGB_S3TC_DXT1_EXT", + "COMPRESSED_TEXTURE_FORMATS", + "COMPUTE", + "CONDITION_SATISFIED", + "CONFIGURATION_UNSUPPORTED", + "CONNECTING", + "CONSTANT_ALPHA", + "CONSTANT_COLOR", + "CONSTRAINT_ERR", + "CONTEXT_LOST_WEBGL", + "CONTROL_MASK", + "COPY_DST", + "COPY_READ_BUFFER", + "COPY_READ_BUFFER_BINDING", + "COPY_SRC", + "COPY_WRITE_BUFFER", + "COPY_WRITE_BUFFER_BINDING", + "COUNTER_STYLE_RULE", + "CSS", + "CSS2Properties", + "CSSAnimation", + "CSSCharsetRule", + "CSSConditionRule", + "CSSContainerRule", + "CSSCounterStyleRule", + "CSSFontFaceRule", + "CSSFontFeatureValuesRule", + "CSSFontPaletteValuesRule", + "CSSGroupingRule", + "CSSImageValue", + "CSSImportRule", + "CSSKeyframeRule", + "CSSKeyframesRule", + "CSSKeywordValue", + "CSSLayerBlockRule", + "CSSLayerStatementRule", + "CSSMathClamp", + "CSSMathInvert", + "CSSMathMax", + "CSSMathMin", + "CSSMathNegate", + "CSSMathProduct", + "CSSMathSum", + "CSSMathValue", + "CSSMatrixComponent", + "CSSMediaRule", + "CSSMozDocumentRule", + "CSSNameSpaceRule", + "CSSNamespaceRule", + "CSSNumericArray", + "CSSNumericValue", + "CSSPageRule", + "CSSPerspective", + "CSSPositionValue", + "CSSPrimitiveValue", + "CSSPropertyRule", + "CSSRotate", + "CSSRule", + "CSSRuleList", + "CSSScale", + "CSSScopeRule", + "CSSSkew", + "CSSSkewX", + "CSSSkewY", + "CSSStartingStyleRule", + "CSSStyleDeclaration", + "CSSStyleRule", + "CSSStyleSheet", + "CSSStyleValue", + "CSSSupportsRule", + "CSSTransformComponent", + "CSSTransformValue", + "CSSTransition", + "CSSTranslate", + "CSSUnitValue", + "CSSUnknownRule", + "CSSUnparsedValue", + "CSSValue", + "CSSValueList", + "CSSVariableReferenceValue", + "CSSVariablesDeclaration", + "CSSVariablesRule", + "CSSViewportRule", + "CSS_ATTR", + "CSS_CM", + "CSS_COUNTER", + "CSS_CUSTOM", + "CSS_DEG", + "CSS_DIMENSION", + "CSS_EMS", + "CSS_EXS", + "CSS_FILTER_BLUR", + "CSS_FILTER_BRIGHTNESS", + "CSS_FILTER_CONTRAST", + "CSS_FILTER_CUSTOM", + "CSS_FILTER_DROP_SHADOW", + "CSS_FILTER_GRAYSCALE", + "CSS_FILTER_HUE_ROTATE", + "CSS_FILTER_INVERT", + "CSS_FILTER_OPACITY", + "CSS_FILTER_REFERENCE", + "CSS_FILTER_SATURATE", + "CSS_FILTER_SEPIA", + "CSS_GRAD", + "CSS_HZ", + "CSS_IDENT", + "CSS_IN", + "CSS_INHERIT", + "CSS_KHZ", + "CSS_MATRIX", + "CSS_MATRIX3D", + "CSS_MM", + "CSS_MS", + "CSS_NUMBER", + "CSS_PC", + "CSS_PERCENTAGE", + "CSS_PERSPECTIVE", + "CSS_PRIMITIVE_VALUE", + "CSS_PT", + "CSS_PX", + "CSS_RAD", + "CSS_RECT", + "CSS_RGBCOLOR", + "CSS_ROTATE", + "CSS_ROTATE3D", + "CSS_ROTATEX", + "CSS_ROTATEY", + "CSS_ROTATEZ", + "CSS_S", + "CSS_SCALE", + "CSS_SCALE3D", + "CSS_SCALEX", + "CSS_SCALEY", + "CSS_SCALEZ", + "CSS_SKEW", + "CSS_SKEWX", + "CSS_SKEWY", + "CSS_STRING", + "CSS_TRANSLATE", + "CSS_TRANSLATE3D", + "CSS_TRANSLATEX", + "CSS_TRANSLATEY", + "CSS_TRANSLATEZ", + "CSS_UNKNOWN", + "CSS_URI", + "CSS_VALUE_LIST", + "CSS_VH", + "CSS_VMAX", + "CSS_VMIN", + "CSS_VW", + "CULL_FACE", + "CULL_FACE_MODE", + "CURRENT_PROGRAM", + "CURRENT_QUERY", + "CURRENT_VERTEX_ATTRIB", + "CUSTOM", + "CW", + "Cache", + "CacheStorage", + "CanvasCaptureMediaStream", + "CanvasCaptureMediaStreamTrack", + "CanvasGradient", + "CanvasPattern", + "CanvasRenderingContext2D", + "CaptureController", + "CaretPosition", + "ChannelMergerNode", + "ChannelSplitterNode", + "CharacterBoundsUpdateEvent", + "CharacterData", + "ClientRect", + "ClientRectList", + "Clipboard", + "ClipboardEvent", + "ClipboardItem", + "CloseEvent", + "Collator", + "CommandEvent", + "Comment", + "CompileError", + "CompositionEvent", + "CompressionStream", + "Console", + "ConstantSourceNode", + "ContentVisibilityAutoStateChangeEvent", + "Controllers", + "ConvolverNode", + "CookieChangeEvent", + "CookieStore", + "CookieStoreManager", + "CountQueuingStrategy", + "Counter", + "Credential", + "CredentialsContainer", + "CropTarget", + "Crypto", + "CryptoKey", + "CustomElementRegistry", + "CustomEvent", + "CustomStateSet", + "DATABASE_ERR", + "DATA_CLONE_ERR", + "DATA_ERR", + "DBLCLICK", + "DECR", + "DECR_WRAP", + "DELETE_STATUS", + "DEPTH", + "DEPTH24_STENCIL8", + "DEPTH32F_STENCIL8", + "DEPTH_ATTACHMENT", + "DEPTH_BITS", + "DEPTH_BUFFER_BIT", + "DEPTH_CLEAR_VALUE", + "DEPTH_COMPONENT", + "DEPTH_COMPONENT16", + "DEPTH_COMPONENT24", + "DEPTH_COMPONENT32F", + "DEPTH_FUNC", + "DEPTH_RANGE", + "DEPTH_STENCIL", + "DEPTH_STENCIL_ATTACHMENT", + "DEPTH_TEST", + "DEPTH_WRITEMASK", + "DEVICE_INELIGIBLE", + "DIRECTION_DOWN", + "DIRECTION_LEFT", + "DIRECTION_RIGHT", + "DIRECTION_UP", + "DISABLED", + "DISPATCH_REQUEST_ERR", + "DITHER", + "DOCUMENT_FRAGMENT_NODE", + "DOCUMENT_NODE", + "DOCUMENT_POSITION_CONTAINED_BY", + "DOCUMENT_POSITION_CONTAINS", + "DOCUMENT_POSITION_DISCONNECTED", + "DOCUMENT_POSITION_FOLLOWING", + "DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC", + "DOCUMENT_POSITION_PRECEDING", + "DOCUMENT_TYPE_NODE", + "DOMCursor", + "DOMError", + "DOMException", + "DOMImplementation", + "DOMImplementationLS", + "DOMMatrix", + "DOMMatrixReadOnly", + "DOMParser", + "DOMPoint", + "DOMPointReadOnly", + "DOMQuad", + "DOMRect", + "DOMRectList", + "DOMRectReadOnly", + "DOMRequest", + "DOMSTRING_SIZE_ERR", + "DOMSettableTokenList", + "DOMStringList", + "DOMStringMap", + "DOMTokenList", + "DOMTransactionEvent", + "DOM_DELTA_LINE", + "DOM_DELTA_PAGE", + "DOM_DELTA_PIXEL", + "DOM_INPUT_METHOD_DROP", + "DOM_INPUT_METHOD_HANDWRITING", + "DOM_INPUT_METHOD_IME", + "DOM_INPUT_METHOD_KEYBOARD", + "DOM_INPUT_METHOD_MULTIMODAL", + "DOM_INPUT_METHOD_OPTION", + "DOM_INPUT_METHOD_PASTE", + "DOM_INPUT_METHOD_SCRIPT", + "DOM_INPUT_METHOD_UNKNOWN", + "DOM_INPUT_METHOD_VOICE", + "DOM_KEY_LOCATION_JOYSTICK", + "DOM_KEY_LOCATION_LEFT", + "DOM_KEY_LOCATION_MOBILE", + "DOM_KEY_LOCATION_NUMPAD", + "DOM_KEY_LOCATION_RIGHT", + "DOM_KEY_LOCATION_STANDARD", + "DOM_VK_0", + "DOM_VK_1", + "DOM_VK_2", + "DOM_VK_3", + "DOM_VK_4", + "DOM_VK_5", + "DOM_VK_6", + "DOM_VK_7", + "DOM_VK_8", + "DOM_VK_9", + "DOM_VK_A", + "DOM_VK_ACCEPT", + "DOM_VK_ADD", + "DOM_VK_ALT", + "DOM_VK_ALTGR", + "DOM_VK_AMPERSAND", + "DOM_VK_ASTERISK", + "DOM_VK_AT", + "DOM_VK_ATTN", + "DOM_VK_B", + "DOM_VK_BACKSPACE", + "DOM_VK_BACK_QUOTE", + "DOM_VK_BACK_SLASH", + "DOM_VK_BACK_SPACE", + "DOM_VK_C", + "DOM_VK_CANCEL", + "DOM_VK_CAPS_LOCK", + "DOM_VK_CIRCUMFLEX", + "DOM_VK_CLEAR", + "DOM_VK_CLOSE_BRACKET", + "DOM_VK_CLOSE_CURLY_BRACKET", + "DOM_VK_CLOSE_PAREN", + "DOM_VK_COLON", + "DOM_VK_COMMA", + "DOM_VK_CONTEXT_MENU", + "DOM_VK_CONTROL", + "DOM_VK_CONVERT", + "DOM_VK_CRSEL", + "DOM_VK_CTRL", + "DOM_VK_D", + "DOM_VK_DECIMAL", + "DOM_VK_DELETE", + "DOM_VK_DIVIDE", + "DOM_VK_DOLLAR", + "DOM_VK_DOUBLE_QUOTE", + "DOM_VK_DOWN", + "DOM_VK_E", + "DOM_VK_EISU", + "DOM_VK_END", + "DOM_VK_ENTER", + "DOM_VK_EQUALS", + "DOM_VK_EREOF", + "DOM_VK_ESCAPE", + "DOM_VK_EXCLAMATION", + "DOM_VK_EXECUTE", + "DOM_VK_EXSEL", + "DOM_VK_F", + "DOM_VK_F1", + "DOM_VK_F10", + "DOM_VK_F11", + "DOM_VK_F12", + "DOM_VK_F13", + "DOM_VK_F14", + "DOM_VK_F15", + "DOM_VK_F16", + "DOM_VK_F17", + "DOM_VK_F18", + "DOM_VK_F19", + "DOM_VK_F2", + "DOM_VK_F20", + "DOM_VK_F21", + "DOM_VK_F22", + "DOM_VK_F23", + "DOM_VK_F24", + "DOM_VK_F25", + "DOM_VK_F26", + "DOM_VK_F27", + "DOM_VK_F28", + "DOM_VK_F29", + "DOM_VK_F3", + "DOM_VK_F30", + "DOM_VK_F31", + "DOM_VK_F32", + "DOM_VK_F33", + "DOM_VK_F34", + "DOM_VK_F35", + "DOM_VK_F36", + "DOM_VK_F4", + "DOM_VK_F5", + "DOM_VK_F6", + "DOM_VK_F7", + "DOM_VK_F8", + "DOM_VK_F9", + "DOM_VK_FINAL", + "DOM_VK_FRONT", + "DOM_VK_G", + "DOM_VK_GREATER_THAN", + "DOM_VK_H", + "DOM_VK_HANGUL", + "DOM_VK_HANJA", + "DOM_VK_HASH", + "DOM_VK_HELP", + "DOM_VK_HK_TOGGLE", + "DOM_VK_HOME", + "DOM_VK_HYPHEN_MINUS", + "DOM_VK_I", + "DOM_VK_INSERT", + "DOM_VK_J", + "DOM_VK_JUNJA", + "DOM_VK_K", + "DOM_VK_KANA", + "DOM_VK_KANJI", + "DOM_VK_L", + "DOM_VK_LEFT", + "DOM_VK_LEFT_TAB", + "DOM_VK_LESS_THAN", + "DOM_VK_M", + "DOM_VK_META", + "DOM_VK_MODECHANGE", + "DOM_VK_MULTIPLY", + "DOM_VK_N", + "DOM_VK_NONCONVERT", + "DOM_VK_NUMPAD0", + "DOM_VK_NUMPAD1", + "DOM_VK_NUMPAD2", + "DOM_VK_NUMPAD3", + "DOM_VK_NUMPAD4", + "DOM_VK_NUMPAD5", + "DOM_VK_NUMPAD6", + "DOM_VK_NUMPAD7", + "DOM_VK_NUMPAD8", + "DOM_VK_NUMPAD9", + "DOM_VK_NUM_LOCK", + "DOM_VK_O", + "DOM_VK_OEM_1", + "DOM_VK_OEM_102", + "DOM_VK_OEM_2", + "DOM_VK_OEM_3", + "DOM_VK_OEM_4", + "DOM_VK_OEM_5", + "DOM_VK_OEM_6", + "DOM_VK_OEM_7", + "DOM_VK_OEM_8", + "DOM_VK_OEM_COMMA", + "DOM_VK_OEM_MINUS", + "DOM_VK_OEM_PERIOD", + "DOM_VK_OEM_PLUS", + "DOM_VK_OPEN_BRACKET", + "DOM_VK_OPEN_CURLY_BRACKET", + "DOM_VK_OPEN_PAREN", + "DOM_VK_P", + "DOM_VK_PA1", + "DOM_VK_PAGEDOWN", + "DOM_VK_PAGEUP", + "DOM_VK_PAGE_DOWN", + "DOM_VK_PAGE_UP", + "DOM_VK_PAUSE", + "DOM_VK_PERCENT", + "DOM_VK_PERIOD", + "DOM_VK_PIPE", + "DOM_VK_PLAY", + "DOM_VK_PLUS", + "DOM_VK_PRINT", + "DOM_VK_PRINTSCREEN", + "DOM_VK_PROCESSKEY", + "DOM_VK_PROPERITES", + "DOM_VK_Q", + "DOM_VK_QUESTION_MARK", + "DOM_VK_QUOTE", + "DOM_VK_R", + "DOM_VK_REDO", + "DOM_VK_RETURN", + "DOM_VK_RIGHT", + "DOM_VK_S", + "DOM_VK_SCROLL_LOCK", + "DOM_VK_SELECT", + "DOM_VK_SEMICOLON", + "DOM_VK_SEPARATOR", + "DOM_VK_SHIFT", + "DOM_VK_SLASH", + "DOM_VK_SLEEP", + "DOM_VK_SPACE", + "DOM_VK_SUBTRACT", + "DOM_VK_T", + "DOM_VK_TAB", + "DOM_VK_TILDE", + "DOM_VK_U", + "DOM_VK_UNDERSCORE", + "DOM_VK_UNDO", + "DOM_VK_UNICODE", + "DOM_VK_UP", + "DOM_VK_V", + "DOM_VK_VOLUME_DOWN", + "DOM_VK_VOLUME_MUTE", + "DOM_VK_VOLUME_UP", + "DOM_VK_W", + "DOM_VK_WIN", + "DOM_VK_WINDOW", + "DOM_VK_WIN_ICO_00", + "DOM_VK_WIN_ICO_CLEAR", + "DOM_VK_WIN_ICO_HELP", + "DOM_VK_WIN_OEM_ATTN", + "DOM_VK_WIN_OEM_AUTO", + "DOM_VK_WIN_OEM_BACKTAB", + "DOM_VK_WIN_OEM_CLEAR", + "DOM_VK_WIN_OEM_COPY", + "DOM_VK_WIN_OEM_CUSEL", + "DOM_VK_WIN_OEM_ENLW", + "DOM_VK_WIN_OEM_FINISH", + "DOM_VK_WIN_OEM_FJ_JISHO", + "DOM_VK_WIN_OEM_FJ_LOYA", + "DOM_VK_WIN_OEM_FJ_MASSHOU", + "DOM_VK_WIN_OEM_FJ_ROYA", + "DOM_VK_WIN_OEM_FJ_TOUROKU", + "DOM_VK_WIN_OEM_JUMP", + "DOM_VK_WIN_OEM_PA1", + "DOM_VK_WIN_OEM_PA2", + "DOM_VK_WIN_OEM_PA3", + "DOM_VK_WIN_OEM_RESET", + "DOM_VK_WIN_OEM_WSCTRL", + "DOM_VK_X", + "DOM_VK_XF86XK_ADD_FAVORITE", + "DOM_VK_XF86XK_APPLICATION_LEFT", + "DOM_VK_XF86XK_APPLICATION_RIGHT", + "DOM_VK_XF86XK_AUDIO_CYCLE_TRACK", + "DOM_VK_XF86XK_AUDIO_FORWARD", + "DOM_VK_XF86XK_AUDIO_LOWER_VOLUME", + "DOM_VK_XF86XK_AUDIO_MEDIA", + "DOM_VK_XF86XK_AUDIO_MUTE", + "DOM_VK_XF86XK_AUDIO_NEXT", + "DOM_VK_XF86XK_AUDIO_PAUSE", + "DOM_VK_XF86XK_AUDIO_PLAY", + "DOM_VK_XF86XK_AUDIO_PREV", + "DOM_VK_XF86XK_AUDIO_RAISE_VOLUME", + "DOM_VK_XF86XK_AUDIO_RANDOM_PLAY", + "DOM_VK_XF86XK_AUDIO_RECORD", + "DOM_VK_XF86XK_AUDIO_REPEAT", + "DOM_VK_XF86XK_AUDIO_REWIND", + "DOM_VK_XF86XK_AUDIO_STOP", + "DOM_VK_XF86XK_AWAY", + "DOM_VK_XF86XK_BACK", + "DOM_VK_XF86XK_BACK_FORWARD", + "DOM_VK_XF86XK_BATTERY", + "DOM_VK_XF86XK_BLUE", + "DOM_VK_XF86XK_BLUETOOTH", + "DOM_VK_XF86XK_BOOK", + "DOM_VK_XF86XK_BRIGHTNESS_ADJUST", + "DOM_VK_XF86XK_CALCULATOR", + "DOM_VK_XF86XK_CALENDAR", + "DOM_VK_XF86XK_CD", + "DOM_VK_XF86XK_CLOSE", + "DOM_VK_XF86XK_COMMUNITY", + "DOM_VK_XF86XK_CONTRAST_ADJUST", + "DOM_VK_XF86XK_COPY", + "DOM_VK_XF86XK_CUT", + "DOM_VK_XF86XK_CYCLE_ANGLE", + "DOM_VK_XF86XK_DISPLAY", + "DOM_VK_XF86XK_DOCUMENTS", + "DOM_VK_XF86XK_DOS", + "DOM_VK_XF86XK_EJECT", + "DOM_VK_XF86XK_EXCEL", + "DOM_VK_XF86XK_EXPLORER", + "DOM_VK_XF86XK_FAVORITES", + "DOM_VK_XF86XK_FINANCE", + "DOM_VK_XF86XK_FORWARD", + "DOM_VK_XF86XK_FRAME_BACK", + "DOM_VK_XF86XK_FRAME_FORWARD", + "DOM_VK_XF86XK_GAME", + "DOM_VK_XF86XK_GO", + "DOM_VK_XF86XK_GREEN", + "DOM_VK_XF86XK_HIBERNATE", + "DOM_VK_XF86XK_HISTORY", + "DOM_VK_XF86XK_HOME_PAGE", + "DOM_VK_XF86XK_HOT_LINKS", + "DOM_VK_XF86XK_I_TOUCH", + "DOM_VK_XF86XK_KBD_BRIGHTNESS_DOWN", + "DOM_VK_XF86XK_KBD_BRIGHTNESS_UP", + "DOM_VK_XF86XK_KBD_LIGHT_ON_OFF", + "DOM_VK_XF86XK_LAUNCH0", + "DOM_VK_XF86XK_LAUNCH1", + "DOM_VK_XF86XK_LAUNCH2", + "DOM_VK_XF86XK_LAUNCH3", + "DOM_VK_XF86XK_LAUNCH4", + "DOM_VK_XF86XK_LAUNCH5", + "DOM_VK_XF86XK_LAUNCH6", + "DOM_VK_XF86XK_LAUNCH7", + "DOM_VK_XF86XK_LAUNCH8", + "DOM_VK_XF86XK_LAUNCH9", + "DOM_VK_XF86XK_LAUNCH_A", + "DOM_VK_XF86XK_LAUNCH_B", + "DOM_VK_XF86XK_LAUNCH_C", + "DOM_VK_XF86XK_LAUNCH_D", + "DOM_VK_XF86XK_LAUNCH_E", + "DOM_VK_XF86XK_LAUNCH_F", + "DOM_VK_XF86XK_LIGHT_BULB", + "DOM_VK_XF86XK_LOG_OFF", + "DOM_VK_XF86XK_MAIL", + "DOM_VK_XF86XK_MAIL_FORWARD", + "DOM_VK_XF86XK_MARKET", + "DOM_VK_XF86XK_MEETING", + "DOM_VK_XF86XK_MEMO", + "DOM_VK_XF86XK_MENU_KB", + "DOM_VK_XF86XK_MENU_PB", + "DOM_VK_XF86XK_MESSENGER", + "DOM_VK_XF86XK_MON_BRIGHTNESS_DOWN", + "DOM_VK_XF86XK_MON_BRIGHTNESS_UP", + "DOM_VK_XF86XK_MUSIC", + "DOM_VK_XF86XK_MY_COMPUTER", + "DOM_VK_XF86XK_MY_SITES", + "DOM_VK_XF86XK_NEW", + "DOM_VK_XF86XK_NEWS", + "DOM_VK_XF86XK_OFFICE_HOME", + "DOM_VK_XF86XK_OPEN", + "DOM_VK_XF86XK_OPEN_URL", + "DOM_VK_XF86XK_OPTION", + "DOM_VK_XF86XK_PASTE", + "DOM_VK_XF86XK_PHONE", + "DOM_VK_XF86XK_PICTURES", + "DOM_VK_XF86XK_POWER_DOWN", + "DOM_VK_XF86XK_POWER_OFF", + "DOM_VK_XF86XK_RED", + "DOM_VK_XF86XK_REFRESH", + "DOM_VK_XF86XK_RELOAD", + "DOM_VK_XF86XK_REPLY", + "DOM_VK_XF86XK_ROCKER_DOWN", + "DOM_VK_XF86XK_ROCKER_ENTER", + "DOM_VK_XF86XK_ROCKER_UP", + "DOM_VK_XF86XK_ROTATE_WINDOWS", + "DOM_VK_XF86XK_ROTATION_KB", + "DOM_VK_XF86XK_ROTATION_PB", + "DOM_VK_XF86XK_SAVE", + "DOM_VK_XF86XK_SCREEN_SAVER", + "DOM_VK_XF86XK_SCROLL_CLICK", + "DOM_VK_XF86XK_SCROLL_DOWN", + "DOM_VK_XF86XK_SCROLL_UP", + "DOM_VK_XF86XK_SEARCH", + "DOM_VK_XF86XK_SEND", + "DOM_VK_XF86XK_SHOP", + "DOM_VK_XF86XK_SPELL", + "DOM_VK_XF86XK_SPLIT_SCREEN", + "DOM_VK_XF86XK_STANDBY", + "DOM_VK_XF86XK_START", + "DOM_VK_XF86XK_STOP", + "DOM_VK_XF86XK_SUBTITLE", + "DOM_VK_XF86XK_SUPPORT", + "DOM_VK_XF86XK_SUSPEND", + "DOM_VK_XF86XK_TASK_PANE", + "DOM_VK_XF86XK_TERMINAL", + "DOM_VK_XF86XK_TIME", + "DOM_VK_XF86XK_TOOLS", + "DOM_VK_XF86XK_TOP_MENU", + "DOM_VK_XF86XK_TO_DO_LIST", + "DOM_VK_XF86XK_TRAVEL", + "DOM_VK_XF86XK_USER1KB", + "DOM_VK_XF86XK_USER2KB", + "DOM_VK_XF86XK_USER_PB", + "DOM_VK_XF86XK_UWB", + "DOM_VK_XF86XK_VENDOR_HOME", + "DOM_VK_XF86XK_VIDEO", + "DOM_VK_XF86XK_VIEW", + "DOM_VK_XF86XK_WAKE_UP", + "DOM_VK_XF86XK_WEB_CAM", + "DOM_VK_XF86XK_WHEEL_BUTTON", + "DOM_VK_XF86XK_WLAN", + "DOM_VK_XF86XK_WORD", + "DOM_VK_XF86XK_WWW", + "DOM_VK_XF86XK_XFER", + "DOM_VK_XF86XK_YELLOW", + "DOM_VK_XF86XK_ZOOM_IN", + "DOM_VK_XF86XK_ZOOM_OUT", + "DOM_VK_Y", + "DOM_VK_Z", + "DOM_VK_ZOOM", + "DONE", + "DONT_CARE", + "DOWNLOADING", + "DRAGDROP", + "DRAW_BUFFER0", + "DRAW_BUFFER1", + "DRAW_BUFFER10", + "DRAW_BUFFER11", + "DRAW_BUFFER12", + "DRAW_BUFFER13", + "DRAW_BUFFER14", + "DRAW_BUFFER15", + "DRAW_BUFFER2", + "DRAW_BUFFER3", + "DRAW_BUFFER4", + "DRAW_BUFFER5", + "DRAW_BUFFER6", + "DRAW_BUFFER7", + "DRAW_BUFFER8", + "DRAW_BUFFER9", + "DRAW_FRAMEBUFFER", + "DRAW_FRAMEBUFFER_BINDING", + "DST_ALPHA", + "DST_COLOR", + "DYNAMIC_COPY", + "DYNAMIC_DRAW", + "DYNAMIC_READ", + "DataChannel", + "DataTransfer", + "DataTransferItem", + "DataTransferItemList", + "DataView", + "Date", + "DateTimeFormat", + "DecompressionStream", + "DelayNode", + "DelegatedInkTrailPresenter", + "DeprecationReportBody", + "DesktopNotification", + "DesktopNotificationCenter", + "DeviceLightEvent", + "DeviceMotionEvent", + "DeviceMotionEventAcceleration", + "DeviceMotionEventRotationRate", + "DeviceOrientationEvent", + "DeviceProximityEvent", + "DeviceStorage", + "DeviceStorageChangeEvent", + "Directory", + "DisplayNames", + "Document", + "DocumentFragment", + "DocumentPictureInPicture", + "DocumentPictureInPictureEvent", + "DocumentTimeline", + "DocumentType", + "DragEvent", + "DynamicsCompressorNode", + "E", + "ELEMENT_ARRAY_BUFFER", + "ELEMENT_ARRAY_BUFFER_BINDING", + "ELEMENT_NODE", + "EMPTY", + "ENCODING_ERR", + "ENDED", + "END_TO_END", + "END_TO_START", + "ENTITY_NODE", + "ENTITY_REFERENCE_NODE", + "EPSILON", + "EQUAL", + "EQUALPOWER", + "ERROR", + "EXPONENTIAL_DISTANCE", + "EditContext", + "Element", + "ElementInternals", + "ElementQuery", + "EncodedAudioChunk", + "EncodedVideoChunk", + "EnterPictureInPictureEvent", + "Entity", + "EntityReference", + "Error", + "ErrorEvent", + "EvalError", + "Event", + "EventCounts", + "EventException", + "EventSource", + "EventTarget", + "Exception", + "External", + "EyeDropper", + "FASTEST", + "FIDOSDK", + "FILTER_ACCEPT", + "FILTER_INTERRUPT", + "FILTER_REJECT", + "FILTER_SKIP", + "FINISHED_STATE", + "FIRST_ORDERED_NODE_TYPE", + "FLOAT", + "FLOAT_32_UNSIGNED_INT_24_8_REV", + "FLOAT_MAT2", + "FLOAT_MAT2x3", + "FLOAT_MAT2x4", + "FLOAT_MAT3", + "FLOAT_MAT3x2", + "FLOAT_MAT3x4", + "FLOAT_MAT4", + "FLOAT_MAT4x2", + "FLOAT_MAT4x3", + "FLOAT_VEC2", + "FLOAT_VEC3", + "FLOAT_VEC4", + "FOCUS", + "FONT_FACE_RULE", + "FONT_FEATURE_VALUES_RULE", + "FRAGMENT", + "FRAGMENT_SHADER", + "FRAGMENT_SHADER_DERIVATIVE_HINT", + "FRAGMENT_SHADER_DERIVATIVE_HINT_OES", + "FRAMEBUFFER", + "FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE", + "FRAMEBUFFER_ATTACHMENT_BLUE_SIZE", + "FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING", + "FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE", + "FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE", + "FRAMEBUFFER_ATTACHMENT_GREEN_SIZE", + "FRAMEBUFFER_ATTACHMENT_OBJECT_NAME", + "FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE", + "FRAMEBUFFER_ATTACHMENT_RED_SIZE", + "FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE", + "FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE", + "FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER", + "FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL", + "FRAMEBUFFER_BINDING", + "FRAMEBUFFER_COMPLETE", + "FRAMEBUFFER_DEFAULT", + "FRAMEBUFFER_INCOMPLETE_ATTACHMENT", + "FRAMEBUFFER_INCOMPLETE_DIMENSIONS", + "FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT", + "FRAMEBUFFER_INCOMPLETE_MULTISAMPLE", + "FRAMEBUFFER_UNSUPPORTED", + "FRONT", + "FRONT_AND_BACK", + "FRONT_FACE", + "FUNC_ADD", + "FUNC_REVERSE_SUBTRACT", + "FUNC_SUBTRACT", + "FeaturePolicy", + "FeaturePolicyViolationReportBody", + "FederatedCredential", + "Feed", + "FeedEntry", + "Fence", + "FencedFrameConfig", + "File", + "FileError", + "FileList", + "FileReader", + "FileSystem", + "FileSystemDirectoryEntry", + "FileSystemDirectoryHandle", + "FileSystemDirectoryReader", + "FileSystemEntry", + "FileSystemFileEntry", + "FileSystemFileHandle", + "FileSystemHandle", + "FileSystemWritableFileStream", + "FinalizationRegistry", + "FindInPage", + "Float32Array", + "Float64Array", + "FocusEvent", + "FontData", + "FontFace", + "FontFaceSet", + "FontFaceSetLoadEvent", + "FormData", + "FormDataEvent", + "FragmentDirective", + "Function", + "GENERATE_MIPMAP_HINT", + "GEQUAL", + "GPU", + "GPUAdapter", + "GPUAdapterInfo", + "GPUBindGroup", + "GPUBindGroupLayout", + "GPUBuffer", + "GPUBufferUsage", + "GPUCanvasContext", + "GPUColorWrite", + "GPUCommandBuffer", + "GPUCommandEncoder", + "GPUCompilationInfo", + "GPUCompilationMessage", + "GPUComputePassEncoder", + "GPUComputePipeline", + "GPUDevice", + "GPUDeviceLostInfo", + "GPUError", + "GPUExternalTexture", + "GPUInternalError", + "GPUMapMode", + "GPUOutOfMemoryError", + "GPUPipelineError", + "GPUPipelineLayout", + "GPUQuerySet", + "GPUQueue", + "GPURenderBundle", + "GPURenderBundleEncoder", + "GPURenderPassEncoder", + "GPURenderPipeline", + "GPUSampler", + "GPUShaderModule", + "GPUShaderStage", + "GPUSupportedFeatures", + "GPUSupportedLimits", + "GPUTexture", + "GPUTextureUsage", + "GPUTextureView", + "GPUUncapturedErrorEvent", + "GPUValidationError", + "GREATER", + "GREEN", + "GREEN_BITS", + "GainNode", + "Gamepad", + "GamepadAxisMoveEvent", + "GamepadButton", + "GamepadButtonEvent", + "GamepadEvent", + "GamepadHapticActuator", + "GamepadPose", + "Geolocation", + "GeolocationCoordinates", + "GeolocationPosition", + "GeolocationPositionError", + "GestureEvent", + "Global", + "GravitySensor", + "Gyroscope", + "HALF_FLOAT", + "HAVE_CURRENT_DATA", + "HAVE_ENOUGH_DATA", + "HAVE_FUTURE_DATA", + "HAVE_METADATA", + "HAVE_NOTHING", + "HEADERS_RECEIVED", + "HID", + "HIDConnectionEvent", + "HIDDEN", + "HIDDevice", + "HIDInputReportEvent", + "HIERARCHY_REQUEST_ERR", + "HIGHPASS", + "HIGHSHELF", + "HIGH_FLOAT", + "HIGH_INT", + "HORIZONTAL", + "HORIZONTAL_AXIS", + "HRTF", + "HTMLAllCollection", + "HTMLAnchorElement", + "HTMLAppletElement", + "HTMLAreaElement", + "HTMLAudioElement", + "HTMLBRElement", + "HTMLBaseElement", + "HTMLBaseFontElement", + "HTMLBlockquoteElement", + "HTMLBodyElement", + "HTMLButtonElement", + "HTMLCanvasElement", + "HTMLCollection", + "HTMLCommandElement", + "HTMLContentElement", + "HTMLDListElement", + "HTMLDataElement", + "HTMLDataListElement", + "HTMLDetailsElement", + "HTMLDialogElement", + "HTMLDirectoryElement", + "HTMLDivElement", + "HTMLDocument", + "HTMLElement", + "HTMLEmbedElement", + "HTMLFencedFrameElement", + "HTMLFieldSetElement", + "HTMLFontElement", + "HTMLFormControlsCollection", + "HTMLFormElement", + "HTMLFrameElement", + "HTMLFrameSetElement", + "HTMLHRElement", + "HTMLHeadElement", + "HTMLHeadingElement", + "HTMLHtmlElement", + "HTMLIFrameElement", + "HTMLImageElement", + "HTMLInputElement", + "HTMLIsIndexElement", + "HTMLKeygenElement", + "HTMLLIElement", + "HTMLLabelElement", + "HTMLLegendElement", + "HTMLLinkElement", + "HTMLMapElement", + "HTMLMarqueeElement", + "HTMLMediaElement", + "HTMLMenuElement", + "HTMLMenuItemElement", + "HTMLMetaElement", + "HTMLMeterElement", + "HTMLModElement", + "HTMLOListElement", + "HTMLObjectElement", + "HTMLOptGroupElement", + "HTMLOptionElement", + "HTMLOptionsCollection", + "HTMLOutputElement", + "HTMLParagraphElement", + "HTMLParamElement", + "HTMLPictureElement", + "HTMLPreElement", + "HTMLProgressElement", + "HTMLPropertiesCollection", + "HTMLQuoteElement", + "HTMLScriptElement", + "HTMLSelectElement", + "HTMLShadowElement", + "HTMLSlotElement", + "HTMLSourceElement", + "HTMLSpanElement", + "HTMLStyleElement", + "HTMLTableCaptionElement", + "HTMLTableCellElement", + "HTMLTableColElement", + "HTMLTableElement", + "HTMLTableRowElement", + "HTMLTableSectionElement", + "HTMLTemplateElement", + "HTMLTextAreaElement", + "HTMLTimeElement", + "HTMLTitleElement", + "HTMLTrackElement", + "HTMLUListElement", + "HTMLUnknownElement", + "HTMLVideoElement", + "HashChangeEvent", + "Headers", + "Highlight", + "HighlightRegistry", + "History", + "Hz", + "ICE_CHECKING", + "ICE_CLOSED", + "ICE_COMPLETED", + "ICE_CONNECTED", + "ICE_FAILED", + "ICE_GATHERING", + "ICE_WAITING", + "IDBCursor", + "IDBCursorWithValue", + "IDBDatabase", + "IDBDatabaseException", + "IDBFactory", + "IDBFileHandle", + "IDBFileRequest", + "IDBIndex", + "IDBKeyRange", + "IDBMutableFile", + "IDBObjectStore", + "IDBOpenDBRequest", + "IDBRequest", + "IDBTransaction", + "IDBVersionChangeEvent", + "IDLE", + "IIRFilterNode", + "IMPLEMENTATION_COLOR_READ_FORMAT", + "IMPLEMENTATION_COLOR_READ_TYPE", + "IMPORT_RULE", + "INCR", + "INCR_WRAP", + "INDEX", + "INDEX_SIZE_ERR", + "INDIRECT", + "INT", + "INTERLEAVED_ATTRIBS", + "INT_2_10_10_10_REV", + "INT_SAMPLER_2D", + "INT_SAMPLER_2D_ARRAY", + "INT_SAMPLER_3D", + "INT_SAMPLER_CUBE", + "INT_VEC2", + "INT_VEC3", + "INT_VEC4", + "INUSE_ATTRIBUTE_ERR", + "INVALID_ACCESS_ERR", + "INVALID_CHARACTER_ERR", + "INVALID_ENUM", + "INVALID_EXPRESSION_ERR", + "INVALID_FRAMEBUFFER_OPERATION", + "INVALID_INDEX", + "INVALID_MODIFICATION_ERR", + "INVALID_NODE_TYPE_ERR", + "INVALID_OPERATION", + "INVALID_STATE_ERR", + "INVALID_VALUE", + "INVERSE_DISTANCE", + "INVERT", + "IceCandidate", + "IdentityCredential", + "IdentityCredentialError", + "IdentityProvider", + "IdleDeadline", + "IdleDetector", + "Image", + "ImageBitmap", + "ImageBitmapRenderingContext", + "ImageCapture", + "ImageData", + "ImageDecoder", + "ImageTrack", + "ImageTrackList", + "Infinity", + "Ink", + "InputDeviceCapabilities", + "InputDeviceInfo", + "InputEvent", + "InputMethodContext", + "InstallTrigger", + "InstallTriggerImpl", + "Instance", + "Int16Array", + "Int32Array", + "Int8Array", + "Intent", + "InternalError", + "IntersectionObserver", + "IntersectionObserverEntry", + "Intl", + "IsSearchProviderInstalled", + "Iterator", + "JSON", + "JSTag", + "KEEP", + "KEYDOWN", + "KEYFRAMES_RULE", + "KEYFRAME_RULE", + "KEYPRESS", + "KEYUP", + "KeyEvent", + "Keyboard", + "KeyboardEvent", + "KeyboardLayoutMap", + "KeyframeEffect", + "LENGTHADJUST_SPACING", + "LENGTHADJUST_SPACINGANDGLYPHS", + "LENGTHADJUST_UNKNOWN", + "LEQUAL", + "LESS", + "LINEAR", + "LINEAR_DISTANCE", + "LINEAR_MIPMAP_LINEAR", + "LINEAR_MIPMAP_NEAREST", + "LINES", + "LINE_LOOP", + "LINE_STRIP", + "LINE_WIDTH", + "LINK_STATUS", + "LIVE", + "LN10", + "LN2", + "LOADED", + "LOADING", + "LOG10E", + "LOG2E", + "LOWPASS", + "LOWSHELF", + "LOW_FLOAT", + "LOW_INT", + "LSException", + "LSParserFilter", + "LUMINANCE", + "LUMINANCE_ALPHA", + "LargestContentfulPaint", + "LaunchParams", + "LaunchQueue", + "LayoutShift", + "LayoutShiftAttribution", + "LinearAccelerationSensor", + "LinkError", + "ListFormat", + "LocalMediaStream", + "Locale", + "Location", + "Lock", + "LockManager", + "MAP_READ", + "MAP_WRITE", + "MAX", + "MAX_3D_TEXTURE_SIZE", + "MAX_ARRAY_TEXTURE_LAYERS", + "MAX_CLIENT_WAIT_TIMEOUT_WEBGL", + "MAX_COLOR_ATTACHMENTS", + "MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS", + "MAX_COMBINED_TEXTURE_IMAGE_UNITS", + "MAX_COMBINED_UNIFORM_BLOCKS", + "MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS", + "MAX_CUBE_MAP_TEXTURE_SIZE", + "MAX_DRAW_BUFFERS", + "MAX_ELEMENTS_INDICES", + "MAX_ELEMENTS_VERTICES", + "MAX_ELEMENT_INDEX", + "MAX_FRAGMENT_INPUT_COMPONENTS", + "MAX_FRAGMENT_UNIFORM_BLOCKS", + "MAX_FRAGMENT_UNIFORM_COMPONENTS", + "MAX_FRAGMENT_UNIFORM_VECTORS", + "MAX_PROGRAM_TEXEL_OFFSET", + "MAX_RENDERBUFFER_SIZE", + "MAX_SAFE_INTEGER", + "MAX_SAMPLES", + "MAX_SERVER_WAIT_TIMEOUT", + "MAX_TEXTURE_IMAGE_UNITS", + "MAX_TEXTURE_LOD_BIAS", + "MAX_TEXTURE_MAX_ANISOTROPY_EXT", + "MAX_TEXTURE_SIZE", + "MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS", + "MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS", + "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS", + "MAX_UNIFORM_BLOCK_SIZE", + "MAX_UNIFORM_BUFFER_BINDINGS", + "MAX_VALUE", + "MAX_VARYING_COMPONENTS", + "MAX_VARYING_VECTORS", + "MAX_VERTEX_ATTRIBS", + "MAX_VERTEX_OUTPUT_COMPONENTS", + "MAX_VERTEX_TEXTURE_IMAGE_UNITS", + "MAX_VERTEX_UNIFORM_BLOCKS", + "MAX_VERTEX_UNIFORM_COMPONENTS", + "MAX_VERTEX_UNIFORM_VECTORS", + "MAX_VIEWPORT_DIMS", + "MEDIA_ERR_ABORTED", + "MEDIA_ERR_DECODE", + "MEDIA_ERR_ENCRYPTED", + "MEDIA_ERR_NETWORK", + "MEDIA_ERR_SRC_NOT_SUPPORTED", + "MEDIA_KEYERR_CLIENT", + "MEDIA_KEYERR_DOMAIN", + "MEDIA_KEYERR_HARDWARECHANGE", + "MEDIA_KEYERR_OUTPUT", + "MEDIA_KEYERR_SERVICE", + "MEDIA_KEYERR_UNKNOWN", + "MEDIA_RULE", + "MEDIUM_FLOAT", + "MEDIUM_INT", + "META_MASK", + "MIDIAccess", + "MIDIConnectionEvent", + "MIDIInput", + "MIDIInputMap", + "MIDIMessageEvent", + "MIDIOutput", + "MIDIOutputMap", + "MIDIPort", + "MIN", + "MIN_PROGRAM_TEXEL_OFFSET", + "MIN_SAFE_INTEGER", + "MIN_VALUE", + "MIRRORED_REPEAT", + "MODE_ASYNCHRONOUS", + "MODE_SYNCHRONOUS", + "MODIFICATION", + "MOUSEDOWN", + "MOUSEDRAG", + "MOUSEMOVE", + "MOUSEOUT", + "MOUSEOVER", + "MOUSEUP", + "MOZ_KEYFRAMES_RULE", + "MOZ_KEYFRAME_RULE", + "MOZ_SOURCE_CURSOR", + "MOZ_SOURCE_ERASER", + "MOZ_SOURCE_KEYBOARD", + "MOZ_SOURCE_MOUSE", + "MOZ_SOURCE_PEN", + "MOZ_SOURCE_TOUCH", + "MOZ_SOURCE_UNKNOWN", + "MSGESTURE_FLAG_BEGIN", + "MSGESTURE_FLAG_CANCEL", + "MSGESTURE_FLAG_END", + "MSGESTURE_FLAG_INERTIA", + "MSGESTURE_FLAG_NONE", + "MSPOINTER_TYPE_MOUSE", + "MSPOINTER_TYPE_PEN", + "MSPOINTER_TYPE_TOUCH", + "MS_ASYNC_CALLBACK_STATUS_ASSIGN_DELEGATE", + "MS_ASYNC_CALLBACK_STATUS_CANCEL", + "MS_ASYNC_CALLBACK_STATUS_CHOOSEANY", + "MS_ASYNC_CALLBACK_STATUS_ERROR", + "MS_ASYNC_CALLBACK_STATUS_JOIN", + "MS_ASYNC_OP_STATUS_CANCELED", + "MS_ASYNC_OP_STATUS_ERROR", + "MS_ASYNC_OP_STATUS_SUCCESS", + "MS_MANIPULATION_STATE_ACTIVE", + "MS_MANIPULATION_STATE_CANCELLED", + "MS_MANIPULATION_STATE_COMMITTED", + "MS_MANIPULATION_STATE_DRAGGING", + "MS_MANIPULATION_STATE_INERTIA", + "MS_MANIPULATION_STATE_PRESELECT", + "MS_MANIPULATION_STATE_SELECTING", + "MS_MANIPULATION_STATE_STOPPED", + "MS_MEDIA_ERR_ENCRYPTED", + "MS_MEDIA_KEYERR_CLIENT", + "MS_MEDIA_KEYERR_DOMAIN", + "MS_MEDIA_KEYERR_HARDWARECHANGE", + "MS_MEDIA_KEYERR_OUTPUT", + "MS_MEDIA_KEYERR_SERVICE", + "MS_MEDIA_KEYERR_UNKNOWN", + "Map", + "Math", + "MathMLElement", + "MediaCapabilities", + "MediaCapabilitiesInfo", + "MediaController", + "MediaDeviceInfo", + "MediaDevices", + "MediaElementAudioSourceNode", + "MediaEncryptedEvent", + "MediaError", + "MediaKeyError", + "MediaKeyEvent", + "MediaKeyMessageEvent", + "MediaKeyNeededEvent", + "MediaKeySession", + "MediaKeyStatusMap", + "MediaKeySystemAccess", + "MediaKeys", + "MediaList", + "MediaMetadata", + "MediaQueryList", + "MediaQueryListEvent", + "MediaRecorder", + "MediaRecorderErrorEvent", + "MediaSession", + "MediaSettingsRange", + "MediaSource", + "MediaSourceHandle", + "MediaStream", + "MediaStreamAudioDestinationNode", + "MediaStreamAudioSourceNode", + "MediaStreamEvent", + "MediaStreamTrack", + "MediaStreamTrackAudioSourceNode", + "MediaStreamTrackEvent", + "MediaStreamTrackGenerator", + "MediaStreamTrackProcessor", + "MediaStreamTrackVideoStats", + "Memory", + "MessageChannel", + "MessageEvent", + "MessagePort", + "Methods", + "MimeType", + "MimeTypeArray", + "Module", + "MouseEvent", + "MouseScrollEvent", + "MozAnimation", + "MozAnimationDelay", + "MozAnimationDirection", + "MozAnimationDuration", + "MozAnimationFillMode", + "MozAnimationIterationCount", + "MozAnimationName", + "MozAnimationPlayState", + "MozAnimationTimingFunction", + "MozAppearance", + "MozBackfaceVisibility", + "MozBinding", + "MozBorderBottomColors", + "MozBorderEnd", + "MozBorderEndColor", + "MozBorderEndStyle", + "MozBorderEndWidth", + "MozBorderImage", + "MozBorderLeftColors", + "MozBorderRightColors", + "MozBorderStart", + "MozBorderStartColor", + "MozBorderStartStyle", + "MozBorderStartWidth", + "MozBorderTopColors", + "MozBoxAlign", + "MozBoxDirection", + "MozBoxFlex", + "MozBoxOrdinalGroup", + "MozBoxOrient", + "MozBoxPack", + "MozBoxSizing", + "MozCSSKeyframeRule", + "MozCSSKeyframesRule", + "MozColumnCount", + "MozColumnFill", + "MozColumnGap", + "MozColumnRule", + "MozColumnRuleColor", + "MozColumnRuleStyle", + "MozColumnRuleWidth", + "MozColumnWidth", + "MozColumns", + "MozContactChangeEvent", + "MozFloatEdge", + "MozFontFeatureSettings", + "MozFontLanguageOverride", + "MozForceBrokenImageIcon", + "MozHyphens", + "MozImageRegion", + "MozMarginEnd", + "MozMarginStart", + "MozMmsEvent", + "MozMmsMessage", + "MozMobileMessageThread", + "MozOSXFontSmoothing", + "MozOrient", + "MozOsxFontSmoothing", + "MozOutlineRadius", + "MozOutlineRadiusBottomleft", + "MozOutlineRadiusBottomright", + "MozOutlineRadiusTopleft", + "MozOutlineRadiusTopright", + "MozPaddingEnd", + "MozPaddingStart", + "MozPerspective", + "MozPerspectiveOrigin", + "MozPowerManager", + "MozSettingsEvent", + "MozSmsEvent", + "MozSmsMessage", + "MozStackSizing", + "MozTabSize", + "MozTextAlignLast", + "MozTextDecorationColor", + "MozTextDecorationLine", + "MozTextDecorationStyle", + "MozTextSizeAdjust", + "MozTransform", + "MozTransformOrigin", + "MozTransformStyle", + "MozTransition", + "MozTransitionDelay", + "MozTransitionDuration", + "MozTransitionProperty", + "MozTransitionTimingFunction", + "MozUserFocus", + "MozUserInput", + "MozUserModify", + "MozUserSelect", + "MozWindowDragging", + "MozWindowShadow", + "MutationEvent", + "MutationObserver", + "MutationRecord", + "NAMESPACE_ERR", + "NAMESPACE_RULE", + "NEAREST", + "NEAREST_MIPMAP_LINEAR", + "NEAREST_MIPMAP_NEAREST", + "NEGATIVE_INFINITY", + "NETWORK_EMPTY", + "NETWORK_ERR", + "NETWORK_IDLE", + "NETWORK_LOADED", + "NETWORK_LOADING", + "NETWORK_NO_SOURCE", + "NEVER", + "NEW", + "NEXT", + "NEXT_NO_DUPLICATE", + "NICEST", + "NODE_AFTER", + "NODE_BEFORE", + "NODE_BEFORE_AND_AFTER", + "NODE_INSIDE", + "NONE", + "NON_TRANSIENT_ERR", + "NOTATION_NODE", + "NOTCH", + "NOTEQUAL", + "NOT_ALLOWED_ERR", + "NOT_FOUND_ERR", + "NOT_READABLE_ERR", + "NOT_SUPPORTED_ERR", + "NO_DATA_ALLOWED_ERR", + "NO_ERR", + "NO_ERROR", + "NO_MODIFICATION_ALLOWED_ERR", + "NUMBER_TYPE", + "NUM_COMPRESSED_TEXTURE_FORMATS", + "NaN", + "NamedNodeMap", + "NavigateEvent", + "Navigation", + "NavigationActivation", + "NavigationCurrentEntryChangeEvent", + "NavigationDestination", + "NavigationHistoryEntry", + "NavigationPreloadManager", + "NavigationTransition", + "Navigator", + "NavigatorLogin", + "NavigatorManagedData", + "NavigatorUAData", + "NearbyLinks", + "NetworkInformation", + "Node", + "NodeFilter", + "NodeIterator", + "NodeList", + "NotRestoredReasonDetails", + "NotRestoredReasons", + "Notation", + "Notification", + "NotifyPaintEvent", + "Number", + "NumberFormat", + "OBJECT_TYPE", + "OBSOLETE", + "OK", + "ONE", + "ONE_MINUS_CONSTANT_ALPHA", + "ONE_MINUS_CONSTANT_COLOR", + "ONE_MINUS_DST_ALPHA", + "ONE_MINUS_DST_COLOR", + "ONE_MINUS_SRC_ALPHA", + "ONE_MINUS_SRC_COLOR", + "OPEN", + "OPENED", + "OPENING", + "ORDERED_NODE_ITERATOR_TYPE", + "ORDERED_NODE_SNAPSHOT_TYPE", + "OTHER_ERROR", + "OTPCredential", + "OUT_OF_MEMORY", + "Object", + "OfflineAudioCompletionEvent", + "OfflineAudioContext", + "OfflineResourceList", + "OffscreenCanvas", + "OffscreenCanvasRenderingContext2D", + "Option", + "OrientationSensor", + "OscillatorNode", + "OverconstrainedError", + "OverflowEvent", + "PACK_ALIGNMENT", + "PACK_ROW_LENGTH", + "PACK_SKIP_PIXELS", + "PACK_SKIP_ROWS", + "PAGE_RULE", + "PARSE_ERR", + "PATHSEG_ARC_ABS", + "PATHSEG_ARC_REL", + "PATHSEG_CLOSEPATH", + "PATHSEG_CURVETO_CUBIC_ABS", + "PATHSEG_CURVETO_CUBIC_REL", + "PATHSEG_CURVETO_CUBIC_SMOOTH_ABS", + "PATHSEG_CURVETO_CUBIC_SMOOTH_REL", + "PATHSEG_CURVETO_QUADRATIC_ABS", + "PATHSEG_CURVETO_QUADRATIC_REL", + "PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS", + "PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL", + "PATHSEG_LINETO_ABS", + "PATHSEG_LINETO_HORIZONTAL_ABS", + "PATHSEG_LINETO_HORIZONTAL_REL", + "PATHSEG_LINETO_REL", + "PATHSEG_LINETO_VERTICAL_ABS", + "PATHSEG_LINETO_VERTICAL_REL", + "PATHSEG_MOVETO_ABS", + "PATHSEG_MOVETO_REL", + "PATHSEG_UNKNOWN", + "PATH_EXISTS_ERR", + "PEAKING", + "PERMISSION_DENIED", + "PERSISTENT", + "PI", + "PIXEL_PACK_BUFFER", + "PIXEL_PACK_BUFFER_BINDING", + "PIXEL_UNPACK_BUFFER", + "PIXEL_UNPACK_BUFFER_BINDING", + "PLAYING_STATE", + "POINTS", + "POLYGON_OFFSET_FACTOR", + "POLYGON_OFFSET_FILL", + "POLYGON_OFFSET_UNITS", + "POSITION_UNAVAILABLE", + "POSITIVE_INFINITY", + "PREV", + "PREV_NO_DUPLICATE", + "PROCESSING_INSTRUCTION_NODE", + "PageChangeEvent", + "PageRevealEvent", + "PageSwapEvent", + "PageTransitionEvent", + "PaintRequest", + "PaintRequestList", + "PannerNode", + "PasswordCredential", + "Path2D", + "PaymentAddress", + "PaymentInstruments", + "PaymentManager", + "PaymentMethodChangeEvent", + "PaymentRequest", + "PaymentRequestUpdateEvent", + "PaymentResponse", + "Performance", + "PerformanceElementTiming", + "PerformanceEntry", + "PerformanceEventTiming", + "PerformanceLongAnimationFrameTiming", + "PerformanceLongTaskTiming", + "PerformanceMark", + "PerformanceMeasure", + "PerformanceNavigation", + "PerformanceNavigationTiming", + "PerformanceObserver", + "PerformanceObserverEntryList", + "PerformancePaintTiming", + "PerformanceResourceTiming", + "PerformanceScriptTiming", + "PerformanceServerTiming", + "PerformanceTiming", + "PeriodicSyncManager", + "PeriodicWave", + "PermissionStatus", + "Permissions", + "PhotoCapabilities", + "PictureInPictureEvent", + "PictureInPictureWindow", + "Plugin", + "PluginArray", + "PluralRules", + "PointerEvent", + "PopStateEvent", + "PopupBlockedEvent", + "Presentation", + "PresentationAvailability", + "PresentationConnection", + "PresentationConnectionAvailableEvent", + "PresentationConnectionCloseEvent", + "PresentationConnectionList", + "PresentationReceiver", + "PresentationRequest", + "ProcessingInstruction", + "Profiler", + "ProgressEvent", + "Promise", + "PromiseRejectionEvent", + "PropertyNodeList", + "Proxy", + "PublicKeyCredential", + "PushManager", + "PushSubscription", + "PushSubscriptionOptions", + "Q", + "QUERY_RESOLVE", + "QUERY_RESULT", + "QUERY_RESULT_AVAILABLE", + "QUOTA_ERR", + "QUOTA_EXCEEDED_ERR", + "QueryInterface", + "R11F_G11F_B10F", + "R16F", + "R16I", + "R16UI", + "R32F", + "R32I", + "R32UI", + "R8", + "R8I", + "R8UI", + "R8_SNORM", + "RASTERIZER_DISCARD", + "READ", + "READ_BUFFER", + "READ_FRAMEBUFFER", + "READ_FRAMEBUFFER_BINDING", + "READ_ONLY", + "READ_ONLY_ERR", + "READ_WRITE", + "RED", + "RED_BITS", + "RED_INTEGER", + "REMOVAL", + "RENDERBUFFER", + "RENDERBUFFER_ALPHA_SIZE", + "RENDERBUFFER_BINDING", + "RENDERBUFFER_BLUE_SIZE", + "RENDERBUFFER_DEPTH_SIZE", + "RENDERBUFFER_GREEN_SIZE", + "RENDERBUFFER_HEIGHT", + "RENDERBUFFER_INTERNAL_FORMAT", + "RENDERBUFFER_RED_SIZE", + "RENDERBUFFER_SAMPLES", + "RENDERBUFFER_STENCIL_SIZE", + "RENDERBUFFER_WIDTH", + "RENDERER", + "RENDERING_INTENT_ABSOLUTE_COLORIMETRIC", + "RENDERING_INTENT_AUTO", + "RENDERING_INTENT_PERCEPTUAL", + "RENDERING_INTENT_RELATIVE_COLORIMETRIC", + "RENDERING_INTENT_SATURATION", + "RENDERING_INTENT_UNKNOWN", + "RENDER_ATTACHMENT", + "REPEAT", + "REPLACE", + "RG", + "RG16F", + "RG16I", + "RG16UI", + "RG32F", + "RG32I", + "RG32UI", + "RG8", + "RG8I", + "RG8UI", + "RG8_SNORM", + "RGB", + "RGB10_A2", + "RGB10_A2UI", + "RGB16F", + "RGB16I", + "RGB16UI", + "RGB32F", + "RGB32I", + "RGB32UI", + "RGB565", + "RGB5_A1", + "RGB8", + "RGB8I", + "RGB8UI", + "RGB8_SNORM", + "RGB9_E5", + "RGBA", + "RGBA16F", + "RGBA16I", + "RGBA16UI", + "RGBA32F", + "RGBA32I", + "RGBA32UI", + "RGBA4", + "RGBA8", + "RGBA8I", + "RGBA8UI", + "RGBA8_SNORM", + "RGBA_INTEGER", + "RGBColor", + "RGB_INTEGER", + "RG_INTEGER", + "ROTATION_CLOCKWISE", + "ROTATION_COUNTERCLOCKWISE", + "RTCCertificate", + "RTCDTMFSender", + "RTCDTMFToneChangeEvent", + "RTCDataChannel", + "RTCDataChannelEvent", + "RTCDtlsTransport", + "RTCEncodedAudioFrame", + "RTCEncodedVideoFrame", + "RTCError", + "RTCErrorEvent", + "RTCIceCandidate", + "RTCIceTransport", + "RTCPeerConnection", + "RTCPeerConnectionIceErrorEvent", + "RTCPeerConnectionIceEvent", + "RTCRtpReceiver", + "RTCRtpScriptTransform", + "RTCRtpSender", + "RTCRtpTransceiver", + "RTCSctpTransport", + "RTCSessionDescription", + "RTCStatsReport", + "RTCTrackEvent", + "RadioNodeList", + "Range", + "RangeError", + "RangeException", + "ReadableByteStreamController", + "ReadableStream", + "ReadableStreamBYOBReader", + "ReadableStreamBYOBRequest", + "ReadableStreamDefaultController", + "ReadableStreamDefaultReader", + "RecordErrorEvent", + "Rect", + "ReferenceError", + "Reflect", + "RegExp", + "RelativeOrientationSensor", + "RelativeTimeFormat", + "RemotePlayback", + "Report", + "ReportBody", + "ReportingObserver", + "Request", + "ResizeObserver", + "ResizeObserverEntry", + "ResizeObserverSize", + "Response", + "RuntimeError", + "SAMPLER_2D", + "SAMPLER_2D_ARRAY", + "SAMPLER_2D_ARRAY_SHADOW", + "SAMPLER_2D_SHADOW", + "SAMPLER_3D", + "SAMPLER_BINDING", + "SAMPLER_CUBE", + "SAMPLER_CUBE_SHADOW", + "SAMPLES", + "SAMPLE_ALPHA_TO_COVERAGE", + "SAMPLE_BUFFERS", + "SAMPLE_COVERAGE", + "SAMPLE_COVERAGE_INVERT", + "SAMPLE_COVERAGE_VALUE", + "SAWTOOTH", + "SCHEDULED_STATE", + "SCISSOR_BOX", + "SCISSOR_TEST", + "SCROLL_PAGE_DOWN", + "SCROLL_PAGE_UP", + "SDP_ANSWER", + "SDP_OFFER", + "SDP_PRANSWER", + "SECURITY_ERR", + "SELECT", + "SEPARATE_ATTRIBS", + "SERIALIZE_ERR", + "SEVERITY_ERROR", + "SEVERITY_FATAL_ERROR", + "SEVERITY_WARNING", + "SHADER_COMPILER", + "SHADER_TYPE", + "SHADING_LANGUAGE_VERSION", + "SHIFT_MASK", + "SHORT", + "SHOWING", + "SHOW_ALL", + "SHOW_ATTRIBUTE", + "SHOW_CDATA_SECTION", + "SHOW_COMMENT", + "SHOW_DOCUMENT", + "SHOW_DOCUMENT_FRAGMENT", + "SHOW_DOCUMENT_TYPE", + "SHOW_ELEMENT", + "SHOW_ENTITY", + "SHOW_ENTITY_REFERENCE", + "SHOW_NOTATION", + "SHOW_PROCESSING_INSTRUCTION", + "SHOW_TEXT", + "SIGNALED", + "SIGNED_NORMALIZED", + "SINE", + "SOUNDFIELD", + "SQLException", + "SQRT1_2", + "SQRT2", + "SQUARE", + "SRC_ALPHA", + "SRC_ALPHA_SATURATE", + "SRC_COLOR", + "SRGB", + "SRGB8", + "SRGB8_ALPHA8", + "START_TO_END", + "START_TO_START", + "STATIC_COPY", + "STATIC_DRAW", + "STATIC_READ", + "STENCIL", + "STENCIL_ATTACHMENT", + "STENCIL_BACK_FAIL", + "STENCIL_BACK_FUNC", + "STENCIL_BACK_PASS_DEPTH_FAIL", + "STENCIL_BACK_PASS_DEPTH_PASS", + "STENCIL_BACK_REF", + "STENCIL_BACK_VALUE_MASK", + "STENCIL_BACK_WRITEMASK", + "STENCIL_BITS", + "STENCIL_BUFFER_BIT", + "STENCIL_CLEAR_VALUE", + "STENCIL_FAIL", + "STENCIL_FUNC", + "STENCIL_INDEX", + "STENCIL_INDEX8", + "STENCIL_PASS_DEPTH_FAIL", + "STENCIL_PASS_DEPTH_PASS", + "STENCIL_REF", + "STENCIL_TEST", + "STENCIL_VALUE_MASK", + "STENCIL_WRITEMASK", + "STORAGE", + "STORAGE_BINDING", + "STREAM_COPY", + "STREAM_DRAW", + "STREAM_READ", + "STRING_TYPE", + "STYLE_RULE", + "SUBPIXEL_BITS", + "SUPPORTS_RULE", + "SVGAElement", + "SVGAltGlyphDefElement", + "SVGAltGlyphElement", + "SVGAltGlyphItemElement", + "SVGAngle", + "SVGAnimateColorElement", + "SVGAnimateElement", + "SVGAnimateMotionElement", + "SVGAnimateTransformElement", + "SVGAnimatedAngle", + "SVGAnimatedBoolean", + "SVGAnimatedEnumeration", + "SVGAnimatedInteger", + "SVGAnimatedLength", + "SVGAnimatedLengthList", + "SVGAnimatedNumber", + "SVGAnimatedNumberList", + "SVGAnimatedPreserveAspectRatio", + "SVGAnimatedRect", + "SVGAnimatedString", + "SVGAnimatedTransformList", + "SVGAnimationElement", + "SVGCircleElement", + "SVGClipPathElement", + "SVGColor", + "SVGComponentTransferFunctionElement", + "SVGCursorElement", + "SVGDefsElement", + "SVGDescElement", + "SVGDiscardElement", + "SVGDocument", + "SVGElement", + "SVGElementInstance", + "SVGElementInstanceList", + "SVGEllipseElement", + "SVGException", + "SVGFEBlendElement", + "SVGFEColorMatrixElement", + "SVGFEComponentTransferElement", + "SVGFECompositeElement", + "SVGFEConvolveMatrixElement", + "SVGFEDiffuseLightingElement", + "SVGFEDisplacementMapElement", + "SVGFEDistantLightElement", + "SVGFEDropShadowElement", + "SVGFEFloodElement", + "SVGFEFuncAElement", + "SVGFEFuncBElement", + "SVGFEFuncGElement", + "SVGFEFuncRElement", + "SVGFEGaussianBlurElement", + "SVGFEImageElement", + "SVGFEMergeElement", + "SVGFEMergeNodeElement", + "SVGFEMorphologyElement", + "SVGFEOffsetElement", + "SVGFEPointLightElement", + "SVGFESpecularLightingElement", + "SVGFESpotLightElement", + "SVGFETileElement", + "SVGFETurbulenceElement", + "SVGFilterElement", + "SVGFontElement", + "SVGFontFaceElement", + "SVGFontFaceFormatElement", + "SVGFontFaceNameElement", + "SVGFontFaceSrcElement", + "SVGFontFaceUriElement", + "SVGForeignObjectElement", + "SVGGElement", + "SVGGeometryElement", + "SVGGlyphElement", + "SVGGlyphRefElement", + "SVGGradientElement", + "SVGGraphicsElement", + "SVGHKernElement", + "SVGImageElement", + "SVGLength", + "SVGLengthList", + "SVGLineElement", + "SVGLinearGradientElement", + "SVGMPathElement", + "SVGMarkerElement", + "SVGMaskElement", + "SVGMatrix", + "SVGMetadataElement", + "SVGMissingGlyphElement", + "SVGNumber", + "SVGNumberList", + "SVGPaint", + "SVGPathElement", + "SVGPathSeg", + "SVGPathSegArcAbs", + "SVGPathSegArcRel", + "SVGPathSegClosePath", + "SVGPathSegCurvetoCubicAbs", + "SVGPathSegCurvetoCubicRel", + "SVGPathSegCurvetoCubicSmoothAbs", + "SVGPathSegCurvetoCubicSmoothRel", + "SVGPathSegCurvetoQuadraticAbs", + "SVGPathSegCurvetoQuadraticRel", + "SVGPathSegCurvetoQuadraticSmoothAbs", + "SVGPathSegCurvetoQuadraticSmoothRel", + "SVGPathSegLinetoAbs", + "SVGPathSegLinetoHorizontalAbs", + "SVGPathSegLinetoHorizontalRel", + "SVGPathSegLinetoRel", + "SVGPathSegLinetoVerticalAbs", + "SVGPathSegLinetoVerticalRel", + "SVGPathSegList", + "SVGPathSegMovetoAbs", + "SVGPathSegMovetoRel", + "SVGPatternElement", + "SVGPoint", + "SVGPointList", + "SVGPolygonElement", + "SVGPolylineElement", + "SVGPreserveAspectRatio", + "SVGRadialGradientElement", + "SVGRect", + "SVGRectElement", + "SVGRenderingIntent", + "SVGSVGElement", + "SVGScriptElement", + "SVGSetElement", + "SVGStopElement", + "SVGStringList", + "SVGStyleElement", + "SVGSwitchElement", + "SVGSymbolElement", + "SVGTRefElement", + "SVGTSpanElement", + "SVGTextContentElement", + "SVGTextElement", + "SVGTextPathElement", + "SVGTextPositioningElement", + "SVGTitleElement", + "SVGTransform", + "SVGTransformList", + "SVGUnitTypes", + "SVGUseElement", + "SVGVKernElement", + "SVGViewElement", + "SVGViewSpec", + "SVGZoomAndPan", + "SVGZoomEvent", + "SVG_ANGLETYPE_DEG", + "SVG_ANGLETYPE_GRAD", + "SVG_ANGLETYPE_RAD", + "SVG_ANGLETYPE_UNKNOWN", + "SVG_ANGLETYPE_UNSPECIFIED", + "SVG_CHANNEL_A", + "SVG_CHANNEL_B", + "SVG_CHANNEL_G", + "SVG_CHANNEL_R", + "SVG_CHANNEL_UNKNOWN", + "SVG_COLORTYPE_CURRENTCOLOR", + "SVG_COLORTYPE_RGBCOLOR", + "SVG_COLORTYPE_RGBCOLOR_ICCCOLOR", + "SVG_COLORTYPE_UNKNOWN", + "SVG_EDGEMODE_DUPLICATE", + "SVG_EDGEMODE_NONE", + "SVG_EDGEMODE_UNKNOWN", + "SVG_EDGEMODE_WRAP", + "SVG_FEBLEND_MODE_COLOR", + "SVG_FEBLEND_MODE_COLOR_BURN", + "SVG_FEBLEND_MODE_COLOR_DODGE", + "SVG_FEBLEND_MODE_DARKEN", + "SVG_FEBLEND_MODE_DIFFERENCE", + "SVG_FEBLEND_MODE_EXCLUSION", + "SVG_FEBLEND_MODE_HARD_LIGHT", + "SVG_FEBLEND_MODE_HUE", + "SVG_FEBLEND_MODE_LIGHTEN", + "SVG_FEBLEND_MODE_LUMINOSITY", + "SVG_FEBLEND_MODE_MULTIPLY", + "SVG_FEBLEND_MODE_NORMAL", + "SVG_FEBLEND_MODE_OVERLAY", + "SVG_FEBLEND_MODE_SATURATION", + "SVG_FEBLEND_MODE_SCREEN", + "SVG_FEBLEND_MODE_SOFT_LIGHT", + "SVG_FEBLEND_MODE_UNKNOWN", + "SVG_FECOLORMATRIX_TYPE_HUEROTATE", + "SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA", + "SVG_FECOLORMATRIX_TYPE_MATRIX", + "SVG_FECOLORMATRIX_TYPE_SATURATE", + "SVG_FECOLORMATRIX_TYPE_UNKNOWN", + "SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE", + "SVG_FECOMPONENTTRANSFER_TYPE_GAMMA", + "SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY", + "SVG_FECOMPONENTTRANSFER_TYPE_LINEAR", + "SVG_FECOMPONENTTRANSFER_TYPE_TABLE", + "SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN", + "SVG_FECOMPOSITE_OPERATOR_ARITHMETIC", + "SVG_FECOMPOSITE_OPERATOR_ATOP", + "SVG_FECOMPOSITE_OPERATOR_IN", + "SVG_FECOMPOSITE_OPERATOR_LIGHTER", + "SVG_FECOMPOSITE_OPERATOR_OUT", + "SVG_FECOMPOSITE_OPERATOR_OVER", + "SVG_FECOMPOSITE_OPERATOR_UNKNOWN", + "SVG_FECOMPOSITE_OPERATOR_XOR", + "SVG_INVALID_VALUE_ERR", + "SVG_LENGTHTYPE_CM", + "SVG_LENGTHTYPE_EMS", + "SVG_LENGTHTYPE_EXS", + "SVG_LENGTHTYPE_IN", + "SVG_LENGTHTYPE_MM", + "SVG_LENGTHTYPE_NUMBER", + "SVG_LENGTHTYPE_PC", + "SVG_LENGTHTYPE_PERCENTAGE", + "SVG_LENGTHTYPE_PT", + "SVG_LENGTHTYPE_PX", + "SVG_LENGTHTYPE_UNKNOWN", + "SVG_MARKERUNITS_STROKEWIDTH", + "SVG_MARKERUNITS_UNKNOWN", + "SVG_MARKERUNITS_USERSPACEONUSE", + "SVG_MARKER_ORIENT_ANGLE", + "SVG_MARKER_ORIENT_AUTO", + "SVG_MARKER_ORIENT_AUTO_START_REVERSE", + "SVG_MARKER_ORIENT_UNKNOWN", + "SVG_MASKTYPE_ALPHA", + "SVG_MASKTYPE_LUMINANCE", + "SVG_MATRIX_NOT_INVERTABLE", + "SVG_MEETORSLICE_MEET", + "SVG_MEETORSLICE_SLICE", + "SVG_MEETORSLICE_UNKNOWN", + "SVG_MORPHOLOGY_OPERATOR_DILATE", + "SVG_MORPHOLOGY_OPERATOR_ERODE", + "SVG_MORPHOLOGY_OPERATOR_UNKNOWN", + "SVG_PAINTTYPE_CURRENTCOLOR", + "SVG_PAINTTYPE_NONE", + "SVG_PAINTTYPE_RGBCOLOR", + "SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR", + "SVG_PAINTTYPE_UNKNOWN", + "SVG_PAINTTYPE_URI", + "SVG_PAINTTYPE_URI_CURRENTCOLOR", + "SVG_PAINTTYPE_URI_NONE", + "SVG_PAINTTYPE_URI_RGBCOLOR", + "SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR", + "SVG_PRESERVEASPECTRATIO_NONE", + "SVG_PRESERVEASPECTRATIO_UNKNOWN", + "SVG_PRESERVEASPECTRATIO_XMAXYMAX", + "SVG_PRESERVEASPECTRATIO_XMAXYMID", + "SVG_PRESERVEASPECTRATIO_XMAXYMIN", + "SVG_PRESERVEASPECTRATIO_XMIDYMAX", + "SVG_PRESERVEASPECTRATIO_XMIDYMID", + "SVG_PRESERVEASPECTRATIO_XMIDYMIN", + "SVG_PRESERVEASPECTRATIO_XMINYMAX", + "SVG_PRESERVEASPECTRATIO_XMINYMID", + "SVG_PRESERVEASPECTRATIO_XMINYMIN", + "SVG_SPREADMETHOD_PAD", + "SVG_SPREADMETHOD_REFLECT", + "SVG_SPREADMETHOD_REPEAT", + "SVG_SPREADMETHOD_UNKNOWN", + "SVG_STITCHTYPE_NOSTITCH", + "SVG_STITCHTYPE_STITCH", + "SVG_STITCHTYPE_UNKNOWN", + "SVG_TRANSFORM_MATRIX", + "SVG_TRANSFORM_ROTATE", + "SVG_TRANSFORM_SCALE", + "SVG_TRANSFORM_SKEWX", + "SVG_TRANSFORM_SKEWY", + "SVG_TRANSFORM_TRANSLATE", + "SVG_TRANSFORM_UNKNOWN", + "SVG_TURBULENCE_TYPE_FRACTALNOISE", + "SVG_TURBULENCE_TYPE_TURBULENCE", + "SVG_TURBULENCE_TYPE_UNKNOWN", + "SVG_UNIT_TYPE_OBJECTBOUNDINGBOX", + "SVG_UNIT_TYPE_UNKNOWN", + "SVG_UNIT_TYPE_USERSPACEONUSE", + "SVG_WRONG_TYPE_ERR", + "SVG_ZOOMANDPAN_DISABLE", + "SVG_ZOOMANDPAN_MAGNIFY", + "SVG_ZOOMANDPAN_UNKNOWN", + "SYNC_CONDITION", + "SYNC_FENCE", + "SYNC_FLAGS", + "SYNC_FLUSH_COMMANDS_BIT", + "SYNC_GPU_COMMANDS_COMPLETE", + "SYNC_STATUS", + "SYNTAX_ERR", + "SavedPages", + "Scheduler", + "Scheduling", + "Screen", + "ScreenDetailed", + "ScreenDetails", + "ScreenOrientation", + "Script", + "ScriptProcessorNode", + "ScrollAreaEvent", + "ScrollTimeline", + "SecurityPolicyViolationEvent", + "Segmenter", + "Selection", + "Sensor", + "SensorErrorEvent", + "Serial", + "SerialPort", + "ServiceWorker", + "ServiceWorkerContainer", + "ServiceWorkerRegistration", + "SessionDescription", + "Set", + "ShadowRoot", + "SharedArrayBuffer", + "SharedStorage", + "SharedStorageWorklet", + "SharedWorker", + "SimpleGestureEvent", + "SourceBuffer", + "SourceBufferList", + "SpeechSynthesis", + "SpeechSynthesisErrorEvent", + "SpeechSynthesisEvent", + "SpeechSynthesisUtterance", + "SpeechSynthesisVoice", + "StaticRange", + "StereoPannerNode", + "StopIteration", + "Storage", + "StorageBucket", + "StorageBucketManager", + "StorageEvent", + "StorageManager", + "String", + "StructType", + "StylePropertyMap", + "StylePropertyMapReadOnly", + "StyleSheet", + "StyleSheetList", + "SubmitEvent", + "SubtleCrypto", + "Symbol", + "SyncManager", + "SyntaxError", + "TEMPORARY", + "TEXTPATH_METHODTYPE_ALIGN", + "TEXTPATH_METHODTYPE_STRETCH", + "TEXTPATH_METHODTYPE_UNKNOWN", + "TEXTPATH_SPACINGTYPE_AUTO", + "TEXTPATH_SPACINGTYPE_EXACT", + "TEXTPATH_SPACINGTYPE_UNKNOWN", + "TEXTURE", + "TEXTURE0", + "TEXTURE1", + "TEXTURE10", + "TEXTURE11", + "TEXTURE12", + "TEXTURE13", + "TEXTURE14", + "TEXTURE15", + "TEXTURE16", + "TEXTURE17", + "TEXTURE18", + "TEXTURE19", + "TEXTURE2", + "TEXTURE20", + "TEXTURE21", + "TEXTURE22", + "TEXTURE23", + "TEXTURE24", + "TEXTURE25", + "TEXTURE26", + "TEXTURE27", + "TEXTURE28", + "TEXTURE29", + "TEXTURE3", + "TEXTURE30", + "TEXTURE31", + "TEXTURE4", + "TEXTURE5", + "TEXTURE6", + "TEXTURE7", + "TEXTURE8", + "TEXTURE9", + "TEXTURE_2D", + "TEXTURE_2D_ARRAY", + "TEXTURE_3D", + "TEXTURE_BASE_LEVEL", + "TEXTURE_BINDING", + "TEXTURE_BINDING_2D", + "TEXTURE_BINDING_2D_ARRAY", + "TEXTURE_BINDING_3D", + "TEXTURE_BINDING_CUBE_MAP", + "TEXTURE_COMPARE_FUNC", + "TEXTURE_COMPARE_MODE", + "TEXTURE_CUBE_MAP", + "TEXTURE_CUBE_MAP_NEGATIVE_X", + "TEXTURE_CUBE_MAP_NEGATIVE_Y", + "TEXTURE_CUBE_MAP_NEGATIVE_Z", + "TEXTURE_CUBE_MAP_POSITIVE_X", + "TEXTURE_CUBE_MAP_POSITIVE_Y", + "TEXTURE_CUBE_MAP_POSITIVE_Z", + "TEXTURE_IMMUTABLE_FORMAT", + "TEXTURE_IMMUTABLE_LEVELS", + "TEXTURE_MAG_FILTER", + "TEXTURE_MAX_ANISOTROPY_EXT", + "TEXTURE_MAX_LEVEL", + "TEXTURE_MAX_LOD", + "TEXTURE_MIN_FILTER", + "TEXTURE_MIN_LOD", + "TEXTURE_WRAP_R", + "TEXTURE_WRAP_S", + "TEXTURE_WRAP_T", + "TEXT_NODE", + "TIMEOUT", + "TIMEOUT_ERR", + "TIMEOUT_EXPIRED", + "TIMEOUT_IGNORED", + "TOO_LARGE_ERR", + "TRANSACTION_INACTIVE_ERR", + "TRANSFORM_FEEDBACK", + "TRANSFORM_FEEDBACK_ACTIVE", + "TRANSFORM_FEEDBACK_BINDING", + "TRANSFORM_FEEDBACK_BUFFER", + "TRANSFORM_FEEDBACK_BUFFER_BINDING", + "TRANSFORM_FEEDBACK_BUFFER_MODE", + "TRANSFORM_FEEDBACK_BUFFER_SIZE", + "TRANSFORM_FEEDBACK_BUFFER_START", + "TRANSFORM_FEEDBACK_PAUSED", + "TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN", + "TRANSFORM_FEEDBACK_VARYINGS", + "TRIANGLE", + "TRIANGLES", + "TRIANGLE_FAN", + "TRIANGLE_STRIP", + "TYPE_BACK_FORWARD", + "TYPE_ERR", + "TYPE_MISMATCH_ERR", + "TYPE_NAVIGATE", + "TYPE_RELOAD", + "TYPE_RESERVED", + "Table", + "Tag", + "TaskAttributionTiming", + "TaskController", + "TaskPriorityChangeEvent", + "TaskSignal", + "Text", + "TextDecoder", + "TextDecoderStream", + "TextEncoder", + "TextEncoderStream", + "TextEvent", + "TextFormat", + "TextFormatUpdateEvent", + "TextMetrics", + "TextTrack", + "TextTrackCue", + "TextTrackCueList", + "TextTrackList", + "TextUpdateEvent", + "TimeEvent", + "TimeRanges", + "ToggleEvent", + "Touch", + "TouchEvent", + "TouchList", + "TrackEvent", + "TransformStream", + "TransformStreamDefaultController", + "TransitionEvent", + "TreeWalker", + "TrustedHTML", + "TrustedScript", + "TrustedScriptURL", + "TrustedTypePolicy", + "TrustedTypePolicyFactory", + "TypeError", + "TypedObject", + "U2F", + "UIEvent", + "UNCACHED", + "UNIFORM", + "UNIFORM_ARRAY_STRIDE", + "UNIFORM_BLOCK_ACTIVE_UNIFORMS", + "UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES", + "UNIFORM_BLOCK_BINDING", + "UNIFORM_BLOCK_DATA_SIZE", + "UNIFORM_BLOCK_INDEX", + "UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER", + "UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER", + "UNIFORM_BUFFER", + "UNIFORM_BUFFER_BINDING", + "UNIFORM_BUFFER_OFFSET_ALIGNMENT", + "UNIFORM_BUFFER_SIZE", + "UNIFORM_BUFFER_START", + "UNIFORM_IS_ROW_MAJOR", + "UNIFORM_MATRIX_STRIDE", + "UNIFORM_OFFSET", + "UNIFORM_SIZE", + "UNIFORM_TYPE", + "UNKNOWN_ERR", + "UNKNOWN_RULE", + "UNMASKED_RENDERER_WEBGL", + "UNMASKED_VENDOR_WEBGL", + "UNORDERED_NODE_ITERATOR_TYPE", + "UNORDERED_NODE_SNAPSHOT_TYPE", + "UNPACK_ALIGNMENT", + "UNPACK_COLORSPACE_CONVERSION_WEBGL", + "UNPACK_FLIP_Y_WEBGL", + "UNPACK_IMAGE_HEIGHT", + "UNPACK_PREMULTIPLY_ALPHA_WEBGL", + "UNPACK_ROW_LENGTH", + "UNPACK_SKIP_IMAGES", + "UNPACK_SKIP_PIXELS", + "UNPACK_SKIP_ROWS", + "UNSCHEDULED_STATE", + "UNSENT", + "UNSIGNALED", + "UNSIGNED_BYTE", + "UNSIGNED_INT", + "UNSIGNED_INT_10F_11F_11F_REV", + "UNSIGNED_INT_24_8", + "UNSIGNED_INT_2_10_10_10_REV", + "UNSIGNED_INT_5_9_9_9_REV", + "UNSIGNED_INT_SAMPLER_2D", + "UNSIGNED_INT_SAMPLER_2D_ARRAY", + "UNSIGNED_INT_SAMPLER_3D", + "UNSIGNED_INT_SAMPLER_CUBE", + "UNSIGNED_INT_VEC2", + "UNSIGNED_INT_VEC3", + "UNSIGNED_INT_VEC4", + "UNSIGNED_NORMALIZED", + "UNSIGNED_SHORT", + "UNSIGNED_SHORT_4_4_4_4", + "UNSIGNED_SHORT_5_5_5_1", + "UNSIGNED_SHORT_5_6_5", + "UNSPECIFIED_EVENT_TYPE_ERR", + "UPDATEREADY", + "URIError", + "URL", + "URLPattern", + "URLSearchParams", + "URLUnencoded", + "URL_MISMATCH_ERR", + "USB", + "USBAlternateInterface", + "USBConfiguration", + "USBConnectionEvent", + "USBDevice", + "USBEndpoint", + "USBInTransferResult", + "USBInterface", + "USBIsochronousInTransferPacket", + "USBIsochronousInTransferResult", + "USBIsochronousOutTransferPacket", + "USBIsochronousOutTransferResult", + "USBOutTransferResult", + "UTC", + "Uint16Array", + "Uint32Array", + "Uint8Array", + "Uint8ClampedArray", + "UserActivation", + "UserMessageHandler", + "UserMessageHandlersNamespace", + "UserProximityEvent", + "VALIDATE_STATUS", + "VALIDATION_ERR", + "VARIABLES_RULE", + "VENDOR", + "VERSION", + "VERSION_CHANGE", + "VERSION_ERR", + "VERTEX", + "VERTEX_ARRAY_BINDING", + "VERTEX_ATTRIB_ARRAY_BUFFER_BINDING", + "VERTEX_ATTRIB_ARRAY_DIVISOR", + "VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE", + "VERTEX_ATTRIB_ARRAY_ENABLED", + "VERTEX_ATTRIB_ARRAY_INTEGER", + "VERTEX_ATTRIB_ARRAY_NORMALIZED", + "VERTEX_ATTRIB_ARRAY_POINTER", + "VERTEX_ATTRIB_ARRAY_SIZE", + "VERTEX_ATTRIB_ARRAY_STRIDE", + "VERTEX_ATTRIB_ARRAY_TYPE", + "VERTEX_SHADER", + "VERTICAL", + "VERTICAL_AXIS", + "VER_ERR", + "VIEWPORT", + "VIEWPORT_RULE", + "VRDisplay", + "VRDisplayCapabilities", + "VRDisplayEvent", + "VREyeParameters", + "VRFieldOfView", + "VRFrameData", + "VRPose", + "VRStageParameters", + "VTTCue", + "VTTRegion", + "ValidityState", + "VideoColorSpace", + "VideoDecoder", + "VideoEncoder", + "VideoFrame", + "VideoPlaybackQuality", + "VideoStreamTrack", + "ViewTimeline", + "ViewTransition", + "VirtualKeyboard", + "VirtualKeyboardGeometryChangeEvent", + "VisibilityStateEntry", + "VisualViewport", + "WAIT_FAILED", + "WEBKIT_FILTER_RULE", + "WEBKIT_KEYFRAMES_RULE", + "WEBKIT_KEYFRAME_RULE", + "WEBKIT_REGION_RULE", + "WGSLLanguageFeatures", + "WRITE", + "WRONG_DOCUMENT_ERR", + "WakeLock", + "WakeLockSentinel", + "WasmAnyRef", + "WaveShaperNode", + "WeakMap", + "WeakRef", + "WeakSet", + "WebAssembly", + "WebGL2RenderingContext", + "WebGLActiveInfo", + "WebGLBuffer", + "WebGLContextEvent", + "WebGLFramebuffer", + "WebGLProgram", + "WebGLQuery", + "WebGLRenderbuffer", + "WebGLRenderingContext", + "WebGLSampler", + "WebGLShader", + "WebGLShaderPrecisionFormat", + "WebGLSync", + "WebGLTexture", + "WebGLTransformFeedback", + "WebGLUniformLocation", + "WebGLVertexArray", + "WebGLVertexArrayObject", + "WebKitAnimationEvent", + "WebKitBlobBuilder", + "WebKitCSSFilterRule", + "WebKitCSSFilterValue", + "WebKitCSSKeyframeRule", + "WebKitCSSKeyframesRule", + "WebKitCSSMatrix", + "WebKitCSSRegionRule", + "WebKitCSSTransformValue", + "WebKitDataCue", + "WebKitGamepad", + "WebKitMediaKeyError", + "WebKitMediaKeyMessageEvent", + "WebKitMediaKeySession", + "WebKitMediaKeys", + "WebKitMediaSource", + "WebKitMutationObserver", + "WebKitNamespace", + "WebKitPlaybackTargetAvailabilityEvent", + "WebKitPoint", + "WebKitShadowRoot", + "WebKitSourceBuffer", + "WebKitSourceBufferList", + "WebKitTransitionEvent", + "WebSocket", + "WebSocketError", + "WebSocketStream", + "WebTransport", + "WebTransportBidirectionalStream", + "WebTransportDatagramDuplexStream", + "WebTransportError", + "WebTransportReceiveStream", + "WebTransportSendStream", + "WebkitAlignContent", + "WebkitAlignItems", + "WebkitAlignSelf", + "WebkitAnimation", + "WebkitAnimationDelay", + "WebkitAnimationDirection", + "WebkitAnimationDuration", + "WebkitAnimationFillMode", + "WebkitAnimationIterationCount", + "WebkitAnimationName", + "WebkitAnimationPlayState", + "WebkitAnimationTimingFunction", + "WebkitAppearance", + "WebkitBackfaceVisibility", + "WebkitBackgroundClip", + "WebkitBackgroundOrigin", + "WebkitBackgroundSize", + "WebkitBorderBottomLeftRadius", + "WebkitBorderBottomRightRadius", + "WebkitBorderImage", + "WebkitBorderRadius", + "WebkitBorderTopLeftRadius", + "WebkitBorderTopRightRadius", + "WebkitBoxAlign", + "WebkitBoxDirection", + "WebkitBoxFlex", + "WebkitBoxOrdinalGroup", + "WebkitBoxOrient", + "WebkitBoxPack", + "WebkitBoxShadow", + "WebkitBoxSizing", + "WebkitClipPath", + "WebkitFilter", + "WebkitFlex", + "WebkitFlexBasis", + "WebkitFlexDirection", + "WebkitFlexFlow", + "WebkitFlexGrow", + "WebkitFlexShrink", + "WebkitFlexWrap", + "WebkitJustifyContent", + "WebkitLineClamp", + "WebkitMask", + "WebkitMaskClip", + "WebkitMaskComposite", + "WebkitMaskImage", + "WebkitMaskOrigin", + "WebkitMaskPosition", + "WebkitMaskPositionX", + "WebkitMaskPositionY", + "WebkitMaskRepeat", + "WebkitMaskSize", + "WebkitOrder", + "WebkitPerspective", + "WebkitPerspectiveOrigin", + "WebkitTextFillColor", + "WebkitTextSecurity", + "WebkitTextSizeAdjust", + "WebkitTextStroke", + "WebkitTextStrokeColor", + "WebkitTextStrokeWidth", + "WebkitTransform", + "WebkitTransformOrigin", + "WebkitTransformStyle", + "WebkitTransition", + "WebkitTransitionDelay", + "WebkitTransitionDuration", + "WebkitTransitionProperty", + "WebkitTransitionTimingFunction", + "WebkitUserSelect", + "WheelEvent", + "Window", + "WindowControlsOverlay", + "WindowControlsOverlayGeometryChangeEvent", + "Worker", + "Worklet", + "WritableStream", + "WritableStreamDefaultController", + "WritableStreamDefaultWriter", + "XMLDocument", + "XMLHttpRequest", + "XMLHttpRequestEventTarget", + "XMLHttpRequestException", + "XMLHttpRequestProgressEvent", + "XMLHttpRequestUpload", + "XMLSerializer", + "XMLStylesheetProcessingInstruction", + "XPathEvaluator", + "XPathException", + "XPathExpression", + "XPathNSResolver", + "XPathResult", + "XRAnchor", + "XRAnchorSet", + "XRBoundedReferenceSpace", + "XRCPUDepthInformation", + "XRCamera", + "XRDOMOverlayState", + "XRDepthInformation", + "XRFrame", + "XRHitTestResult", + "XRHitTestSource", + "XRInputSource", + "XRInputSourceArray", + "XRInputSourceEvent", + "XRInputSourcesChangeEvent", + "XRLayer", + "XRLightEstimate", + "XRLightProbe", + "XRPose", + "XRRay", + "XRReferenceSpace", + "XRReferenceSpaceEvent", + "XRRenderState", + "XRRigidTransform", + "XRSession", + "XRSessionEvent", + "XRSpace", + "XRSystem", + "XRTransientInputHitTestResult", + "XRTransientInputHitTestSource", + "XRView", + "XRViewerPose", + "XRViewport", + "XRWebGLBinding", + "XRWebGLDepthInformation", + "XRWebGLLayer", + "XSLTProcessor", + "ZERO", + "_XD0M_", + "_YD0M_", + "__REACT_DEVTOOLS_GLOBAL_HOOK__", + "__brand", + "__defineGetter__", + "__defineSetter__", + "__lookupGetter__", + "__lookupSetter__", + "__opera", + "__proto__", + "_browserjsran", + "a", + "aLink", + "abbr", + "abort", + "aborted", + "abs", + "absolute", + "acceleration", + "accelerationIncludingGravity", + "accelerator", + "accent-color", + "accentColor", + "accept", + "acceptCharset", + "acceptNode", + "access", + "accessKey", + "accessKeyLabel", + "accuracy", + "acos", + "acosh", + "action", + "actionURL", + "actions", + "activated", + "activation", + "activationStart", + "active", + "activeCues", + "activeElement", + "activeSourceBuffers", + "activeSourceCount", + "activeTexture", + "activeVRDisplays", + "actualBoundingBoxAscent", + "actualBoundingBoxDescent", + "actualBoundingBoxLeft", + "actualBoundingBoxRight", + "adAuctionComponents", + "adAuctionHeaders", + "add", + "addAll", + "addBehavior", + "addCandidate", + "addColorStop", + "addCue", + "addElement", + "addEventListener", + "addFilter", + "addFromString", + "addFromUri", + "addIceCandidate", + "addImport", + "addListener", + "addModule", + "addNamed", + "addPageRule", + "addPath", + "addPointer", + "addRange", + "addRegion", + "addRule", + "addSearchEngine", + "addSourceBuffer", + "addStream", + "addTextTrack", + "addTrack", + "addTransceiver", + "addWakeLockListener", + "added", + "addedNodes", + "additionalName", + "additiveSymbols", + "addons", + "address", + "addressLine", + "addressModeU", + "addressModeV", + "addressModeW", + "adoptNode", + "adoptedCallback", + "adoptedStyleSheets", + "adr", + "advance", + "after", + "album", + "alert", + "algorithm", + "align", + "align-content", + "align-items", + "align-self", + "alignContent", + "alignItems", + "alignSelf", + "alignmentBaseline", + "alinkColor", + "all", + "allSettled", + "allocationSize", + "allow", + "allowFullscreen", + "allowPaymentRequest", + "allowedDirections", + "allowedFeatures", + "allowedToPlay", + "allowsFeature", + "alpha", + "alphaMode", + "alphaToCoverageEnabled", + "alphabeticBaseline", + "alt", + "altGraphKey", + "altHtml", + "altKey", + "altLeft", + "alternate", + "alternateSetting", + "alternates", + "altitude", + "altitudeAccuracy", + "altitudeAngle", + "amplitude", + "ancestorOrigins", + "anchor", + "anchorNode", + "anchorOffset", + "anchorSpace", + "anchors", + "and", + "angle", + "angularAcceleration", + "angularVelocity", + "animVal", + "animate", + "animated", + "animatedInstanceRoot", + "animatedNormalizedPathSegList", + "animatedPathSegList", + "animatedPoints", + "animation", + "animation-composition", + "animation-delay", + "animation-direction", + "animation-duration", + "animation-fill-mode", + "animation-iteration-count", + "animation-name", + "animation-play-state", + "animation-timing-function", + "animationComposition", + "animationDelay", + "animationDirection", + "animationDuration", + "animationFillMode", + "animationIterationCount", + "animationName", + "animationPlayState", + "animationStartTime", + "animationTimingFunction", + "animationsPaused", + "anniversary", + "antialias", + "anticipatedRemoval", + "any", + "app", + "appCodeName", + "appMinorVersion", + "appName", + "appNotifications", + "appVersion", + "appearance", + "append", + "appendBuffer", + "appendChild", + "appendData", + "appendItem", + "appendMedium", + "appendNamed", + "appendRule", + "appendStream", + "appendWindowEnd", + "appendWindowStart", + "applets", + "applicationCache", + "applicationServerKey", + "apply", + "applyConstraints", + "applyElement", + "arc", + "arcTo", + "architecture", + "archive", + "areas", + "arguments", + "ariaAtomic", + "ariaAutoComplete", + "ariaBrailleLabel", + "ariaBrailleRoleDescription", + "ariaBusy", + "ariaChecked", + "ariaColCount", + "ariaColIndex", + "ariaColIndexText", + "ariaColSpan", + "ariaCurrent", + "ariaDescription", + "ariaDisabled", + "ariaExpanded", + "ariaHasPopup", + "ariaHidden", + "ariaInvalid", + "ariaKeyShortcuts", + "ariaLabel", + "ariaLevel", + "ariaLive", + "ariaModal", + "ariaMultiLine", + "ariaMultiSelectable", + "ariaOrientation", + "ariaPlaceholder", + "ariaPosInSet", + "ariaPressed", + "ariaReadOnly", + "ariaRelevant", + "ariaRequired", + "ariaRoleDescription", + "ariaRowCount", + "ariaRowIndex", + "ariaRowIndexText", + "ariaRowSpan", + "ariaSelected", + "ariaSetSize", + "ariaSort", + "ariaValueMax", + "ariaValueMin", + "ariaValueNow", + "ariaValueText", + "arrayBuffer", + "arrayLayerCount", + "arrayStride", + "artist", + "artwork", + "as", + "asIntN", + "asUintN", + "ascentOverride", + "asin", + "asinh", + "aspect", + "aspect-ratio", + "aspectRatio", + "assert", + "assign", + "assignedElements", + "assignedNodes", + "assignedSlot", + "async", + "asyncIterator", + "at", + "atEnd", + "atan", + "atan2", + "atanh", + "atob", + "attachEvent", + "attachInternals", + "attachShader", + "attachShadow", + "attachedElements", + "attachments", + "attack", + "attestationObject", + "attrChange", + "attrName", + "attributeChangedCallback", + "attributeFilter", + "attributeName", + "attributeNamespace", + "attributeOldValue", + "attributeStyleMap", + "attributes", + "attribution", + "attributionSrc", + "audioBitrateMode", + "audioBitsPerSecond", + "audioTracks", + "audioWorklet", + "authenticatedSignedWrites", + "authenticatorAttachment", + "authenticatorData", + "autoIncrement", + "autobuffer", + "autocapitalize", + "autocomplete", + "autocorrect", + "autofocus", + "automationRate", + "autoplay", + "availHeight", + "availLeft", + "availTop", + "availWidth", + "availability", + "available", + "aversion", + "ax", + "axes", + "axis", + "ay", + "azimuth", + "azimuthAngle", + "b", + "back", + "backdrop-filter", + "backdropFilter", + "backends", + "backface-visibility", + "backfaceVisibility", + "background", + "background-attachment", + "background-blend-mode", + "background-clip", + "background-color", + "background-image", + "background-origin", + "background-position", + "background-position-x", + "background-position-y", + "background-repeat", + "background-size", + "backgroundAttachment", + "backgroundBlendMode", + "backgroundClip", + "backgroundColor", + "backgroundFetch", + "backgroundImage", + "backgroundOrigin", + "backgroundPosition", + "backgroundPositionX", + "backgroundPositionY", + "backgroundRepeat", + "backgroundSize", + "badInput", + "badge", + "balance", + "baseArrayLayer", + "baseFrequencyX", + "baseFrequencyY", + "baseLatency", + "baseLayer", + "baseMipLevel", + "baseNode", + "baseOffset", + "basePalette", + "baseURI", + "baseVal", + "baseline-source", + "baselineShift", + "baselineSource", + "battery", + "bday", + "before", + "beginComputePass", + "beginElement", + "beginElementAt", + "beginOcclusionQuery", + "beginPath", + "beginQuery", + "beginRenderPass", + "beginTransformFeedback", + "beginningOfPassWriteIndex", + "behavior", + "behaviorCookie", + "behaviorPart", + "behaviorUrns", + "beta", + "bezierCurveTo", + "bgColor", + "bgProperties", + "bias", + "big", + "bigint64", + "biguint64", + "binaryType", + "bind", + "bindAttribLocation", + "bindBuffer", + "bindBufferBase", + "bindBufferRange", + "bindFramebuffer", + "bindGroupLayouts", + "bindRenderbuffer", + "bindSampler", + "bindTexture", + "bindTransformFeedback", + "bindVertexArray", + "binding", + "bitness", + "blend", + "blendColor", + "blendEquation", + "blendEquationSeparate", + "blendFunc", + "blendFuncSeparate", + "blink", + "blitFramebuffer", + "blob", + "block-size", + "blockDirection", + "blockSize", + "blockedURI", + "blocking", + "blockingDuration", + "blue", + "bluetooth", + "blur", + "body", + "bodyUsed", + "bold", + "bookmarks", + "booleanValue", + "border", + "border-block", + "border-block-color", + "border-block-end", + "border-block-end-color", + "border-block-end-style", + "border-block-end-width", + "border-block-start", + "border-block-start-color", + "border-block-start-style", + "border-block-start-width", + "border-block-style", + "border-block-width", + "border-bottom", + "border-bottom-color", + "border-bottom-left-radius", + "border-bottom-right-radius", + "border-bottom-style", + "border-bottom-width", + "border-collapse", + "border-color", + "border-end-end-radius", + "border-end-start-radius", + "border-image", + "border-image-outset", + "border-image-repeat", + "border-image-slice", + "border-image-source", + "border-image-width", + "border-inline", + "border-inline-color", + "border-inline-end", + "border-inline-end-color", + "border-inline-end-style", + "border-inline-end-width", + "border-inline-start", + "border-inline-start-color", + "border-inline-start-style", + "border-inline-start-width", + "border-inline-style", + "border-inline-width", + "border-left", + "border-left-color", + "border-left-style", + "border-left-width", + "border-radius", + "border-right", + "border-right-color", + "border-right-style", + "border-right-width", + "border-spacing", + "border-start-end-radius", + "border-start-start-radius", + "border-style", + "border-top", + "border-top-color", + "border-top-left-radius", + "border-top-right-radius", + "border-top-style", + "border-top-width", + "border-width", + "borderBlock", + "borderBlockColor", + "borderBlockEnd", + "borderBlockEndColor", + "borderBlockEndStyle", + "borderBlockEndWidth", + "borderBlockStart", + "borderBlockStartColor", + "borderBlockStartStyle", + "borderBlockStartWidth", + "borderBlockStyle", + "borderBlockWidth", + "borderBottom", + "borderBottomColor", + "borderBottomLeftRadius", + "borderBottomRightRadius", + "borderBottomStyle", + "borderBottomWidth", + "borderBoxSize", + "borderCollapse", + "borderColor", + "borderColorDark", + "borderColorLight", + "borderEndEndRadius", + "borderEndStartRadius", + "borderImage", + "borderImageOutset", + "borderImageRepeat", + "borderImageSlice", + "borderImageSource", + "borderImageWidth", + "borderInline", + "borderInlineColor", + "borderInlineEnd", + "borderInlineEndColor", + "borderInlineEndStyle", + "borderInlineEndWidth", + "borderInlineStart", + "borderInlineStartColor", + "borderInlineStartStyle", + "borderInlineStartWidth", + "borderInlineStyle", + "borderInlineWidth", + "borderLeft", + "borderLeftColor", + "borderLeftStyle", + "borderLeftWidth", + "borderRadius", + "borderRight", + "borderRightColor", + "borderRightStyle", + "borderRightWidth", + "borderSpacing", + "borderStartEndRadius", + "borderStartStartRadius", + "borderStyle", + "borderTop", + "borderTopColor", + "borderTopLeftRadius", + "borderTopRightRadius", + "borderTopStyle", + "borderTopWidth", + "borderWidth", + "bottom", + "bottomMargin", + "bound", + "boundElements", + "boundingClientRect", + "boundingHeight", + "boundingLeft", + "boundingRect", + "boundingTop", + "boundingWidth", + "bounds", + "boundsGeometry", + "box-decoration-break", + "box-shadow", + "box-sizing", + "boxDecorationBreak", + "boxShadow", + "boxSizing", + "brand", + "brands", + "break-after", + "break-before", + "break-inside", + "breakAfter", + "breakBefore", + "breakInside", + "broadcast", + "browserLanguage", + "browsingTopics", + "btoa", + "bubbles", + "buffer", + "bufferData", + "bufferDepth", + "bufferSize", + "bufferSubData", + "buffered", + "bufferedAmount", + "bufferedAmountLowThreshold", + "buffers", + "buildID", + "buildNumber", + "button", + "buttonID", + "buttons", + "byobRequest", + "byteLength", + "byteOffset", + "bytesPerRow", + "bytesWritten", + "c", + "cache", + "caches", + "call", + "caller", + "camera", + "canBeFormatted", + "canBeMounted", + "canBeShared", + "canConstructInDedicatedWorker", + "canGoBack", + "canGoForward", + "canHaveChildren", + "canHaveHTML", + "canInsertDTMF", + "canIntercept", + "canLoadAdAuctionFencedFrame", + "canLoadOpaqueURL", + "canMakePayment", + "canParse", + "canPlayType", + "canPresent", + "canShare", + "canTransition", + "canTrickleIceCandidates", + "cancel", + "cancelAndHoldAtTime", + "cancelAnimationFrame", + "cancelBubble", + "cancelIdleCallback", + "cancelScheduledValues", + "cancelVideoFrameCallback", + "cancelWatchAvailability", + "cancelable", + "candidate", + "canonicalUUID", + "canvas", + "cap", + "capabilities", + "caption", + "caption-side", + "captionSide", + "capture", + "captureEvents", + "captureStackTrace", + "captureStream", + "caret-color", + "caretBidiLevel", + "caretColor", + "caretPositionFromPoint", + "caretRangeFromPoint", + "cast", + "catch", + "category", + "cbrt", + "cd", + "ceil", + "cellIndex", + "cellPadding", + "cellSpacing", + "cells", + "ch", + "chOff", + "chain", + "challenge", + "changeType", + "changed", + "changedTouches", + "channel", + "channelCount", + "channelCountMode", + "channelInterpretation", + "char", + "charAt", + "charCode", + "charCodeAt", + "charIndex", + "charLength", + "characterBounds", + "characterBoundsRangeStart", + "characterData", + "characterDataOldValue", + "characterSet", + "characteristic", + "charging", + "chargingTime", + "charset", + "check", + "checkDCE", + "checkEnclosure", + "checkFramebufferStatus", + "checkIntersection", + "checkValidity", + "checkVisibility", + "checked", + "childElementCount", + "childList", + "childNodes", + "children", + "chrome", + "ciphertext", + "cite", + "city", + "claimInterface", + "claimed", + "classList", + "className", + "classid", + "clear", + "clearAppBadge", + "clearAttributes", + "clearBuffer", + "clearBufferfi", + "clearBufferfv", + "clearBufferiv", + "clearBufferuiv", + "clearColor", + "clearData", + "clearDepth", + "clearHalt", + "clearImmediate", + "clearInterval", + "clearLiveSeekableRange", + "clearMarks", + "clearMaxGCPauseAccumulator", + "clearMeasures", + "clearOriginJoinedAdInterestGroups", + "clearParameters", + "clearRect", + "clearResourceTimings", + "clearShadow", + "clearStencil", + "clearTimeout", + "clearValue", + "clearWatch", + "click", + "clickCount", + "clientDataJSON", + "clientHeight", + "clientInformation", + "clientLeft", + "clientRect", + "clientRects", + "clientTop", + "clientWaitSync", + "clientWidth", + "clientX", + "clientY", + "clip", + "clip-path", + "clip-rule", + "clipBottom", + "clipLeft", + "clipPath", + "clipPathUnits", + "clipRight", + "clipRule", + "clipTop", + "clipboard", + "clipboardData", + "clonable", + "clone", + "cloneContents", + "cloneNode", + "cloneRange", + "close", + "closeCode", + "closePath", + "closed", + "closest", + "clz", + "clz32", + "cm", + "cmp", + "code", + "codeBase", + "codePointAt", + "codeType", + "codedHeight", + "codedRect", + "codedWidth", + "colSpan", + "collapse", + "collapseToEnd", + "collapseToStart", + "collapsed", + "collect", + "collections", + "colno", + "color", + "color-adjust", + "color-interpolation", + "color-interpolation-filters", + "color-scheme", + "colorAdjust", + "colorAttachments", + "colorDepth", + "colorFormats", + "colorInterpolation", + "colorInterpolationFilters", + "colorMask", + "colorScheme", + "colorSpace", + "colorType", + "cols", + "column-count", + "column-fill", + "column-gap", + "column-rule", + "column-rule-color", + "column-rule-style", + "column-rule-width", + "column-span", + "column-width", + "columnCount", + "columnFill", + "columnGap", + "columnNumber", + "columnRule", + "columnRuleColor", + "columnRuleStyle", + "columnRuleWidth", + "columnSpan", + "columnWidth", + "columns", + "command", + "commit", + "commitPreferences", + "commitStyles", + "commonAncestorContainer", + "compact", + "compare", + "compareBoundaryPoints", + "compareDocumentPosition", + "compareEndPoints", + "compareExchange", + "compareNode", + "comparePoint", + "compatMode", + "compatible", + "compile", + "compileShader", + "compileStreaming", + "complete", + "completed", + "component", + "componentFromPoint", + "composed", + "composedPath", + "composite", + "compositionEndOffset", + "compositionStartOffset", + "compressedTexImage2D", + "compressedTexImage3D", + "compressedTexSubImage2D", + "compressedTexSubImage3D", + "compute", + "computedStyleMap", + "concat", + "conditionText", + "coneInnerAngle", + "coneOuterAngle", + "coneOuterGain", + "config", + "configurable", + "configuration", + "configurationName", + "configurationValue", + "configurations", + "configure", + "confirm", + "confirmComposition", + "confirmSiteSpecificTrackingException", + "confirmWebWideTrackingException", + "congestionControl", + "connect", + "connectEnd", + "connectShark", + "connectStart", + "connected", + "connectedCallback", + "connection", + "connectionList", + "connectionSpeed", + "connectionState", + "connections", + "console", + "consolidate", + "constants", + "constraint", + "constrictionActive", + "construct", + "constructor", + "contactID", + "contain", + "contain-intrinsic-block-size", + "contain-intrinsic-height", + "contain-intrinsic-inline-size", + "contain-intrinsic-size", + "contain-intrinsic-width", + "containIntrinsicBlockSize", + "containIntrinsicHeight", + "containIntrinsicInlineSize", + "containIntrinsicSize", + "containIntrinsicWidth", + "container", + "container-name", + "container-type", + "containerId", + "containerName", + "containerQuery", + "containerSrc", + "containerType", + "contains", + "containsNode", + "content", + "content-visibility", + "contentBoxSize", + "contentDocument", + "contentEditable", + "contentHint", + "contentOverflow", + "contentRect", + "contentScriptType", + "contentStyleType", + "contentType", + "contentVisibility", + "contentWindow", + "context", + "contextMenu", + "contextmenu", + "continue", + "continuePrimaryKey", + "continuous", + "control", + "controlTransferIn", + "controlTransferOut", + "controller", + "controls", + "controlsList", + "convertPointFromNode", + "convertQuadFromNode", + "convertRectFromNode", + "convertToBlob", + "convertToSpecifiedUnits", + "cookie", + "cookieEnabled", + "cookieStore", + "cookies", + "coords", + "copyBufferSubData", + "copyBufferToBuffer", + "copyBufferToTexture", + "copyExternalImageToTexture", + "copyFromChannel", + "copyTexImage2D", + "copyTexSubImage2D", + "copyTexSubImage3D", + "copyTextureToBuffer", + "copyTextureToTexture", + "copyTo", + "copyToChannel", + "copyWithin", + "correspondingElement", + "correspondingUseElement", + "corruptedVideoFrames", + "cos", + "cosh", + "count", + "countReset", + "counter-increment", + "counter-reset", + "counter-set", + "counterIncrement", + "counterReset", + "counterSet", + "country", + "cpuClass", + "cpuSleepAllowed", + "cqb", + "cqh", + "cqi", + "cqmax", + "cqmin", + "cqw", + "create", + "createAnalyser", + "createAnchor", + "createAnswer", + "createAttribute", + "createAttributeNS", + "createAuctionNonce", + "createBidirectionalStream", + "createBindGroup", + "createBindGroupLayout", + "createBiquadFilter", + "createBuffer", + "createBufferSource", + "createCDATASection", + "createCSSStyleSheet", + "createCaption", + "createChannelMerger", + "createChannelSplitter", + "createCommandEncoder", + "createComment", + "createComputePipeline", + "createComputePipelineAsync", + "createConicGradient", + "createConstantSource", + "createContextualFragment", + "createControlRange", + "createConvolver", + "createDTMFSender", + "createDataChannel", + "createDelay", + "createDelayNode", + "createDocument", + "createDocumentFragment", + "createDocumentType", + "createDynamicsCompressor", + "createElement", + "createElementNS", + "createEncodedStreams", + "createEntityReference", + "createEvent", + "createEventObject", + "createExpression", + "createFramebuffer", + "createFunction", + "createGain", + "createGainNode", + "createHTML", + "createHTMLDocument", + "createIIRFilter", + "createImageBitmap", + "createImageData", + "createIndex", + "createJavaScriptNode", + "createLinearGradient", + "createMediaElementSource", + "createMediaKeys", + "createMediaStreamDestination", + "createMediaStreamSource", + "createMediaStreamTrackSource", + "createMutableFile", + "createNSResolver", + "createNodeIterator", + "createNotification", + "createObjectStore", + "createObjectURL", + "createOffer", + "createOscillator", + "createPanner", + "createPattern", + "createPeriodicWave", + "createPipelineLayout", + "createPolicy", + "createPopup", + "createProcessingInstruction", + "createProgram", + "createQuery", + "createQuerySet", + "createRadialGradient", + "createRange", + "createRangeCollection", + "createReader", + "createRenderBundleEncoder", + "createRenderPipeline", + "createRenderPipelineAsync", + "createRenderbuffer", + "createSVGAngle", + "createSVGLength", + "createSVGMatrix", + "createSVGNumber", + "createSVGPathSegArcAbs", + "createSVGPathSegArcRel", + "createSVGPathSegClosePath", + "createSVGPathSegCurvetoCubicAbs", + "createSVGPathSegCurvetoCubicRel", + "createSVGPathSegCurvetoCubicSmoothAbs", + "createSVGPathSegCurvetoCubicSmoothRel", + "createSVGPathSegCurvetoQuadraticAbs", + "createSVGPathSegCurvetoQuadraticRel", + "createSVGPathSegCurvetoQuadraticSmoothAbs", + "createSVGPathSegCurvetoQuadraticSmoothRel", + "createSVGPathSegLinetoAbs", + "createSVGPathSegLinetoHorizontalAbs", + "createSVGPathSegLinetoHorizontalRel", + "createSVGPathSegLinetoRel", + "createSVGPathSegLinetoVerticalAbs", + "createSVGPathSegLinetoVerticalRel", + "createSVGPathSegMovetoAbs", + "createSVGPathSegMovetoRel", + "createSVGPoint", + "createSVGRect", + "createSVGTransform", + "createSVGTransformFromMatrix", + "createSampler", + "createScript", + "createScriptProcessor", + "createScriptURL", + "createSession", + "createShader", + "createShaderModule", + "createShadowRoot", + "createStereoPanner", + "createStyleSheet", + "createTBody", + "createTFoot", + "createTHead", + "createTask", + "createTextNode", + "createTextRange", + "createTexture", + "createTouch", + "createTouchList", + "createTransformFeedback", + "createTreeWalker", + "createUnidirectionalStream", + "createVertexArray", + "createView", + "createWaveShaper", + "createWritable", + "creationTime", + "credentialless", + "credentials", + "criticalCHRestart", + "cropTo", + "crossOrigin", + "crossOriginIsolated", + "crypto", + "csi", + "csp", + "cssFloat", + "cssRules", + "cssText", + "cssValueType", + "ctrlKey", + "ctrlLeft", + "cues", + "cullFace", + "cullMode", + "currentDirection", + "currentEntry", + "currentLocalDescription", + "currentNode", + "currentPage", + "currentRect", + "currentRemoteDescription", + "currentScale", + "currentScreen", + "currentScript", + "currentSrc", + "currentState", + "currentStyle", + "currentTarget", + "currentTime", + "currentTranslate", + "currentView", + "cursor", + "curve", + "customElements", + "customError", + "cx", + "cy", + "d", + "data", + "dataFld", + "dataFormatAs", + "dataLoss", + "dataLossMessage", + "dataPageSize", + "dataSrc", + "dataTransfer", + "database", + "databases", + "datagrams", + "dataset", + "dateTime", + "db", + "debug", + "debuggerEnabled", + "declare", + "decode", + "decodeAudioData", + "decodeQueueSize", + "decodeURI", + "decodeURIComponent", + "decodedBodySize", + "decoding", + "decodingInfo", + "decrypt", + "default", + "defaultCharset", + "defaultChecked", + "defaultMuted", + "defaultPlaybackRate", + "defaultPolicy", + "defaultPrevented", + "defaultQueue", + "defaultRequest", + "defaultSelected", + "defaultStatus", + "defaultURL", + "defaultValue", + "defaultView", + "defaultstatus", + "defer", + "define", + "defineMagicFunction", + "defineMagicVariable", + "defineProperties", + "defineProperty", + "deg", + "delay", + "delayTime", + "delegatesFocus", + "delete", + "deleteBuffer", + "deleteCaption", + "deleteCell", + "deleteContents", + "deleteData", + "deleteDatabase", + "deleteFramebuffer", + "deleteFromDocument", + "deleteIndex", + "deleteMedium", + "deleteObjectStore", + "deleteProgram", + "deleteProperty", + "deleteQuery", + "deleteRenderbuffer", + "deleteRow", + "deleteRule", + "deleteSampler", + "deleteShader", + "deleteSync", + "deleteTFoot", + "deleteTHead", + "deleteTexture", + "deleteTransformFeedback", + "deleteVertexArray", + "deleted", + "deliverChangeRecords", + "deliveredFrames", + "delivery", + "deliveryInfo", + "deliveryStatus", + "deliveryTimestamp", + "deliveryType", + "delta", + "deltaMode", + "deltaX", + "deltaY", + "deltaZ", + "dependentLocality", + "deprecatedReplaceInURN", + "deprecatedRunAdAuctionEnforcesKAnonymity", + "deprecatedURNToURL", + "depthBias", + "depthBiasClamp", + "depthBiasSlopeScale", + "depthClearValue", + "depthCompare", + "depthDataFormat", + "depthFailOp", + "depthFar", + "depthFunc", + "depthLoadOp", + "depthMask", + "depthNear", + "depthOrArrayLayers", + "depthRange", + "depthReadOnly", + "depthStencil", + "depthStencilAttachment", + "depthStencilFormat", + "depthStoreOp", + "depthUsage", + "depthWriteEnabled", + "deref", + "deriveBits", + "deriveKey", + "descentOverride", + "description", + "deselectAll", + "designMode", + "desiredSize", + "destination", + "destinationURL", + "destroy", + "detach", + "detachEvent", + "detachShader", + "detached", + "detail", + "details", + "detect", + "detune", + "device", + "deviceClass", + "deviceId", + "deviceMemory", + "devicePixelContentBoxSize", + "devicePixelRatio", + "deviceProtocol", + "deviceSubclass", + "deviceVersionMajor", + "deviceVersionMinor", + "deviceVersionSubminor", + "deviceXDPI", + "deviceYDPI", + "didTimeout", + "difference", + "diffuseConstant", + "digest", + "dimension", + "dimensions", + "dir", + "dirName", + "direction", + "dirxml", + "disable", + "disablePictureInPicture", + "disableRemotePlayback", + "disableVertexAttribArray", + "disabled", + "discardedFrames", + "dischargingTime", + "disconnect", + "disconnectShark", + "disconnectedCallback", + "dispatchEvent", + "dispatchWorkgroups", + "dispatchWorkgroupsIndirect", + "display", + "displayHeight", + "displayId", + "displayName", + "displayWidth", + "disposition", + "distanceModel", + "div", + "divisor", + "djsapi", + "djsproxy", + "doImport", + "doNotTrack", + "doScroll", + "doctype", + "document", + "documentElement", + "documentMode", + "documentPictureInPicture", + "documentURI", + "dolphin", + "dolphinGameCenter", + "dolphininfo", + "dolphinmeta", + "domComplete", + "domContentLoadedEventEnd", + "domContentLoadedEventStart", + "domInteractive", + "domLoading", + "domOverlayState", + "domain", + "domainLookupEnd", + "domainLookupStart", + "dominant-baseline", + "dominantBaseline", + "done", + "dopplerFactor", + "dotAll", + "downDegrees", + "downlink", + "download", + "downloadRequest", + "downloadTotal", + "downloaded", + "dpcm", + "dpi", + "dppx", + "dragDrop", + "draggable", + "draw", + "drawArrays", + "drawArraysInstanced", + "drawArraysInstancedANGLE", + "drawBuffers", + "drawCustomFocusRing", + "drawElements", + "drawElementsInstanced", + "drawElementsInstancedANGLE", + "drawFocusIfNeeded", + "drawImage", + "drawImageFromRect", + "drawIndexed", + "drawIndexedIndirect", + "drawIndirect", + "drawRangeElements", + "drawSystemFocusRing", + "drawingBufferColorSpace", + "drawingBufferFormat", + "drawingBufferHeight", + "drawingBufferStorage", + "drawingBufferWidth", + "drop", + "dropEffect", + "droppedVideoFrames", + "dropzone", + "dstFactor", + "dtmf", + "dump", + "dumpProfile", + "duplicate", + "durability", + "duration", + "dvb", + "dvh", + "dvi", + "dvmax", + "dvmin", + "dvname", + "dvnum", + "dvw", + "dx", + "dy", + "dynsrc", + "e", + "edgeMode", + "editContext", + "effect", + "effectAllowed", + "effectiveDirective", + "effectiveType", + "elapsedTime", + "element", + "elementFromPoint", + "elementTiming", + "elements", + "elementsFromPoint", + "elevation", + "ellipse", + "em", + "emHeightAscent", + "emHeightDescent", + "email", + "embeds", + "emit", + "emma", + "empty", + "empty-cells", + "emptyCells", + "emptyHTML", + "emptyScript", + "emulatedPosition", + "enable", + "enableBackground", + "enableDelegations", + "enableStyleSheetsForSet", + "enableVertexAttribArray", + "enabled", + "enabledFeatures", + "enabledPlugin", + "encode", + "encodeInto", + "encodeQueueSize", + "encodeURI", + "encodeURIComponent", + "encodedBodySize", + "encoding", + "encodingInfo", + "encrypt", + "enctype", + "end", + "endContainer", + "endElement", + "endElementAt", + "endOcclusionQuery", + "endOfPassWriteIndex", + "endOfStream", + "endOffset", + "endQuery", + "endTime", + "endTransformFeedback", + "ended", + "endpoint", + "endpointNumber", + "endpoints", + "endsWith", + "enqueue", + "enterKeyHint", + "entities", + "entries", + "entry", + "entryPoint", + "entryType", + "enumerable", + "enumerate", + "enumerateDevices", + "enumerateEditable", + "environmentBlendMode", + "equals", + "error", + "errorCode", + "errorDetail", + "errorText", + "escape", + "estimate", + "eval", + "evaluate", + "event", + "eventCounts", + "eventPhase", + "every", + "ex", + "exception", + "exchange", + "exec", + "execCommand", + "execCommandShowHelp", + "execScript", + "executeBundles", + "executionStart", + "exitFullscreen", + "exitPictureInPicture", + "exitPointerLock", + "exitPresent", + "exp", + "expand", + "expandEntityReferences", + "expando", + "expansion", + "expectedImprovement", + "expiration", + "expirationTime", + "expires", + "expiryDate", + "explicitOriginalTarget", + "expm1", + "exponent", + "exponentialRampToValueAtTime", + "exportKey", + "exports", + "extend", + "extensions", + "extentNode", + "extentOffset", + "external", + "externalResourcesRequired", + "externalTexture", + "extractContents", + "extractable", + "eye", + "f", + "face", + "factoryReset", + "failOp", + "failureReason", + "fallback", + "family", + "familyName", + "farthestViewportElement", + "fastSeek", + "fatal", + "featureId", + "featurePolicy", + "featureSettings", + "features", + "fence", + "fenceSync", + "fetch", + "fetchPriority", + "fetchStart", + "fftSize", + "fgColor", + "fieldOfView", + "file", + "fileCreatedDate", + "fileHandle", + "fileModifiedDate", + "fileName", + "fileSize", + "fileUpdatedDate", + "filename", + "files", + "filesystem", + "fill", + "fill-opacity", + "fill-rule", + "fillLightMode", + "fillOpacity", + "fillRect", + "fillRule", + "fillStyle", + "fillText", + "filter", + "filterResX", + "filterResY", + "filterUnits", + "filters", + "finally", + "find", + "findIndex", + "findLast", + "findLastIndex", + "findRule", + "findText", + "finish", + "finished", + "fireEvent", + "firesTouchEvents", + "firstChild", + "firstElementChild", + "firstInterimResponseStart", + "firstPage", + "firstUIEventTimestamp", + "fixed", + "flags", + "flat", + "flatMap", + "flex", + "flex-basis", + "flex-direction", + "flex-flow", + "flex-grow", + "flex-shrink", + "flex-wrap", + "flexBasis", + "flexDirection", + "flexFlow", + "flexGrow", + "flexShrink", + "flexWrap", + "flipX", + "flipY", + "float", + "float32", + "float64", + "flood-color", + "flood-opacity", + "floodColor", + "floodOpacity", + "floor", + "flush", + "focus", + "focusNode", + "focusOffset", + "font", + "font-family", + "font-feature-settings", + "font-kerning", + "font-language-override", + "font-optical-sizing", + "font-palette", + "font-size", + "font-size-adjust", + "font-stretch", + "font-style", + "font-synthesis", + "font-synthesis-position", + "font-synthesis-small-caps", + "font-synthesis-style", + "font-synthesis-weight", + "font-variant", + "font-variant-alternates", + "font-variant-caps", + "font-variant-east-asian", + "font-variant-ligatures", + "font-variant-numeric", + "font-variant-position", + "font-variation-settings", + "font-weight", + "fontBoundingBoxAscent", + "fontBoundingBoxDescent", + "fontFamily", + "fontFeatureSettings", + "fontKerning", + "fontLanguageOverride", + "fontOpticalSizing", + "fontPalette", + "fontSize", + "fontSizeAdjust", + "fontSmoothingEnabled", + "fontStretch", + "fontStyle", + "fontSynthesis", + "fontSynthesisPosition", + "fontSynthesisSmallCaps", + "fontSynthesisStyle", + "fontSynthesisWeight", + "fontVariant", + "fontVariantAlternates", + "fontVariantCaps", + "fontVariantEastAsian", + "fontVariantLigatures", + "fontVariantNumeric", + "fontVariantPosition", + "fontVariationSettings", + "fontWeight", + "fontcolor", + "fontfaces", + "fonts", + "fontsize", + "for", + "forEach", + "force", + "forceFallbackAdapter", + "forceRedraw", + "forced-color-adjust", + "forcedColorAdjust", + "forcedStyleAndLayoutDuration", + "forget", + "form", + "formAction", + "formData", + "formEnctype", + "formMethod", + "formNoValidate", + "formTarget", + "format", + "formatToParts", + "forms", + "forward", + "forwardX", + "forwardY", + "forwardZ", + "foundation", + "fr", + "fragment", + "fragmentDirective", + "frame", + "frameBorder", + "frameCount", + "frameElement", + "frameSpacing", + "framebuffer", + "framebufferHeight", + "framebufferRenderbuffer", + "framebufferTexture2D", + "framebufferTextureLayer", + "framebufferWidth", + "frames", + "freeSpace", + "freeze", + "frequency", + "frequencyBinCount", + "from", + "fromAsync", + "fromCharCode", + "fromCodePoint", + "fromElement", + "fromEntries", + "fromFloat32Array", + "fromFloat64Array", + "fromMatrix", + "fromPoint", + "fromQuad", + "fromRect", + "frontFace", + "fround", + "fullName", + "fullPath", + "fullRange", + "fullScreen", + "fullVersionList", + "fullscreen", + "fullscreenElement", + "fullscreenEnabled", + "fx", + "fy", + "g", + "gain", + "gamepad", + "gamma", + "gap", + "gatheringState", + "gatt", + "genderIdentity", + "generateCertificate", + "generateKey", + "generateMipmap", + "generateRequest", + "geolocation", + "gestureObject", + "get", + "getActiveAttrib", + "getActiveUniform", + "getActiveUniformBlockName", + "getActiveUniformBlockParameter", + "getActiveUniforms", + "getAdjacentText", + "getAll", + "getAllKeys", + "getAllResponseHeaders", + "getAllowlistForFeature", + "getAnimations", + "getAsFile", + "getAsFileSystemHandle", + "getAsString", + "getAttachedShaders", + "getAttribLocation", + "getAttribute", + "getAttributeNS", + "getAttributeNames", + "getAttributeNode", + "getAttributeNodeNS", + "getAttributeType", + "getAudioTracks", + "getAuthenticatorData", + "getAutoplayPolicy", + "getAvailability", + "getBBox", + "getBattery", + "getBigInt64", + "getBigUint64", + "getBindGroupLayout", + "getBlob", + "getBookmark", + "getBoundingClientRect", + "getBounds", + "getBoxQuads", + "getBufferParameter", + "getBufferSubData", + "getByteFrequencyData", + "getByteTimeDomainData", + "getCSSCanvasContext", + "getCTM", + "getCameraImage", + "getCandidateWindowClientRect", + "getCanonicalLocales", + "getCapabilities", + "getCaptureHandle", + "getChannelData", + "getCharNumAtPosition", + "getCharacteristic", + "getCharacteristics", + "getClientExtensionResults", + "getClientRect", + "getClientRects", + "getCoalescedEvents", + "getCompilationInfo", + "getCompositionAlternatives", + "getComputedStyle", + "getComputedTextLength", + "getComputedTiming", + "getConfiguration", + "getConstraints", + "getContext", + "getContextAttributes", + "getContributingSources", + "getCounterValue", + "getCueAsHTML", + "getCueById", + "getCurrentPosition", + "getCurrentTexture", + "getCurrentTime", + "getData", + "getDatabaseNames", + "getDate", + "getDay", + "getDefaultComputedStyle", + "getDepthInMeters", + "getDepthInformation", + "getDescriptor", + "getDescriptors", + "getDestinationInsertionPoints", + "getDevices", + "getDirectory", + "getDirectoryHandle", + "getDisplayMedia", + "getDistributedNodes", + "getEditable", + "getElementById", + "getElementsByClassName", + "getElementsByName", + "getElementsByTagName", + "getElementsByTagNameNS", + "getEnclosureList", + "getEndPositionOfChar", + "getEntries", + "getEntriesByName", + "getEntriesByType", + "getError", + "getExtension", + "getExtentOfChar", + "getEyeParameters", + "getFeature", + "getFiberRoots", + "getFile", + "getFileHandle", + "getFiles", + "getFilesAndDirectories", + "getFingerprints", + "getFloat32", + "getFloat64", + "getFloatFrequencyData", + "getFloatTimeDomainData", + "getFloatValue", + "getFragDataLocation", + "getFrameData", + "getFramebufferAttachmentParameter", + "getFrequencyResponse", + "getFullYear", + "getGamepads", + "getHeaderExtensionsToNegotiate", + "getHighEntropyValues", + "getHitTestResults", + "getHitTestResultsForTransientInput", + "getHours", + "getIdentityAssertion", + "getIds", + "getImageData", + "getIndexedParameter", + "getInfo", + "getInnerHTML", + "getInstalledRelatedApps", + "getInt16", + "getInt32", + "getInt8", + "getInternalModuleRanges", + "getInternalformatParameter", + "getIntersectionList", + "getItem", + "getItems", + "getKey", + "getKeyframes", + "getLayers", + "getLayoutMap", + "getLightEstimate", + "getLineDash", + "getLocalCandidates", + "getLocalParameters", + "getLocalStreams", + "getManagedConfiguration", + "getMappedRange", + "getMarks", + "getMatchedCSSRules", + "getMaxGCPauseSinceClear", + "getMeasures", + "getMetadata", + "getMilliseconds", + "getMinutes", + "getModifierState", + "getMonth", + "getName", + "getNamedItem", + "getNamedItemNS", + "getNativeFramebufferScaleFactor", + "getNegotiatedHeaderExtensions", + "getNestedConfigs", + "getNotifications", + "getNotifier", + "getNumberOfChars", + "getOffsetReferenceSpace", + "getOutputTimestamp", + "getOverrideHistoryNavigationMode", + "getOverrideStyle", + "getOwnPropertyDescriptor", + "getOwnPropertyDescriptors", + "getOwnPropertyNames", + "getOwnPropertySymbols", + "getParameter", + "getParameters", + "getParent", + "getPathSegAtLength", + "getPhotoCapabilities", + "getPhotoSettings", + "getPointAtLength", + "getPorts", + "getPose", + "getPredictedEvents", + "getPreference", + "getPreferenceDefault", + "getPreferredCanvasFormat", + "getPresentationAttribute", + "getPreventDefault", + "getPrimaryService", + "getPrimaryServices", + "getProgramInfoLog", + "getProgramParameter", + "getPropertyCSSValue", + "getPropertyPriority", + "getPropertyShorthand", + "getPropertyType", + "getPropertyValue", + "getPrototypeOf", + "getPublicKey", + "getPublicKeyAlgorithm", + "getQuery", + "getQueryParameter", + "getRGBColorValue", + "getRandomValues", + "getRangeAt", + "getReader", + "getReceivers", + "getRectValue", + "getReflectionCubeMap", + "getRegistration", + "getRegistrations", + "getRemoteCandidates", + "getRemoteCertificates", + "getRemoteParameters", + "getRemoteStreams", + "getRenderbufferParameter", + "getResponseHeader", + "getRoot", + "getRootNode", + "getRotationOfChar", + "getSVGDocument", + "getSamplerParameter", + "getScreenCTM", + "getScreenDetails", + "getSeconds", + "getSelectedCandidatePair", + "getSelection", + "getSenders", + "getService", + "getSetCookie", + "getSettings", + "getShaderInfoLog", + "getShaderParameter", + "getShaderPrecisionFormat", + "getShaderSource", + "getSignals", + "getSimpleDuration", + "getSiteIcons", + "getSources", + "getSpeculativeParserUrls", + "getStartPositionOfChar", + "getStartTime", + "getState", + "getStats", + "getStatusForPolicy", + "getStorageUpdates", + "getStreamById", + "getStringValue", + "getSubStringLength", + "getSubscription", + "getSubscriptions", + "getSupportedConstraints", + "getSupportedExtensions", + "getSupportedFormats", + "getSyncParameter", + "getSynchronizationSources", + "getTags", + "getTargetRanges", + "getTexParameter", + "getTextFormats", + "getTime", + "getTimezoneOffset", + "getTiming", + "getTitlebarAreaRect", + "getTotalLength", + "getTrackById", + "getTracks", + "getTransceivers", + "getTransform", + "getTransformFeedbackVarying", + "getTransformToElement", + "getTransports", + "getType", + "getTypeMapping", + "getUTCDate", + "getUTCDay", + "getUTCFullYear", + "getUTCHours", + "getUTCMilliseconds", + "getUTCMinutes", + "getUTCMonth", + "getUTCSeconds", + "getUint16", + "getUint32", + "getUint8", + "getUniform", + "getUniformBlockIndex", + "getUniformIndices", + "getUniformLocation", + "getUserInfo", + "getUserMedia", + "getVRDisplays", + "getValues", + "getVarDate", + "getVariableValue", + "getVertexAttrib", + "getVertexAttribOffset", + "getVideoPlaybackQuality", + "getVideoTracks", + "getViewerPose", + "getViewport", + "getVoices", + "getWakeLockState", + "getWriter", + "getYear", + "givenName", + "global", + "globalAlpha", + "globalCompositeOperation", + "globalPrivacyControl", + "globalThis", + "glyphOrientationHorizontal", + "glyphOrientationVertical", + "glyphRef", + "go", + "gpu", + "grabFrame", + "grad", + "gradientTransform", + "gradientUnits", + "grammars", + "green", + "grid", + "grid-area", + "grid-auto-columns", + "grid-auto-flow", + "grid-auto-rows", + "grid-column", + "grid-column-end", + "grid-column-gap", + "grid-column-start", + "grid-gap", + "grid-row", + "grid-row-end", + "grid-row-gap", + "grid-row-start", + "grid-template", + "grid-template-areas", + "grid-template-columns", + "grid-template-rows", + "gridArea", + "gridAutoColumns", + "gridAutoFlow", + "gridAutoRows", + "gridColumn", + "gridColumnEnd", + "gridColumnGap", + "gridColumnStart", + "gridGap", + "gridRow", + "gridRowEnd", + "gridRowGap", + "gridRowStart", + "gridTemplate", + "gridTemplateAreas", + "gridTemplateColumns", + "gridTemplateRows", + "gripSpace", + "group", + "groupBy", + "groupCollapsed", + "groupEnd", + "groupId", + "groups", + "hadRecentInput", + "hand", + "handedness", + "hangingBaseline", + "hapticActuators", + "hardwareConcurrency", + "has", + "hasAttribute", + "hasAttributeNS", + "hasAttributes", + "hasBeenActive", + "hasChildNodes", + "hasComposition", + "hasDynamicOffset", + "hasEnrolledInstrument", + "hasExtension", + "hasExternalDisplay", + "hasFeature", + "hasFocus", + "hasIndices", + "hasInstance", + "hasLayout", + "hasOrientation", + "hasOwn", + "hasOwnProperty", + "hasPointerCapture", + "hasPosition", + "hasPrivateToken", + "hasReading", + "hasRedemptionRecord", + "hasRegExpGroups", + "hasStorageAccess", + "hasUAVisualTransition", + "hash", + "hashChange", + "head", + "headers", + "heading", + "height", + "hid", + "hidden", + "hide", + "hideFocus", + "hidePopover", + "high", + "highWaterMark", + "highlights", + "hint", + "hints", + "history", + "honorificPrefix", + "honorificSuffix", + "horizontalOverflow", + "host", + "hostCandidate", + "hostname", + "href", + "hrefTranslate", + "hreflang", + "hspace", + "html5TagCheckInerface", + "htmlFor", + "htmlText", + "httpEquiv", + "httpRequestStatusCode", + "hwTimestamp", + "hyphenate-character", + "hyphenateCharacter", + "hyphens", + "hypot", + "ic", + "iccId", + "iceConnectionState", + "iceGatheringState", + "iceTransport", + "icon", + "iconURL", + "id", + "identifier", + "identity", + "ideographicBaseline", + "idpLoginUrl", + "ignoreBOM", + "ignoreCase", + "ignoreDepthValues", + "image", + "image-orientation", + "image-rendering", + "imageHeight", + "imageOrientation", + "imageRendering", + "imageSizes", + "imageSmoothingEnabled", + "imageSmoothingQuality", + "imageSrcset", + "imageWidth", + "images", + "ime-mode", + "imeMode", + "implementation", + "importExternalTexture", + "importKey", + "importNode", + "importStylesheet", + "imports", + "impp", + "imul", + "in", + "in1", + "in2", + "inBandMetadataTrackDispatchType", + "inRange", + "includes", + "incomingBidirectionalStreams", + "incomingHighWaterMark", + "incomingMaxAge", + "incomingUnidirectionalStreams", + "incremental", + "indeterminate", + "index", + "indexNames", + "indexOf", + "indexedDB", + "indicate", + "indices", + "inert", + "inertiaDestinationX", + "inertiaDestinationY", + "info", + "inherits", + "init", + "initAnimationEvent", + "initBeforeLoadEvent", + "initClipboardEvent", + "initCloseEvent", + "initCommandEvent", + "initCompositionEvent", + "initCustomEvent", + "initData", + "initDataType", + "initDeviceMotionEvent", + "initDeviceOrientationEvent", + "initDragEvent", + "initErrorEvent", + "initEvent", + "initFocusEvent", + "initGestureEvent", + "initHashChangeEvent", + "initKeyEvent", + "initKeyboardEvent", + "initMSManipulationEvent", + "initMessageEvent", + "initMouseEvent", + "initMouseScrollEvent", + "initMouseWheelEvent", + "initMutationEvent", + "initNSMouseEvent", + "initOverflowEvent", + "initPageEvent", + "initPageTransitionEvent", + "initPointerEvent", + "initPopStateEvent", + "initProgressEvent", + "initScrollAreaEvent", + "initSimpleGestureEvent", + "initStorageEvent", + "initTextEvent", + "initTimeEvent", + "initTouchEvent", + "initTransitionEvent", + "initUIEvent", + "initWebKitAnimationEvent", + "initWebKitTransitionEvent", + "initWebKitWheelEvent", + "initWheelEvent", + "initialTime", + "initialValue", + "initialize", + "initiatorType", + "inject", + "ink", + "inline-size", + "inlineSize", + "inlineVerticalFieldOfView", + "inner", + "innerHTML", + "innerHeight", + "innerText", + "innerWidth", + "input", + "inputBuffer", + "inputEncoding", + "inputMethod", + "inputMode", + "inputSource", + "inputSources", + "inputType", + "inputs", + "insertAdjacentElement", + "insertAdjacentHTML", + "insertAdjacentText", + "insertBefore", + "insertCell", + "insertDTMF", + "insertData", + "insertDebugMarker", + "insertItemBefore", + "insertNode", + "insertRow", + "insertRule", + "inset", + "inset-block", + "inset-block-end", + "inset-block-start", + "inset-inline", + "inset-inline-end", + "inset-inline-start", + "insetBlock", + "insetBlockEnd", + "insetBlockStart", + "insetInline", + "insetInlineEnd", + "insetInlineStart", + "installing", + "instanceRoot", + "instantiate", + "instantiateStreaming", + "instruments", + "int16", + "int32", + "int8", + "integrity", + "interactionId", + "interactionMode", + "intercept", + "interfaceClass", + "interfaceName", + "interfaceNumber", + "interfaceProtocol", + "interfaceSubclass", + "interfaces", + "interimResults", + "internalSubset", + "interpretation", + "intersection", + "intersectionRatio", + "intersectionRect", + "intersectsNode", + "interval", + "invalidIteratorState", + "invalidateFramebuffer", + "invalidateSubFramebuffer", + "inverse", + "invertSelf", + "invoker", + "invokerType", + "is", + "is2D", + "isActive", + "isAlternate", + "isArray", + "isAutoSelected", + "isBingCurrentSearchDefault", + "isBuffer", + "isCandidateWindowVisible", + "isChar", + "isCollapsed", + "isComposing", + "isConcatSpreadable", + "isConditionalMediationAvailable", + "isConfigSupported", + "isConnected", + "isContentEditable", + "isContentHandlerRegistered", + "isContextLost", + "isDefaultNamespace", + "isDirectory", + "isDisabled", + "isDisjointFrom", + "isEnabled", + "isEqual", + "isEqualNode", + "isExtended", + "isExtensible", + "isExternalCTAP2SecurityKeySupported", + "isFallbackAdapter", + "isFile", + "isFinite", + "isFirstPersonObserver", + "isFramebuffer", + "isFrozen", + "isGenerator", + "isHTML", + "isHistoryNavigation", + "isId", + "isIdentity", + "isInjected", + "isInputPending", + "isInteger", + "isInternal", + "isIntersecting", + "isLockFree", + "isMap", + "isMultiLine", + "isNaN", + "isOpen", + "isPointInFill", + "isPointInPath", + "isPointInRange", + "isPointInStroke", + "isPrefAlternate", + "isPresenting", + "isPrimary", + "isProgram", + "isPropertyImplicit", + "isProtocolHandlerRegistered", + "isPrototypeOf", + "isQuery", + "isRawJSON", + "isRenderbuffer", + "isSafeInteger", + "isSameEntry", + "isSameNode", + "isSampler", + "isScript", + "isScriptURL", + "isSealed", + "isSecureContext", + "isSessionSupported", + "isShader", + "isSubsetOf", + "isSupersetOf", + "isSupported", + "isSync", + "isTextEdit", + "isTexture", + "isTransformFeedback", + "isTrusted", + "isTypeSupported", + "isUserVerifyingPlatformAuthenticatorAvailable", + "isVertexArray", + "isView", + "isVisible", + "isWellFormed", + "isochronousTransferIn", + "isochronousTransferOut", + "isolation", + "italics", + "item", + "itemId", + "itemProp", + "itemRef", + "itemScope", + "itemType", + "itemValue", + "items", + "iterateNext", + "iterationComposite", + "iterator", + "javaEnabled", + "jitterBufferTarget", + "jobTitle", + "join", + "joinAdInterestGroup", + "json", + "justify-content", + "justify-items", + "justify-self", + "justifyContent", + "justifyItems", + "justifySelf", + "k1", + "k2", + "k3", + "k4", + "kHz", + "keepalive", + "kernelMatrix", + "kernelUnitLengthX", + "kernelUnitLengthY", + "kerning", + "key", + "keyCode", + "keyFor", + "keyIdentifier", + "keyLightEnabled", + "keyLocation", + "keyPath", + "keyStatuses", + "keySystem", + "keyText", + "keyUsage", + "keyboard", + "keys", + "keytype", + "kind", + "knee", + "label", + "labels", + "lang", + "language", + "languages", + "largeArcFlag", + "lastChild", + "lastElementChild", + "lastEventId", + "lastIndex", + "lastIndexOf", + "lastInputTime", + "lastMatch", + "lastMessageSubject", + "lastMessageType", + "lastModified", + "lastModifiedDate", + "lastPage", + "lastParen", + "lastState", + "lastStyleSheetSet", + "latitude", + "launchQueue", + "layerName", + "layerX", + "layerY", + "layout", + "layoutFlow", + "layoutGrid", + "layoutGridChar", + "layoutGridLine", + "layoutGridMode", + "layoutGridType", + "lbound", + "leaveAdInterestGroup", + "left", + "leftContext", + "leftDegrees", + "leftMargin", + "leftProjectionMatrix", + "leftViewMatrix", + "length", + "lengthAdjust", + "lengthComputable", + "letter-spacing", + "letterSpacing", + "level", + "lh", + "lighting-color", + "lightingColor", + "limitingConeAngle", + "limits", + "line", + "line-break", + "line-height", + "lineAlign", + "lineBreak", + "lineCap", + "lineDashOffset", + "lineGapOverride", + "lineHeight", + "lineJoin", + "lineNum", + "lineNumber", + "linePos", + "lineTo", + "lineWidth", + "linearAcceleration", + "linearRampToValueAtTime", + "linearVelocity", + "lineno", + "lines", + "link", + "linkColor", + "linkProgram", + "links", + "list", + "list-style", + "list-style-image", + "list-style-position", + "list-style-type", + "listStyle", + "listStyleImage", + "listStylePosition", + "listStyleType", + "listener", + "listeners", + "load", + "loadEventEnd", + "loadEventStart", + "loadOp", + "loadTime", + "loadTimes", + "loaded", + "loading", + "localDescription", + "localName", + "localService", + "localStorage", + "locale", + "localeCompare", + "location", + "locationbar", + "lock", + "locked", + "lockedFile", + "locks", + "lodMaxClamp", + "lodMinClamp", + "log", + "log10", + "log1p", + "log2", + "logicalXDPI", + "logicalYDPI", + "login", + "loglevel", + "longDesc", + "longitude", + "lookupNamespaceURI", + "lookupPrefix", + "loop", + "loopEnd", + "loopStart", + "looping", + "lost", + "low", + "lower", + "lowerBound", + "lowerOpen", + "lowsrc", + "lvb", + "lvh", + "lvi", + "lvmax", + "lvmin", + "lvw", + "m11", + "m12", + "m13", + "m14", + "m21", + "m22", + "m23", + "m24", + "m31", + "m32", + "m33", + "m34", + "m41", + "m42", + "m43", + "m44", + "magFilter", + "makeXRCompatible", + "managed", + "manifest", + "manufacturer", + "manufacturerName", + "map", + "mapAsync", + "mapState", + "mappedAtCreation", + "mapping", + "margin", + "margin-block", + "margin-block-end", + "margin-block-start", + "margin-bottom", + "margin-inline", + "margin-inline-end", + "margin-inline-start", + "margin-left", + "margin-right", + "margin-top", + "marginBlock", + "marginBlockEnd", + "marginBlockStart", + "marginBottom", + "marginHeight", + "marginInline", + "marginInlineEnd", + "marginInlineStart", + "marginLeft", + "marginRight", + "marginTop", + "marginWidth", + "mark", + "marker", + "marker-end", + "marker-mid", + "marker-offset", + "marker-start", + "markerEnd", + "markerHeight", + "markerMid", + "markerOffset", + "markerStart", + "markerUnits", + "markerWidth", + "marks", + "mask", + "mask-clip", + "mask-composite", + "mask-image", + "mask-mode", + "mask-origin", + "mask-position", + "mask-position-x", + "mask-position-y", + "mask-repeat", + "mask-size", + "mask-type", + "maskClip", + "maskComposite", + "maskContentUnits", + "maskImage", + "maskMode", + "maskOrigin", + "maskPosition", + "maskPositionX", + "maskPositionY", + "maskRepeat", + "maskSize", + "maskType", + "maskUnits", + "match", + "matchAll", + "matchMedia", + "matchMedium", + "matches", + "math-depth", + "math-style", + "mathDepth", + "mathStyle", + "matrix", + "matrixTransform", + "max", + "max-block-size", + "max-height", + "max-inline-size", + "max-width", + "maxActions", + "maxAlternatives", + "maxAnisotropy", + "maxBindGroups", + "maxBindGroupsPlusVertexBuffers", + "maxBindingsPerBindGroup", + "maxBlockSize", + "maxBufferSize", + "maxByteLength", + "maxChannelCount", + "maxChannels", + "maxColorAttachmentBytesPerSample", + "maxColorAttachments", + "maxComputeInvocationsPerWorkgroup", + "maxComputeWorkgroupSizeX", + "maxComputeWorkgroupSizeY", + "maxComputeWorkgroupSizeZ", + "maxComputeWorkgroupStorageSize", + "maxComputeWorkgroupsPerDimension", + "maxConnectionsPerServer", + "maxDatagramSize", + "maxDecibels", + "maxDistance", + "maxDrawCount", + "maxDynamicStorageBuffersPerPipelineLayout", + "maxDynamicUniformBuffersPerPipelineLayout", + "maxHeight", + "maxInlineSize", + "maxInterStageShaderComponents", + "maxInterStageShaderVariables", + "maxLayers", + "maxLength", + "maxMessageSize", + "maxPacketLifeTime", + "maxRetransmits", + "maxSampledTexturesPerShaderStage", + "maxSamplersPerShaderStage", + "maxStorageBufferBindingSize", + "maxStorageBuffersPerShaderStage", + "maxStorageTexturesPerShaderStage", + "maxTextureArrayLayers", + "maxTextureDimension1D", + "maxTextureDimension2D", + "maxTextureDimension3D", + "maxTouchPoints", + "maxUniformBufferBindingSize", + "maxUniformBuffersPerShaderStage", + "maxValue", + "maxVertexAttributes", + "maxVertexBufferArrayStride", + "maxVertexBuffers", + "maxWidth", + "measure", + "measureText", + "media", + "mediaCapabilities", + "mediaDevices", + "mediaElement", + "mediaGroup", + "mediaKeys", + "mediaSession", + "mediaStream", + "mediaText", + "meetOrSlice", + "memory", + "menubar", + "mergeAttributes", + "message", + "messageClass", + "messageHandlers", + "messageType", + "messages", + "metaKey", + "metadata", + "method", + "methodDetails", + "methodName", + "mid", + "mimeType", + "mimeTypes", + "min", + "min-block-size", + "min-height", + "min-inline-size", + "min-width", + "minBindingSize", + "minBlockSize", + "minDecibels", + "minFilter", + "minHeight", + "minInlineSize", + "minLength", + "minStorageBufferOffsetAlignment", + "minUniformBufferOffsetAlignment", + "minValue", + "minWidth", + "mipLevel", + "mipLevelCount", + "mipmapFilter", + "miterLimit", + "mix-blend-mode", + "mixBlendMode", + "mm", + "mobile", + "mode", + "model", + "modify", + "module", + "mount", + "move", + "moveBy", + "moveEnd", + "moveFirst", + "moveFocusDown", + "moveFocusLeft", + "moveFocusRight", + "moveFocusUp", + "moveNext", + "moveRow", + "moveStart", + "moveTo", + "moveToBookmark", + "moveToElementText", + "moveToPoint", + "movementX", + "movementY", + "mozAdd", + "mozAnimationStartTime", + "mozAnon", + "mozApps", + "mozAudioCaptured", + "mozAudioChannelType", + "mozAutoplayEnabled", + "mozCancelAnimationFrame", + "mozCancelFullScreen", + "mozCancelRequestAnimationFrame", + "mozCaptureStream", + "mozCaptureStreamUntilEnded", + "mozClearDataAt", + "mozContact", + "mozContacts", + "mozCreateFileHandle", + "mozCurrentTransform", + "mozCurrentTransformInverse", + "mozCursor", + "mozDash", + "mozDashOffset", + "mozDecodedFrames", + "mozExitPointerLock", + "mozFillRule", + "mozFragmentEnd", + "mozFrameDelay", + "mozFullScreen", + "mozFullScreenElement", + "mozFullScreenEnabled", + "mozGetAll", + "mozGetAllKeys", + "mozGetAsFile", + "mozGetDataAt", + "mozGetMetadata", + "mozGetUserMedia", + "mozHasAudio", + "mozHasItem", + "mozHidden", + "mozImageSmoothingEnabled", + "mozIndexedDB", + "mozInnerScreenX", + "mozInnerScreenY", + "mozInputSource", + "mozIsTextField", + "mozItem", + "mozItemCount", + "mozItems", + "mozLength", + "mozLockOrientation", + "mozMatchesSelector", + "mozMovementX", + "mozMovementY", + "mozOpaque", + "mozOrientation", + "mozPaintCount", + "mozPaintedFrames", + "mozParsedFrames", + "mozPay", + "mozPointerLockElement", + "mozPresentedFrames", + "mozPreservesPitch", + "mozPressure", + "mozPrintCallback", + "mozRTCIceCandidate", + "mozRTCPeerConnection", + "mozRTCSessionDescription", + "mozRemove", + "mozRequestAnimationFrame", + "mozRequestFullScreen", + "mozRequestPointerLock", + "mozSetDataAt", + "mozSetImageElement", + "mozSourceNode", + "mozSrcObject", + "mozSystem", + "mozTCPSocket", + "mozTextStyle", + "mozTypesAt", + "mozUnlockOrientation", + "mozUserCancelled", + "mozVisibilityState", + "ms", + "msAnimation", + "msAnimationDelay", + "msAnimationDirection", + "msAnimationDuration", + "msAnimationFillMode", + "msAnimationIterationCount", + "msAnimationName", + "msAnimationPlayState", + "msAnimationStartTime", + "msAnimationTimingFunction", + "msBackfaceVisibility", + "msBlockProgression", + "msCSSOMElementFloatMetrics", + "msCaching", + "msCachingEnabled", + "msCancelRequestAnimationFrame", + "msCapsLockWarningOff", + "msClearImmediate", + "msClose", + "msContentZoomChaining", + "msContentZoomFactor", + "msContentZoomLimit", + "msContentZoomLimitMax", + "msContentZoomLimitMin", + "msContentZoomSnap", + "msContentZoomSnapPoints", + "msContentZoomSnapType", + "msContentZooming", + "msConvertURL", + "msCrypto", + "msDoNotTrack", + "msElementsFromPoint", + "msElementsFromRect", + "msExitFullscreen", + "msExtendedCode", + "msFillRule", + "msFirstPaint", + "msFlex", + "msFlexAlign", + "msFlexDirection", + "msFlexFlow", + "msFlexItemAlign", + "msFlexLinePack", + "msFlexNegative", + "msFlexOrder", + "msFlexPack", + "msFlexPositive", + "msFlexPreferredSize", + "msFlexWrap", + "msFlowFrom", + "msFlowInto", + "msFontFeatureSettings", + "msFullscreenElement", + "msFullscreenEnabled", + "msGetInputContext", + "msGetRegionContent", + "msGetUntransformedBounds", + "msGraphicsTrustStatus", + "msGridColumn", + "msGridColumnAlign", + "msGridColumnSpan", + "msGridColumns", + "msGridRow", + "msGridRowAlign", + "msGridRowSpan", + "msGridRows", + "msHidden", + "msHighContrastAdjust", + "msHyphenateLimitChars", + "msHyphenateLimitLines", + "msHyphenateLimitZone", + "msHyphens", + "msImageSmoothingEnabled", + "msImeAlign", + "msIndexedDB", + "msInterpolationMode", + "msIsStaticHTML", + "msKeySystem", + "msKeys", + "msLaunchUri", + "msLockOrientation", + "msManipulationViewsEnabled", + "msMatchMedia", + "msMatchesSelector", + "msMaxTouchPoints", + "msOrientation", + "msOverflowStyle", + "msPerspective", + "msPerspectiveOrigin", + "msPlayToDisabled", + "msPlayToPreferredSourceUri", + "msPlayToPrimary", + "msPointerEnabled", + "msRegionOverflow", + "msReleasePointerCapture", + "msRequestAnimationFrame", + "msRequestFullscreen", + "msSaveBlob", + "msSaveOrOpenBlob", + "msScrollChaining", + "msScrollLimit", + "msScrollLimitXMax", + "msScrollLimitXMin", + "msScrollLimitYMax", + "msScrollLimitYMin", + "msScrollRails", + "msScrollSnapPointsX", + "msScrollSnapPointsY", + "msScrollSnapType", + "msScrollSnapX", + "msScrollSnapY", + "msScrollTranslation", + "msSetImmediate", + "msSetMediaKeys", + "msSetPointerCapture", + "msTextCombineHorizontal", + "msTextSizeAdjust", + "msToBlob", + "msTouchAction", + "msTouchSelect", + "msTraceAsyncCallbackCompleted", + "msTraceAsyncCallbackStarting", + "msTraceAsyncOperationCompleted", + "msTraceAsyncOperationStarting", + "msTransform", + "msTransformOrigin", + "msTransformStyle", + "msTransition", + "msTransitionDelay", + "msTransitionDuration", + "msTransitionProperty", + "msTransitionTimingFunction", + "msUnlockOrientation", + "msUpdateAsyncCallbackRelation", + "msUserSelect", + "msVisibilityState", + "msWrapFlow", + "msWrapMargin", + "msWrapThrough", + "msWriteProfilerMark", + "msZoom", + "msZoomTo", + "mt", + "mul", + "multiEntry", + "multiSelectionObj", + "multiline", + "multiple", + "multiply", + "multiplySelf", + "multisample", + "multisampled", + "mutableFile", + "muted", + "n", + "name", + "nameList", + "nameProp", + "namedItem", + "namedRecordset", + "names", + "namespaceURI", + "namespaces", + "nativeMap", + "nativeObjectCreate", + "nativeSet", + "nativeWeakMap", + "naturalHeight", + "naturalWidth", + "navigate", + "navigation", + "navigationMode", + "navigationPreload", + "navigationStart", + "navigationType", + "navigator", + "near", + "nearestViewportElement", + "negative", + "negotiated", + "netscape", + "networkState", + "newScale", + "newState", + "newTranslate", + "newURL", + "newValue", + "newValueSpecifiedUnits", + "newVersion", + "newhome", + "next", + "nextElementSibling", + "nextHopProtocol", + "nextNode", + "nextPage", + "nextSibling", + "nickname", + "noHref", + "noModule", + "noResize", + "noShade", + "noValidate", + "noWrap", + "node", + "nodeName", + "nodeType", + "nodeValue", + "nonce", + "normDepthBufferFromNormView", + "normalize", + "normalizedPathSegList", + "notRestoredReasons", + "notationName", + "notations", + "note", + "noteGrainOn", + "noteOff", + "noteOn", + "notify", + "now", + "numOctaves", + "number", + "numberOfChannels", + "numberOfFrames", + "numberOfInputs", + "numberOfItems", + "numberOfOutputs", + "numberValue", + "oMatchesSelector", + "object", + "object-fit", + "object-position", + "objectFit", + "objectPosition", + "objectStore", + "objectStoreNames", + "objectType", + "observe", + "occlusionQuerySet", + "of", + "off", + "offscreenBuffering", + "offset", + "offset-anchor", + "offset-distance", + "offset-path", + "offset-position", + "offset-rotate", + "offsetAnchor", + "offsetDistance", + "offsetHeight", + "offsetLeft", + "offsetNode", + "offsetParent", + "offsetPath", + "offsetPosition", + "offsetRotate", + "offsetTop", + "offsetWidth", + "offsetX", + "offsetY", + "ok", + "oldState", + "oldURL", + "oldValue", + "oldVersion", + "olderShadowRoot", + "on", + "onCommitFiberRoot", + "onCommitFiberUnmount", + "onLine", + "onPostCommitFiberRoot", + "onSubmittedWorkDone", + "onabort", + "onabsolutedeviceorientation", + "onactivate", + "onactive", + "onaddsourcebuffer", + "onaddstream", + "onaddtrack", + "onafterprint", + "onafterscriptexecute", + "onafterupdate", + "onanimationcancel", + "onanimationend", + "onanimationiteration", + "onanimationstart", + "onappinstalled", + "onaudioend", + "onaudioprocess", + "onaudiostart", + "onautocomplete", + "onautocompleteerror", + "onauxclick", + "onbeforeactivate", + "onbeforecopy", + "onbeforecut", + "onbeforedeactivate", + "onbeforeeditfocus", + "onbeforeinput", + "onbeforeinstallprompt", + "onbeforematch", + "onbeforepaste", + "onbeforeprint", + "onbeforescriptexecute", + "onbeforetoggle", + "onbeforeunload", + "onbeforeupdate", + "onbeforexrselect", + "onbegin", + "onblocked", + "onblur", + "onbounce", + "onboundary", + "onbufferedamountlow", + "oncached", + "oncancel", + "oncandidatewindowhide", + "oncandidatewindowshow", + "oncandidatewindowupdate", + "oncanplay", + "oncanplaythrough", + "oncapturehandlechange", + "once", + "oncellchange", + "onchange", + "oncharacterboundsupdate", + "oncharacteristicvaluechanged", + "onchargingchange", + "onchargingtimechange", + "onchecking", + "onclick", + "onclose", + "onclosing", + "oncompassneedscalibration", + "oncomplete", + "oncompositionend", + "oncompositionstart", + "onconnect", + "onconnecting", + "onconnectionavailable", + "onconnectionstatechange", + "oncontentvisibilityautostatechange", + "oncontextlost", + "oncontextmenu", + "oncontextrestored", + "oncontrollerchange", + "oncontrolselect", + "oncopy", + "oncuechange", + "oncurrententrychange", + "oncurrentscreenchange", + "oncut", + "ondataavailable", + "ondatachannel", + "ondatasetchanged", + "ondatasetcomplete", + "ondblclick", + "ondeactivate", + "ondequeue", + "ondevicechange", + "ondevicelight", + "ondevicemotion", + "ondeviceorientation", + "ondeviceorientationabsolute", + "ondeviceproximity", + "ondischargingtimechange", + "ondisconnect", + "ondisplay", + "ondispose", + "ondownloading", + "ondrag", + "ondragend", + "ondragenter", + "ondragexit", + "ondragleave", + "ondragover", + "ondragstart", + "ondrop", + "ondurationchange", + "onemptied", + "onencrypted", + "onend", + "onended", + "onenter", + "onenterpictureinpicture", + "onerror", + "onerrorupdate", + "onexit", + "onfencedtreeclick", + "onfilterchange", + "onfinish", + "onfocus", + "onfocusin", + "onfocusout", + "onformdata", + "onfreeze", + "onfullscreenchange", + "onfullscreenerror", + "ongamepadconnected", + "ongamepaddisconnected", + "ongatheringstatechange", + "ongattserverdisconnected", + "ongeometrychange", + "ongesturechange", + "ongestureend", + "ongesturestart", + "ongotpointercapture", + "onhashchange", + "onhelp", + "onicecandidate", + "onicecandidateerror", + "oniceconnectionstatechange", + "onicegatheringstatechange", + "oninactive", + "oninput", + "oninputreport", + "oninputsourceschange", + "oninvalid", + "onkeydown", + "onkeypress", + "onkeystatuseschange", + "onkeyup", + "onlanguagechange", + "onlayoutcomplete", + "onleavepictureinpicture", + "onlevelchange", + "onload", + "onloadeddata", + "onloadedmetadata", + "onloadend", + "onloading", + "onloadingdone", + "onloadingerror", + "onloadstart", + "onlosecapture", + "onlostpointercapture", + "only", + "onmanagedconfigurationchange", + "onmark", + "onmessage", + "onmessageerror", + "onmidimessage", + "onmousedown", + "onmouseenter", + "onmouseleave", + "onmousemove", + "onmouseout", + "onmouseover", + "onmouseup", + "onmousewheel", + "onmove", + "onmoveend", + "onmovestart", + "onmozfullscreenchange", + "onmozfullscreenerror", + "onmozorientationchange", + "onmozpointerlockchange", + "onmozpointerlockerror", + "onmscontentzoom", + "onmsfullscreenchange", + "onmsfullscreenerror", + "onmsgesturechange", + "onmsgesturedoubletap", + "onmsgestureend", + "onmsgesturehold", + "onmsgesturestart", + "onmsgesturetap", + "onmsgotpointercapture", + "onmsinertiastart", + "onmslostpointercapture", + "onmsmanipulationstatechanged", + "onmsneedkey", + "onmsorientationchange", + "onmspointercancel", + "onmspointerdown", + "onmspointerenter", + "onmspointerhover", + "onmspointerleave", + "onmspointermove", + "onmspointerout", + "onmspointerover", + "onmspointerup", + "onmssitemodejumplistitemremoved", + "onmsthumbnailclick", + "onmute", + "onnavigate", + "onnavigateerror", + "onnavigatesuccess", + "onnegotiationneeded", + "onnomatch", + "onnoupdate", + "onobsolete", + "onoffline", + "ononline", + "onopen", + "onorientationchange", + "onpagechange", + "onpagehide", + "onpagereveal", + "onpageshow", + "onpageswap", + "onpaste", + "onpause", + "onpayerdetailchange", + "onpaymentmethodchange", + "onplay", + "onplaying", + "onpluginstreamstart", + "onpointercancel", + "onpointerdown", + "onpointerenter", + "onpointerleave", + "onpointerlockchange", + "onpointerlockerror", + "onpointermove", + "onpointerout", + "onpointerover", + "onpointerrawupdate", + "onpointerup", + "onpopstate", + "onprerenderingchange", + "onprioritychange", + "onprocessorerror", + "onprogress", + "onpropertychange", + "onratechange", + "onreading", + "onreadystatechange", + "onreflectionchange", + "onrejectionhandled", + "onrelease", + "onremove", + "onremovesourcebuffer", + "onremovestream", + "onremovetrack", + "onrepeat", + "onreset", + "onresize", + "onresizeend", + "onresizestart", + "onresourcetimingbufferfull", + "onresult", + "onresume", + "onrowenter", + "onrowexit", + "onrowsdelete", + "onrowsinserted", + "onscreenschange", + "onscroll", + "onscrollend", + "onsearch", + "onsecuritypolicyviolation", + "onseeked", + "onseeking", + "onselect", + "onselectedcandidatepairchange", + "onselectend", + "onselectionchange", + "onselectstart", + "onshippingaddresschange", + "onshippingoptionchange", + "onshow", + "onsignalingstatechange", + "onsinkchange", + "onslotchange", + "onsoundend", + "onsoundstart", + "onsourceclose", + "onsourceclosed", + "onsourceended", + "onsourceopen", + "onspeechend", + "onspeechstart", + "onsqueeze", + "onsqueezeend", + "onsqueezestart", + "onstalled", + "onstart", + "onstatechange", + "onstop", + "onstorage", + "onstoragecommit", + "onsubmit", + "onsuccess", + "onsuspend", + "onterminate", + "ontextformatupdate", + "ontextinput", + "ontextupdate", + "ontimeout", + "ontimeupdate", + "ontoggle", + "ontonechange", + "ontouchcancel", + "ontouchend", + "ontouchmove", + "ontouchstart", + "ontrack", + "ontransitioncancel", + "ontransitionend", + "ontransitionrun", + "ontransitionstart", + "onuncapturederror", + "onunhandledrejection", + "onunload", + "onunmute", + "onupdate", + "onupdateend", + "onupdatefound", + "onupdateready", + "onupdatestart", + "onupgradeneeded", + "onuserproximity", + "onversionchange", + "onvisibilitychange", + "onvoiceschanged", + "onvolumechange", + "onvrdisplayactivate", + "onvrdisplayconnect", + "onvrdisplaydeactivate", + "onvrdisplaydisconnect", + "onvrdisplaypresentchange", + "onwaiting", + "onwaitingforkey", + "onwarning", + "onwebkitanimationend", + "onwebkitanimationiteration", + "onwebkitanimationstart", + "onwebkitcurrentplaybacktargetiswirelesschanged", + "onwebkitfullscreenchange", + "onwebkitfullscreenerror", + "onwebkitkeyadded", + "onwebkitkeyerror", + "onwebkitkeymessage", + "onwebkitneedkey", + "onwebkitorientationchange", + "onwebkitplaybacktargetavailabilitychanged", + "onwebkitpointerlockchange", + "onwebkitpointerlockerror", + "onwebkitresourcetimingbufferfull", + "onwebkittransitionend", + "onwheel", + "onzoom", + "opacity", + "open", + "openCursor", + "openDatabase", + "openKeyCursor", + "opened", + "opener", + "opera", + "operation", + "operationType", + "operator", + "opr", + "optimum", + "options", + "or", + "order", + "orderX", + "orderY", + "ordered", + "org", + "organization", + "orient", + "orientAngle", + "orientType", + "orientation", + "orientationX", + "orientationY", + "orientationZ", + "origin", + "originAgentCluster", + "originalPolicy", + "originalTarget", + "orphans", + "oscpu", + "outerHTML", + "outerHeight", + "outerText", + "outerWidth", + "outgoingHighWaterMark", + "outgoingMaxAge", + "outline", + "outline-color", + "outline-offset", + "outline-style", + "outline-width", + "outlineColor", + "outlineOffset", + "outlineStyle", + "outlineWidth", + "outputBuffer", + "outputChannelCount", + "outputLatency", + "outputs", + "overflow", + "overflow-anchor", + "overflow-block", + "overflow-clip-margin", + "overflow-inline", + "overflow-wrap", + "overflow-x", + "overflow-y", + "overflowAnchor", + "overflowBlock", + "overflowClipMargin", + "overflowInline", + "overflowWrap", + "overflowX", + "overflowY", + "overlaysContent", + "overrideColors", + "overrideMimeType", + "oversample", + "overscroll-behavior", + "overscroll-behavior-block", + "overscroll-behavior-inline", + "overscroll-behavior-x", + "overscroll-behavior-y", + "overscrollBehavior", + "overscrollBehaviorBlock", + "overscrollBehaviorInline", + "overscrollBehaviorX", + "overscrollBehaviorY", + "ownKeys", + "ownerDocument", + "ownerElement", + "ownerNode", + "ownerRule", + "ownerSVGElement", + "owningElement", + "p1", + "p2", + "p3", + "p4", + "packetSize", + "packets", + "pad", + "padEnd", + "padStart", + "padding", + "padding-block", + "padding-block-end", + "padding-block-start", + "padding-bottom", + "padding-inline", + "padding-inline-end", + "padding-inline-start", + "padding-left", + "padding-right", + "padding-top", + "paddingBlock", + "paddingBlockEnd", + "paddingBlockStart", + "paddingBottom", + "paddingInline", + "paddingInlineEnd", + "paddingInlineStart", + "paddingLeft", + "paddingRight", + "paddingTop", + "page", + "page-break-after", + "page-break-before", + "page-break-inside", + "pageBreakAfter", + "pageBreakBefore", + "pageBreakInside", + "pageCount", + "pageLeft", + "pageTop", + "pageX", + "pageXOffset", + "pageY", + "pageYOffset", + "pages", + "paint-order", + "paintOrder", + "paintRequests", + "paintType", + "paintWorklet", + "palette", + "pan", + "panningModel", + "parameterData", + "parameters", + "parent", + "parentElement", + "parentNode", + "parentRule", + "parentStyleSheet", + "parentTextEdit", + "parentWindow", + "parse", + "parseAll", + "parseCreationOptionsFromJSON", + "parseFloat", + "parseFromString", + "parseHTMLUnsafe", + "parseInt", + "parseRequestOptionsFromJSON", + "part", + "participants", + "passOp", + "passive", + "password", + "pasteHTML", + "path", + "pathLength", + "pathSegList", + "pathSegType", + "pathSegTypeAsLetter", + "pathname", + "pattern", + "patternContentUnits", + "patternMismatch", + "patternTransform", + "patternUnits", + "pause", + "pauseAnimations", + "pauseDuration", + "pauseOnExit", + "pauseProfilers", + "pauseTransformFeedback", + "paused", + "payerEmail", + "payerName", + "payerPhone", + "paymentManager", + "pc", + "pdfViewerEnabled", + "peerIdentity", + "pending", + "pendingLocalDescription", + "pendingRemoteDescription", + "percent", + "performance", + "periodicSync", + "permission", + "permissionState", + "permissions", + "persist", + "persisted", + "personalbar", + "perspective", + "perspective-origin", + "perspectiveOrigin", + "phone", + "phoneticFamilyName", + "phoneticGivenName", + "photo", + "pictureInPictureElement", + "pictureInPictureEnabled", + "pictureInPictureWindow", + "ping", + "pipeThrough", + "pipeTo", + "pitch", + "pixelBottom", + "pixelDepth", + "pixelHeight", + "pixelLeft", + "pixelRight", + "pixelStorei", + "pixelTop", + "pixelUnitToMillimeterX", + "pixelUnitToMillimeterY", + "pixelWidth", + "place-content", + "place-items", + "place-self", + "placeContent", + "placeItems", + "placeSelf", + "placeholder", + "platform", + "platformVersion", + "platforms", + "play", + "playEffect", + "playState", + "playbackRate", + "playbackState", + "playbackTime", + "played", + "playoutDelayHint", + "playsInline", + "plugins", + "pluginspage", + "pname", + "pointer-events", + "pointerBeforeReferenceNode", + "pointerEnabled", + "pointerEvents", + "pointerId", + "pointerLockElement", + "pointerType", + "points", + "pointsAtX", + "pointsAtY", + "pointsAtZ", + "polygonOffset", + "pop", + "popDebugGroup", + "popErrorScope", + "popover", + "popoverTargetAction", + "popoverTargetElement", + "populateMatrix", + "popupWindowFeatures", + "popupWindowName", + "popupWindowURI", + "port", + "port1", + "port2", + "ports", + "posBottom", + "posHeight", + "posLeft", + "posRight", + "posTop", + "posWidth", + "pose", + "position", + "positionAlign", + "positionX", + "positionY", + "positionZ", + "postError", + "postMessage", + "postTask", + "postalCode", + "poster", + "postscriptName", + "pow", + "powerEfficient", + "powerOff", + "powerPreference", + "preMultiplySelf", + "precision", + "preferredReflectionFormat", + "preferredStyleSheetSet", + "preferredStylesheetSet", + "prefix", + "preload", + "premultipliedAlpha", + "prepend", + "prerendering", + "presentation", + "presentationArea", + "preserveAlpha", + "preserveAspectRatio", + "preserveAspectRatioString", + "preservesPitch", + "pressed", + "pressure", + "prevValue", + "preventDefault", + "preventExtensions", + "preventSilentAccess", + "previousElementSibling", + "previousNode", + "previousPage", + "previousPriority", + "previousRect", + "previousScale", + "previousSibling", + "previousTranslate", + "primaries", + "primaryKey", + "primaryLightDirection", + "primaryLightIntensity", + "primitive", + "primitiveType", + "primitiveUnits", + "principals", + "print", + "print-color-adjust", + "printColorAdjust", + "priority", + "privateKey", + "privateToken", + "probablySupportsContext", + "probeSpace", + "process", + "processIceMessage", + "processingEnd", + "processingStart", + "processorOptions", + "product", + "productId", + "productName", + "productSub", + "profile", + "profileEnd", + "profiles", + "projectionMatrix", + "promise", + "prompt", + "properties", + "propertyIsEnumerable", + "propertyName", + "protocol", + "protocolLong", + "prototype", + "provider", + "pseudoClass", + "pseudoElement", + "pt", + "publicId", + "publicKey", + "published", + "pulse", + "push", + "pushDebugGroup", + "pushErrorScope", + "pushManager", + "pushNotification", + "pushState", + "put", + "putImageData", + "px", + "quadraticCurveTo", + "qualifier", + "quaternion", + "query", + "queryCommandEnabled", + "queryCommandIndeterm", + "queryCommandState", + "queryCommandSupported", + "queryCommandText", + "queryCommandValue", + "queryLocalFonts", + "queryPermission", + "querySelector", + "querySelectorAll", + "querySet", + "queue", + "queueMicrotask", + "quote", + "quotes", + "r", + "r1", + "r2", + "race", + "rad", + "radiogroup", + "radiusX", + "radiusY", + "random", + "randomUUID", + "range", + "rangeCount", + "rangeEnd", + "rangeMax", + "rangeMin", + "rangeOffset", + "rangeOverflow", + "rangeParent", + "rangeStart", + "rangeUnderflow", + "rate", + "ratio", + "raw", + "rawId", + "rawJSON", + "rawValueToMeters", + "rcap", + "rch", + "read", + "readAsArrayBuffer", + "readAsBinaryString", + "readAsBlob", + "readAsDataURL", + "readAsText", + "readBuffer", + "readEntries", + "readOnly", + "readPixels", + "readReportRequested", + "readText", + "readValue", + "readable", + "ready", + "readyState", + "reason", + "reasons", + "reboot", + "receiveFeatureReport", + "receivedAlert", + "receiver", + "receivers", + "recipient", + "recommendedViewportScale", + "reconnect", + "recordNumber", + "recordsAvailable", + "recordset", + "rect", + "red", + "redEyeReduction", + "redirect", + "redirectCount", + "redirectEnd", + "redirectStart", + "redirected", + "reduce", + "reduceRight", + "reduction", + "refDistance", + "refX", + "refY", + "referenceNode", + "referenceSpace", + "referrer", + "referrerPolicy", + "refresh", + "region", + "regionAnchorX", + "regionAnchorY", + "regionId", + "regions", + "register", + "registerContentHandler", + "registerElement", + "registerInternalModuleStart", + "registerInternalModuleStop", + "registerProperty", + "registerProtocolHandler", + "reject", + "rel", + "relList", + "relatedAddress", + "relatedNode", + "relatedPort", + "relatedTarget", + "relayProtocol", + "release", + "releaseCapture", + "releaseEvents", + "releaseInterface", + "releaseLock", + "releasePointerCapture", + "releaseShaderCompiler", + "released", + "reliability", + "reliable", + "reliableWrite", + "reload", + "rem", + "remainingSpace", + "remote", + "remoteDescription", + "remove", + "removeAllRanges", + "removeAttribute", + "removeAttributeNS", + "removeAttributeNode", + "removeBehavior", + "removeChild", + "removeCue", + "removeEntry", + "removeEventListener", + "removeFilter", + "removeImport", + "removeItem", + "removeListener", + "removeNamedItem", + "removeNamedItemNS", + "removeNode", + "removeParameter", + "removeProperty", + "removeRange", + "removeRegion", + "removeRule", + "removeSiteSpecificTrackingException", + "removeSourceBuffer", + "removeStream", + "removeTrack", + "removeVariable", + "removeWakeLockListener", + "removeWebWideTrackingException", + "removed", + "removedNodes", + "renderBlockingStatus", + "renderHeight", + "renderStart", + "renderState", + "renderTime", + "renderWidth", + "renderbufferStorage", + "renderbufferStorageMultisample", + "renderedBuffer", + "rendererInterfaces", + "renderers", + "renderingMode", + "renotify", + "repeat", + "repetitionCount", + "replace", + "replaceAdjacentText", + "replaceAll", + "replaceChild", + "replaceChildren", + "replaceData", + "replaceId", + "replaceItem", + "replaceNode", + "replaceState", + "replaceSync", + "replaceTrack", + "replaceWholeText", + "replaceWith", + "reportError", + "reportEvent", + "reportId", + "reportValidity", + "request", + "requestAdapter", + "requestAdapterInfo", + "requestAnimationFrame", + "requestAutocomplete", + "requestData", + "requestDevice", + "requestFrame", + "requestFullscreen", + "requestHitTestSource", + "requestHitTestSourceForTransientInput", + "requestId", + "requestIdleCallback", + "requestLightProbe", + "requestMIDIAccess", + "requestMediaKeySystemAccess", + "requestPermission", + "requestPictureInPicture", + "requestPointerLock", + "requestPort", + "requestPresent", + "requestPresenter", + "requestReferenceSpace", + "requestSession", + "requestStart", + "requestStorageAccess", + "requestStorageAccessFor", + "requestSubmit", + "requestVideoFrameCallback", + "requestViewportScale", + "requestWindow", + "requestingWindow", + "requireInteraction", + "required", + "requiredExtensions", + "requiredFeatures", + "requiredLimits", + "reset", + "resetPose", + "resetTransform", + "resizable", + "resize", + "resizeBy", + "resizeTo", + "resolve", + "resolveQuerySet", + "resolveTarget", + "resource", + "respond", + "respondWithNewView", + "response", + "responseBody", + "responseEnd", + "responseReady", + "responseStart", + "responseStatus", + "responseText", + "responseType", + "responseURL", + "responseXML", + "restartIce", + "restore", + "result", + "resultIndex", + "resultType", + "results", + "resume", + "resumeProfilers", + "resumeTransformFeedback", + "retry", + "returnValue", + "rev", + "reverse", + "reversed", + "revocable", + "revokeObjectURL", + "rex", + "rgbColor", + "ric", + "right", + "rightContext", + "rightDegrees", + "rightMargin", + "rightProjectionMatrix", + "rightViewMatrix", + "rlh", + "role", + "rolloffFactor", + "root", + "rootBounds", + "rootElement", + "rootMargin", + "rotate", + "rotateAxisAngle", + "rotateAxisAngleSelf", + "rotateFromVector", + "rotateFromVectorSelf", + "rotateSelf", + "rotation", + "rotationAngle", + "rotationRate", + "round", + "roundRect", + "row-gap", + "rowGap", + "rowIndex", + "rowSpan", + "rows", + "rowsPerImage", + "rtcpTransport", + "rtt", + "ruby-align", + "ruby-position", + "rubyAlign", + "rubyOverhang", + "rubyPosition", + "rules", + "run", + "runAdAuction", + "runtime", + "runtimeStyle", + "rx", + "ry", + "s", + "safari", + "sameDocument", + "sample", + "sampleCount", + "sampleCoverage", + "sampleInterval", + "sampleRate", + "sampleType", + "sampler", + "samplerParameterf", + "samplerParameteri", + "sandbox", + "save", + "saveData", + "scale", + "scale3d", + "scale3dSelf", + "scaleNonUniform", + "scaleNonUniformSelf", + "scaleSelf", + "scheduler", + "scheduling", + "scheme", + "scissor", + "scope", + "scopeName", + "scoped", + "screen", + "screenBrightness", + "screenEnabled", + "screenLeft", + "screenPixelToMillimeterX", + "screenPixelToMillimeterY", + "screenState", + "screenTop", + "screenX", + "screenY", + "screens", + "scriptURL", + "scripts", + "scroll", + "scroll-behavior", + "scroll-margin", + "scroll-margin-block", + "scroll-margin-block-end", + "scroll-margin-block-start", + "scroll-margin-bottom", + "scroll-margin-inline", + "scroll-margin-inline-end", + "scroll-margin-inline-start", + "scroll-margin-left", + "scroll-margin-right", + "scroll-margin-top", + "scroll-padding", + "scroll-padding-block", + "scroll-padding-block-end", + "scroll-padding-block-start", + "scroll-padding-bottom", + "scroll-padding-inline", + "scroll-padding-inline-end", + "scroll-padding-inline-start", + "scroll-padding-left", + "scroll-padding-right", + "scroll-padding-top", + "scroll-snap-align", + "scroll-snap-stop", + "scroll-snap-type", + "scrollAmount", + "scrollBehavior", + "scrollBy", + "scrollByLines", + "scrollByPages", + "scrollDelay", + "scrollHeight", + "scrollIntoView", + "scrollIntoViewIfNeeded", + "scrollLeft", + "scrollLeftMax", + "scrollMargin", + "scrollMarginBlock", + "scrollMarginBlockEnd", + "scrollMarginBlockStart", + "scrollMarginBottom", + "scrollMarginInline", + "scrollMarginInlineEnd", + "scrollMarginInlineStart", + "scrollMarginLeft", + "scrollMarginRight", + "scrollMarginTop", + "scrollMaxX", + "scrollMaxY", + "scrollPadding", + "scrollPaddingBlock", + "scrollPaddingBlockEnd", + "scrollPaddingBlockStart", + "scrollPaddingBottom", + "scrollPaddingInline", + "scrollPaddingInlineEnd", + "scrollPaddingInlineStart", + "scrollPaddingLeft", + "scrollPaddingRight", + "scrollPaddingTop", + "scrollRestoration", + "scrollSnapAlign", + "scrollSnapStop", + "scrollSnapType", + "scrollTo", + "scrollTop", + "scrollTopMax", + "scrollWidth", + "scrollX", + "scrollY", + "scrollbar-color", + "scrollbar-gutter", + "scrollbar-width", + "scrollbar3dLightColor", + "scrollbarArrowColor", + "scrollbarBaseColor", + "scrollbarColor", + "scrollbarDarkShadowColor", + "scrollbarFaceColor", + "scrollbarGutter", + "scrollbarHighlightColor", + "scrollbarShadowColor", + "scrollbarTrackColor", + "scrollbarWidth", + "scrollbars", + "scrolling", + "scrollingElement", + "sctp", + "sctpCauseCode", + "sdp", + "sdpLineNumber", + "sdpMLineIndex", + "sdpMid", + "seal", + "search", + "searchBox", + "searchBoxJavaBridge_", + "searchParams", + "sectionRowIndex", + "secureConnectionStart", + "security", + "seed", + "seek", + "seekToNextFrame", + "seekable", + "seeking", + "select", + "selectAllChildren", + "selectAlternateInterface", + "selectAudioOutput", + "selectConfiguration", + "selectNode", + "selectNodeContents", + "selectNodes", + "selectSingleNode", + "selectSubString", + "selectURL", + "selected", + "selectedIndex", + "selectedOptions", + "selectedStyleSheetSet", + "selectedStylesheetSet", + "selectedTrack", + "selection", + "selectionDirection", + "selectionEnd", + "selectionStart", + "selector", + "selectorText", + "self", + "send", + "sendAsBinary", + "sendBeacon", + "sendFeatureReport", + "sendOrder", + "sendReport", + "sender", + "sentAlert", + "sentTimestamp", + "separator", + "serial", + "serialNumber", + "serializeToString", + "serverTiming", + "service", + "serviceWorker", + "session", + "sessionId", + "sessionStorage", + "set", + "setActionHandler", + "setActive", + "setAlpha", + "setAppBadge", + "setAttribute", + "setAttributeNS", + "setAttributeNode", + "setAttributeNodeNS", + "setAttributionReporting", + "setBaseAndExtent", + "setBigInt64", + "setBigUint64", + "setBindGroup", + "setBingCurrentSearchDefault", + "setBlendConstant", + "setCameraActive", + "setCapture", + "setCaptureHandleConfig", + "setCodecPreferences", + "setColor", + "setCompositeOperation", + "setConfiguration", + "setConsumer", + "setCurrentTime", + "setCustomValidity", + "setData", + "setDate", + "setDragImage", + "setEnd", + "setEndAfter", + "setEndBefore", + "setEndPoint", + "setExpires", + "setFillColor", + "setFilterRes", + "setFloat32", + "setFloat64", + "setFloatValue", + "setFocusBehavior", + "setFormValue", + "setFullYear", + "setHTMLUnsafe", + "setHeaderExtensionsToNegotiate", + "setHeaderValue", + "setHours", + "setIdentityProvider", + "setImmediate", + "setIndexBuffer", + "setInt16", + "setInt32", + "setInt8", + "setInterval", + "setItem", + "setKeyframes", + "setLineCap", + "setLineDash", + "setLineJoin", + "setLineWidth", + "setLiveSeekableRange", + "setLocalDescription", + "setMatrix", + "setMatrixValue", + "setMediaKeys", + "setMicrophoneActive", + "setMilliseconds", + "setMinutes", + "setMiterLimit", + "setMonth", + "setNamedItem", + "setNamedItemNS", + "setNonUserCodeExceptions", + "setOrientToAngle", + "setOrientToAuto", + "setOrientation", + "setOverrideHistoryNavigationMode", + "setPaint", + "setParameter", + "setParameters", + "setPeriodicWave", + "setPipeline", + "setPointerCapture", + "setPosition", + "setPositionState", + "setPreference", + "setPriority", + "setPrivateToken", + "setProperty", + "setPrototypeOf", + "setRGBColor", + "setRGBColorICCColor", + "setRadius", + "setRangeText", + "setRemoteDescription", + "setReportEventDataForAutomaticBeacons", + "setRequestHeader", + "setResizable", + "setResourceTimingBufferSize", + "setRotate", + "setScale", + "setScissorRect", + "setSeconds", + "setSelectionRange", + "setServerCertificate", + "setShadow", + "setSharedStorageContext", + "setSignals", + "setSinkId", + "setSkewX", + "setSkewY", + "setStart", + "setStartAfter", + "setStartBefore", + "setStatus", + "setStdDeviation", + "setStencilReference", + "setStreams", + "setStrictMode", + "setStringValue", + "setStrokeColor", + "setSuggestResult", + "setTargetAtTime", + "setTargetValueAtTime", + "setTime", + "setTimeout", + "setTransform", + "setTranslate", + "setUTCDate", + "setUTCFullYear", + "setUTCHours", + "setUTCMilliseconds", + "setUTCMinutes", + "setUTCMonth", + "setUTCSeconds", + "setUint16", + "setUint32", + "setUint8", + "setUri", + "setValidity", + "setValueAtTime", + "setValueCurveAtTime", + "setVariable", + "setVelocity", + "setVersion", + "setVertexBuffer", + "setViewport", + "setYear", + "settingName", + "settingValue", + "sex", + "shaderLocation", + "shaderSource", + "shadowBlur", + "shadowColor", + "shadowOffsetX", + "shadowOffsetY", + "shadowRoot", + "shadowRootClonable", + "shadowRootDelegatesFocus", + "shadowRootMode", + "shape", + "shape-image-threshold", + "shape-margin", + "shape-outside", + "shape-rendering", + "shapeImageThreshold", + "shapeMargin", + "shapeOutside", + "shapeRendering", + "share", + "sharedStorage", + "sharedStorageWritable", + "sheet", + "shift", + "shiftKey", + "shiftLeft", + "shippingAddress", + "shippingOption", + "shippingType", + "show", + "showDirectoryPicker", + "showHelp", + "showModal", + "showModalDialog", + "showModelessDialog", + "showNotification", + "showOpenFilePicker", + "showPicker", + "showPopover", + "showSaveFilePicker", + "sidebar", + "sign", + "signal", + "signalingState", + "signature", + "silent", + "sin", + "singleNodeValue", + "sinh", + "sinkId", + "sittingToStandingTransform", + "size", + "sizeAdjust", + "sizeToContent", + "sizeX", + "sizeZ", + "sizes", + "skewX", + "skewXSelf", + "skewY", + "skewYSelf", + "skipTransition", + "skipped", + "slice", + "slope", + "slot", + "slotAssignment", + "small", + "smil", + "smooth", + "smoothingTimeConstant", + "snapToLines", + "snapshotItem", + "snapshotLength", + "some", + "sort", + "sortingCode", + "source", + "sourceBuffer", + "sourceBuffers", + "sourceCapabilities", + "sourceCharPosition", + "sourceFile", + "sourceFunctionName", + "sourceIndex", + "sourceMap", + "sourceURL", + "sources", + "spacing", + "span", + "speak", + "speakAs", + "speaking", + "species", + "specified", + "specularConstant", + "specularExponent", + "speechSynthesis", + "speed", + "speedOfSound", + "spellcheck", + "sphericalHarmonicsCoefficients", + "splice", + "split", + "splitText", + "spreadMethod", + "sqrt", + "src", + "srcElement", + "srcFactor", + "srcFilter", + "srcObject", + "srcUrn", + "srcdoc", + "srclang", + "srcset", + "stack", + "stackTraceLimit", + "stacktrace", + "stageParameters", + "standalone", + "standby", + "start", + "startContainer", + "startIce", + "startMessages", + "startNotifications", + "startOffset", + "startProfiling", + "startRendering", + "startShark", + "startTime", + "startViewTransition", + "startsWith", + "state", + "states", + "stats", + "status", + "statusCode", + "statusMessage", + "statusText", + "statusbar", + "stdDeviationX", + "stdDeviationY", + "stencilBack", + "stencilClearValue", + "stencilFront", + "stencilFunc", + "stencilFuncSeparate", + "stencilLoadOp", + "stencilMask", + "stencilMaskSeparate", + "stencilOp", + "stencilOpSeparate", + "stencilReadMask", + "stencilReadOnly", + "stencilStoreOp", + "stencilWriteMask", + "step", + "stepDown", + "stepMismatch", + "stepMode", + "stepUp", + "sticky", + "stitchTiles", + "stop", + "stop-color", + "stop-opacity", + "stopColor", + "stopImmediatePropagation", + "stopNotifications", + "stopOpacity", + "stopProfiling", + "stopPropagation", + "stopShark", + "stopped", + "storage", + "storageArea", + "storageBuckets", + "storageName", + "storageStatus", + "storageTexture", + "store", + "storeOp", + "storeSiteSpecificTrackingException", + "storeWebWideTrackingException", + "stpVersion", + "stream", + "streamErrorCode", + "streams", + "stretch", + "strike", + "string", + "stringValue", + "stringify", + "stripIndexFormat", + "stroke", + "stroke-dasharray", + "stroke-dashoffset", + "stroke-linecap", + "stroke-linejoin", + "stroke-miterlimit", + "stroke-opacity", + "stroke-width", + "strokeDasharray", + "strokeDashoffset", + "strokeLinecap", + "strokeLinejoin", + "strokeMiterlimit", + "strokeOpacity", + "strokeRect", + "strokeStyle", + "strokeText", + "strokeWidth", + "structuredClone", + "style", + "styleAndLayoutStart", + "styleFloat", + "styleMap", + "styleMedia", + "styleSheet", + "styleSheetSets", + "styleSheets", + "sub", + "subarray", + "subject", + "submit", + "submitFrame", + "submitter", + "subscribe", + "substr", + "substring", + "substringData", + "subtle", + "subtree", + "suffix", + "suffixes", + "summary", + "sup", + "supported", + "supportedContentEncodings", + "supportedEntryTypes", + "supportedValuesOf", + "supports", + "supportsFiber", + "supportsSession", + "supportsText", + "surfaceScale", + "surroundContents", + "suspend", + "suspendRedraw", + "svb", + "svh", + "svi", + "svmax", + "svmin", + "svw", + "swapCache", + "swapNode", + "sweepFlag", + "symbols", + "symmetricDifference", + "sync", + "syntax", + "sysexEnabled", + "system", + "systemCode", + "systemId", + "systemLanguage", + "systemXDPI", + "systemYDPI", + "tBodies", + "tFoot", + "tHead", + "tab-size", + "tabIndex", + "tabSize", + "table", + "table-layout", + "tableLayout", + "tableValues", + "tag", + "tagName", + "tagUrn", + "tags", + "taintEnabled", + "take", + "takePhoto", + "takeRecords", + "tan", + "tangentialPressure", + "tanh", + "target", + "targetAddressSpace", + "targetElement", + "targetRayMode", + "targetRaySpace", + "targetTouches", + "targetURL", + "targetX", + "targetY", + "targets", + "tcpType", + "tee", + "tel", + "terminate", + "test", + "texImage2D", + "texImage3D", + "texParameterf", + "texParameteri", + "texStorage2D", + "texStorage3D", + "texSubImage2D", + "texSubImage3D", + "text", + "text-align", + "text-align-last", + "text-anchor", + "text-combine-upright", + "text-decoration", + "text-decoration-color", + "text-decoration-line", + "text-decoration-skip-ink", + "text-decoration-style", + "text-decoration-thickness", + "text-emphasis", + "text-emphasis-color", + "text-emphasis-position", + "text-emphasis-style", + "text-indent", + "text-justify", + "text-orientation", + "text-overflow", + "text-rendering", + "text-shadow", + "text-transform", + "text-underline-offset", + "text-underline-position", + "text-wrap", + "text-wrap-mode", + "text-wrap-style", + "textAlign", + "textAlignLast", + "textAnchor", + "textAutospace", + "textBaseline", + "textCombineUpright", + "textContent", + "textDecoration", + "textDecorationBlink", + "textDecorationColor", + "textDecorationLine", + "textDecorationLineThrough", + "textDecorationNone", + "textDecorationOverline", + "textDecorationSkipInk", + "textDecorationStyle", + "textDecorationThickness", + "textDecorationUnderline", + "textEmphasis", + "textEmphasisColor", + "textEmphasisPosition", + "textEmphasisStyle", + "textIndent", + "textJustify", + "textJustifyTrim", + "textKashida", + "textKashidaSpace", + "textLength", + "textOrientation", + "textOverflow", + "textRendering", + "textShadow", + "textTracks", + "textTransform", + "textUnderlineOffset", + "textUnderlinePosition", + "textWrap", + "textWrapMode", + "textWrapStyle", + "texture", + "then", + "threadId", + "threshold", + "thresholds", + "throwIfAborted", + "tiltX", + "tiltY", + "time", + "timeEnd", + "timeLog", + "timeOrigin", + "timeRemaining", + "timeStamp", + "timecode", + "timeline", + "timelineTime", + "timeout", + "timestamp", + "timestampOffset", + "timestampWrites", + "timing", + "title", + "titlebarAreaRect", + "to", + "toArray", + "toBlob", + "toDataURL", + "toDateString", + "toElement", + "toExponential", + "toFixed", + "toFloat32Array", + "toFloat64Array", + "toGMTString", + "toISOString", + "toJSON", + "toLocaleDateString", + "toLocaleFormat", + "toLocaleLowerCase", + "toLocaleString", + "toLocaleTimeString", + "toLocaleUpperCase", + "toLowerCase", + "toMatrix", + "toMethod", + "toPrecision", + "toPrimitive", + "toReversed", + "toSdp", + "toSorted", + "toSource", + "toSpliced", + "toStaticHTML", + "toString", + "toStringTag", + "toSum", + "toTimeString", + "toUTCString", + "toUpperCase", + "toWellFormed", + "toggle", + "toggleAttribute", + "toggleLongPressEnabled", + "togglePopover", + "token", + "tone", + "toneBuffer", + "tooLong", + "tooShort", + "toolbar", + "top", + "topMargin", + "topology", + "total", + "totalFrameDelay", + "totalFrames", + "totalVideoFrames", + "touch-action", + "touchAction", + "touched", + "touches", + "trace", + "track", + "trackVisibility", + "trackedAnchors", + "tracks", + "transaction", + "transactions", + "transceiver", + "transfer", + "transferControlToOffscreen", + "transferFromImageBitmap", + "transferImageBitmap", + "transferIn", + "transferOut", + "transferSize", + "transferToFixedLength", + "transferToImageBitmap", + "transform", + "transform-box", + "transform-origin", + "transform-style", + "transformBox", + "transformFeedbackVaryings", + "transformOrigin", + "transformPoint", + "transformString", + "transformStyle", + "transformToDocument", + "transformToFragment", + "transition", + "transition-delay", + "transition-duration", + "transition-property", + "transition-timing-function", + "transitionDelay", + "transitionDuration", + "transitionProperty", + "transitionTimingFunction", + "translate", + "translateSelf", + "translationX", + "translationY", + "transport", + "traverseTo", + "trim", + "trimEnd", + "trimLeft", + "trimRight", + "trimStart", + "trueSpeed", + "trunc", + "truncate", + "trustedTypes", + "turn", + "twist", + "type", + "typeDetail", + "typeMismatch", + "typeMustMatch", + "types", + "u2f", + "ubound", + "uint16", + "uint32", + "uint8", + "uint8Clamped", + "unadjustedMovement", + "unclippedDepth", + "unconfigure", + "undefined", + "underlineStyle", + "underlineThickness", + "unescape", + "uneval", + "unicode", + "unicode-bidi", + "unicodeBidi", + "unicodeRange", + "unicodeSets", + "uniform1f", + "uniform1fv", + "uniform1i", + "uniform1iv", + "uniform1ui", + "uniform1uiv", + "uniform2f", + "uniform2fv", + "uniform2i", + "uniform2iv", + "uniform2ui", + "uniform2uiv", + "uniform3f", + "uniform3fv", + "uniform3i", + "uniform3iv", + "uniform3ui", + "uniform3uiv", + "uniform4f", + "uniform4fv", + "uniform4i", + "uniform4iv", + "uniform4ui", + "uniform4uiv", + "uniformBlockBinding", + "uniformMatrix2fv", + "uniformMatrix2x3fv", + "uniformMatrix2x4fv", + "uniformMatrix3fv", + "uniformMatrix3x2fv", + "uniformMatrix3x4fv", + "uniformMatrix4fv", + "uniformMatrix4x2fv", + "uniformMatrix4x3fv", + "union", + "unique", + "uniqueID", + "uniqueNumber", + "unit", + "unitType", + "units", + "unloadEventEnd", + "unloadEventStart", + "unlock", + "unmap", + "unmount", + "unobserve", + "unpackColorSpace", + "unpause", + "unpauseAnimations", + "unreadCount", + "unregister", + "unregisterContentHandler", + "unregisterProtocolHandler", + "unscopables", + "unselectable", + "unshift", + "unsubscribe", + "unsuspendRedraw", + "unsuspendRedrawAll", + "unwatch", + "unwrapKey", + "upDegrees", + "upX", + "upY", + "upZ", + "update", + "updateAdInterestGroups", + "updateCallbackDone", + "updateCharacterBounds", + "updateCommands", + "updateControlBounds", + "updateCurrentEntry", + "updateIce", + "updateInkTrailStartPoint", + "updateInterval", + "updatePlaybackRate", + "updateRangeEnd", + "updateRangeStart", + "updateRenderState", + "updateSelection", + "updateSelectionBounds", + "updateSettings", + "updateText", + "updateTiming", + "updateViaCache", + "updateWith", + "updated", + "updating", + "upgrade", + "upload", + "uploadTotal", + "uploaded", + "upper", + "upperBound", + "upperOpen", + "uri", + "url", + "urn", + "urns", + "usage", + "usages", + "usb", + "usbVersionMajor", + "usbVersionMinor", + "usbVersionSubminor", + "useCurrentView", + "useMap", + "useProgram", + "usedSpace", + "user-select", + "userActivation", + "userAgent", + "userAgentData", + "userChoice", + "userHandle", + "userHint", + "userInitiated", + "userLanguage", + "userSelect", + "userState", + "userVisibleOnly", + "username", + "usernameFragment", + "utterance", + "uuid", + "v8BreakIterator", + "vAlign", + "vLink", + "valid", + "validate", + "validateProgram", + "validationMessage", + "validity", + "value", + "valueAsDate", + "valueAsNumber", + "valueAsString", + "valueInSpecifiedUnits", + "valueMissing", + "valueOf", + "valueText", + "valueType", + "values", + "variable", + "variant", + "variationSettings", + "vb", + "vector-effect", + "vectorEffect", + "velocityAngular", + "velocityExpansion", + "velocityX", + "velocityY", + "vendor", + "vendorId", + "vendorSub", + "verify", + "version", + "vertex", + "vertexAttrib1f", + "vertexAttrib1fv", + "vertexAttrib2f", + "vertexAttrib2fv", + "vertexAttrib3f", + "vertexAttrib3fv", + "vertexAttrib4f", + "vertexAttrib4fv", + "vertexAttribDivisor", + "vertexAttribDivisorANGLE", + "vertexAttribI4i", + "vertexAttribI4iv", + "vertexAttribI4ui", + "vertexAttribI4uiv", + "vertexAttribIPointer", + "vertexAttribPointer", + "vertical", + "vertical-align", + "verticalAlign", + "verticalOverflow", + "vh", + "vi", + "vibrate", + "vibrationActuator", + "videoBitsPerSecond", + "videoHeight", + "videoTracks", + "videoWidth", + "view", + "viewBox", + "viewBoxString", + "viewDimension", + "viewFormats", + "viewTarget", + "viewTargetString", + "viewport", + "viewportAnchorX", + "viewportAnchorY", + "viewportElement", + "views", + "violatedDirective", + "virtualKeyboard", + "virtualKeyboardPolicy", + "visibility", + "visibilityState", + "visible", + "visibleRect", + "visualViewport", + "vlinkColor", + "vmax", + "vmin", + "voice", + "voiceURI", + "volume", + "vrml", + "vspace", + "vw", + "w", + "wait", + "waitAsync", + "waitSync", + "waiting", + "wake", + "wakeLock", + "wand", + "warn", + "wasClean", + "wasDiscarded", + "watch", + "watchAvailability", + "watchPosition", + "webdriver", + "webkitAddKey", + "webkitAlignContent", + "webkitAlignItems", + "webkitAlignSelf", + "webkitAnimation", + "webkitAnimationDelay", + "webkitAnimationDirection", + "webkitAnimationDuration", + "webkitAnimationFillMode", + "webkitAnimationIterationCount", + "webkitAnimationName", + "webkitAnimationPlayState", + "webkitAnimationTimingFunction", + "webkitAppearance", + "webkitAudioContext", + "webkitAudioDecodedByteCount", + "webkitAudioPannerNode", + "webkitBackfaceVisibility", + "webkitBackground", + "webkitBackgroundAttachment", + "webkitBackgroundClip", + "webkitBackgroundColor", + "webkitBackgroundImage", + "webkitBackgroundOrigin", + "webkitBackgroundPosition", + "webkitBackgroundPositionX", + "webkitBackgroundPositionY", + "webkitBackgroundRepeat", + "webkitBackgroundSize", + "webkitBackingStorePixelRatio", + "webkitBorderBottomLeftRadius", + "webkitBorderBottomRightRadius", + "webkitBorderImage", + "webkitBorderImageOutset", + "webkitBorderImageRepeat", + "webkitBorderImageSlice", + "webkitBorderImageSource", + "webkitBorderImageWidth", + "webkitBorderRadius", + "webkitBorderTopLeftRadius", + "webkitBorderTopRightRadius", + "webkitBoxAlign", + "webkitBoxDirection", + "webkitBoxFlex", + "webkitBoxOrdinalGroup", + "webkitBoxOrient", + "webkitBoxPack", + "webkitBoxShadow", + "webkitBoxSizing", + "webkitCancelAnimationFrame", + "webkitCancelFullScreen", + "webkitCancelKeyRequest", + "webkitCancelRequestAnimationFrame", + "webkitClearResourceTimings", + "webkitClipPath", + "webkitClosedCaptionsVisible", + "webkitConvertPointFromNodeToPage", + "webkitConvertPointFromPageToNode", + "webkitCreateShadowRoot", + "webkitCurrentFullScreenElement", + "webkitCurrentPlaybackTargetIsWireless", + "webkitDecodedFrameCount", + "webkitDirectionInvertedFromDevice", + "webkitDisplayingFullscreen", + "webkitDroppedFrameCount", + "webkitEnterFullScreen", + "webkitEnterFullscreen", + "webkitEntries", + "webkitExitFullScreen", + "webkitExitFullscreen", + "webkitExitPointerLock", + "webkitFilter", + "webkitFlex", + "webkitFlexBasis", + "webkitFlexDirection", + "webkitFlexFlow", + "webkitFlexGrow", + "webkitFlexShrink", + "webkitFlexWrap", + "webkitFullScreenKeyboardInputAllowed", + "webkitFullscreenElement", + "webkitFullscreenEnabled", + "webkitGenerateKeyRequest", + "webkitGetAsEntry", + "webkitGetDatabaseNames", + "webkitGetEntries", + "webkitGetEntriesByName", + "webkitGetEntriesByType", + "webkitGetFlowByName", + "webkitGetGamepads", + "webkitGetImageDataHD", + "webkitGetNamedFlows", + "webkitGetRegionFlowRanges", + "webkitGetUserMedia", + "webkitHasClosedCaptions", + "webkitHidden", + "webkitIDBCursor", + "webkitIDBDatabase", + "webkitIDBDatabaseError", + "webkitIDBDatabaseException", + "webkitIDBFactory", + "webkitIDBIndex", + "webkitIDBKeyRange", + "webkitIDBObjectStore", + "webkitIDBRequest", + "webkitIDBTransaction", + "webkitImageSmoothingEnabled", + "webkitIndexedDB", + "webkitInitMessageEvent", + "webkitIsFullScreen", + "webkitJustifyContent", + "webkitKeys", + "webkitLineClamp", + "webkitLineDashOffset", + "webkitLockOrientation", + "webkitMask", + "webkitMaskClip", + "webkitMaskComposite", + "webkitMaskImage", + "webkitMaskOrigin", + "webkitMaskPosition", + "webkitMaskPositionX", + "webkitMaskPositionY", + "webkitMaskRepeat", + "webkitMaskSize", + "webkitMatchesSelector", + "webkitMediaStream", + "webkitNotifications", + "webkitOfflineAudioContext", + "webkitOrder", + "webkitOrientation", + "webkitPeerConnection00", + "webkitPersistentStorage", + "webkitPerspective", + "webkitPerspectiveOrigin", + "webkitPointerLockElement", + "webkitPostMessage", + "webkitPreservesPitch", + "webkitPutImageDataHD", + "webkitRTCPeerConnection", + "webkitRegionOverset", + "webkitRelativePath", + "webkitRequestAnimationFrame", + "webkitRequestFileSystem", + "webkitRequestFullScreen", + "webkitRequestFullscreen", + "webkitRequestPointerLock", + "webkitResolveLocalFileSystemURL", + "webkitSetMediaKeys", + "webkitSetResourceTimingBufferSize", + "webkitShadowRoot", + "webkitShowPlaybackTargetPicker", + "webkitSlice", + "webkitSpeechGrammar", + "webkitSpeechGrammarList", + "webkitSpeechRecognition", + "webkitSpeechRecognitionError", + "webkitSpeechRecognitionEvent", + "webkitStorageInfo", + "webkitSupportsFullscreen", + "webkitTemporaryStorage", + "webkitTextFillColor", + "webkitTextSecurity", + "webkitTextSizeAdjust", + "webkitTextStroke", + "webkitTextStrokeColor", + "webkitTextStrokeWidth", + "webkitTransform", + "webkitTransformOrigin", + "webkitTransformStyle", + "webkitTransition", + "webkitTransitionDelay", + "webkitTransitionDuration", + "webkitTransitionProperty", + "webkitTransitionTimingFunction", + "webkitURL", + "webkitUnlockOrientation", + "webkitUserSelect", + "webkitVideoDecodedByteCount", + "webkitVisibilityState", + "webkitWirelessVideoPlaybackDisabled", + "webkitdirectory", + "webkitdropzone", + "webstore", + "weight", + "wgslLanguageFeatures", + "whatToShow", + "wheelDelta", + "wheelDeltaX", + "wheelDeltaY", + "whenDefined", + "which", + "white-space", + "white-space-collapse", + "whiteSpace", + "whiteSpaceCollapse", + "wholeText", + "widows", + "width", + "will-change", + "willChange", + "willValidate", + "window", + "windowAttribution", + "windowControlsOverlay", + "with", + "withCredentials", + "withResolvers", + "word-break", + "word-spacing", + "word-wrap", + "wordBreak", + "wordSpacing", + "wordWrap", + "workerStart", + "worklet", + "wow64", + "wrap", + "wrapKey", + "writable", + "writableAuxiliaries", + "write", + "writeBuffer", + "writeMask", + "writeText", + "writeTexture", + "writeTimestamp", + "writeValue", + "writeValueWithResponse", + "writeValueWithoutResponse", + "writeWithoutResponse", + "writeln", + "writing-mode", + "writingMode", + "writingSuggestions", + "x", + "x1", + "x2", + "xChannelSelector", + "xmlEncoding", + "xmlStandalone", + "xmlVersion", + "xmlbase", + "xmllang", + "xmlspace", + "xor", + "xr", + "y", + "y1", + "y2", + "yChannelSelector", + "yandex", + "z", + "z-index", + "zIndex", + "zoom", + "zoomAndPan", + "zoomRectScreen", +]; diff --git a/node_modules/terser/tools/exit.cjs b/node_modules/terser/tools/exit.cjs new file mode 100644 index 0000000..46a970b --- /dev/null +++ b/node_modules/terser/tools/exit.cjs @@ -0,0 +1,7 @@ +// workaround for tty output truncation upon process.exit() +// https://github.com/nodejs/node/issues/6456 + +[process.stdout, process.stderr].forEach((s) => { + s && s.isTTY && s._handle && s._handle.setBlocking && + s._handle.setBlocking(true) +}); diff --git a/node_modules/terser/tools/props.html b/node_modules/terser/tools/props.html new file mode 100644 index 0000000..fbb4cb8 --- /dev/null +++ b/node_modules/terser/tools/props.html @@ -0,0 +1,66 @@ + + + + + + + diff --git a/node_modules/terser/tools/terser.d.ts b/node_modules/terser/tools/terser.d.ts new file mode 100644 index 0000000..2d7ca19 --- /dev/null +++ b/node_modules/terser/tools/terser.d.ts @@ -0,0 +1,216 @@ +/// + +import { SectionedSourceMapInput, EncodedSourceMap, DecodedSourceMap } from '@jridgewell/source-map'; + +export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020; + +export type ConsoleProperty = keyof typeof console; +type DropConsoleOption = boolean | ConsoleProperty[]; + +export interface ParseOptions { + bare_returns?: boolean; + /** @deprecated legacy option. Currently, all supported EcmaScript is valid to parse. */ + ecma?: ECMA; + html5_comments?: boolean; + shebang?: boolean; +} + +export interface CompressOptions { + arguments?: boolean; + arrows?: boolean; + booleans_as_integers?: boolean; + booleans?: boolean; + collapse_vars?: boolean; + comparisons?: boolean; + computed_props?: boolean; + conditionals?: boolean; + dead_code?: boolean; + defaults?: boolean; + directives?: boolean; + drop_console?: DropConsoleOption; + drop_debugger?: boolean; + ecma?: ECMA; + evaluate?: boolean; + expression?: boolean; + global_defs?: object; + hoist_funs?: boolean; + hoist_props?: boolean; + hoist_vars?: boolean; + ie8?: boolean; + if_return?: boolean; + inline?: boolean | InlineFunctions; + join_vars?: boolean; + keep_classnames?: boolean | RegExp; + keep_fargs?: boolean; + keep_fnames?: boolean | RegExp; + keep_infinity?: boolean; + loops?: boolean; + module?: boolean; + negate_iife?: boolean; + passes?: number; + properties?: boolean; + pure_funcs?: string[]; + pure_new?: boolean; + pure_getters?: boolean | 'strict'; + reduce_funcs?: boolean; + reduce_vars?: boolean; + sequences?: boolean | number; + side_effects?: boolean; + switches?: boolean; + toplevel?: boolean; + top_retain?: null | string | string[] | RegExp; + typeofs?: boolean; + unsafe_arrows?: boolean; + unsafe?: boolean; + unsafe_comps?: boolean; + unsafe_Function?: boolean; + unsafe_math?: boolean; + unsafe_symbols?: boolean; + unsafe_methods?: boolean; + unsafe_proto?: boolean; + unsafe_regexp?: boolean; + unsafe_undefined?: boolean; + unused?: boolean; +} + +export enum InlineFunctions { + Disabled = 0, + SimpleFunctions = 1, + WithArguments = 2, + WithArgumentsAndVariables = 3 +} + +export interface MangleOptions { + eval?: boolean; + keep_classnames?: boolean | RegExp; + keep_fnames?: boolean | RegExp; + module?: boolean; + nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler; + properties?: boolean | ManglePropertiesOptions; + reserved?: string[]; + safari10?: boolean; + toplevel?: boolean; +} + +/** + * An identifier mangler for which the output is invariant with respect to the source code. + */ +export interface SimpleIdentifierMangler { + /** + * Obtains the nth most favored (usually shortest) identifier to rename a variable to. + * The mangler will increment n and retry until the return value is not in use in scope, and is not a reserved word. + * This function is expected to be stable; Evaluating get(n) === get(n) should always return true. + * @param n The ordinal of the identifier. + */ + get(n: number): string; +} + +/** + * An identifier mangler that leverages character frequency analysis to determine identifier precedence. + */ +export interface WeightedIdentifierMangler extends SimpleIdentifierMangler { + /** + * Modifies the internal weighting of the input characters by the specified delta. + * Will be invoked on the entire printed AST, and then deduct mangleable identifiers. + * @param chars The characters to modify the weighting of. + * @param delta The numeric weight to add to the characters. + */ + consider(chars: string, delta: number): number; + /** + * Resets character weights. + */ + reset(): void; + /** + * Sorts identifiers by character frequency, in preparation for calls to get(n). + */ + sort(): void; +} + +export interface ManglePropertiesOptions { + builtins?: boolean; + debug?: boolean; + keep_quoted?: boolean | 'strict'; + nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler; + regex?: RegExp | string; + reserved?: string[]; +} + +export interface FormatOptions { + ascii_only?: boolean; + /** @deprecated Not implemented anymore */ + beautify?: boolean; + braces?: boolean; + comments?: boolean | 'all' | 'some' | RegExp | ( (node: any, comment: { + value: string, + type: 'comment1' | 'comment2' | 'comment3' | 'comment4', + pos: number, + line: number, + col: number, + }) => boolean ); + ecma?: ECMA; + ie8?: boolean; + keep_numbers?: boolean; + indent_level?: number; + indent_start?: number; + inline_script?: boolean; + keep_quoted_props?: boolean; + max_line_len?: number | false; + preamble?: string; + preserve_annotations?: boolean; + quote_keys?: boolean; + quote_style?: OutputQuoteStyle; + safari10?: boolean; + semicolons?: boolean; + shebang?: boolean; + shorthand?: boolean; + source_map?: SourceMapOptions; + webkit?: boolean; + width?: number; + wrap_iife?: boolean; + wrap_func_args?: boolean; +} + +export enum OutputQuoteStyle { + PreferDouble = 0, + AlwaysSingle = 1, + AlwaysDouble = 2, + AlwaysOriginal = 3 +} + +export interface MinifyOptions { + compress?: boolean | CompressOptions; + ecma?: ECMA; + enclose?: boolean | string; + ie8?: boolean; + keep_classnames?: boolean | RegExp; + keep_fnames?: boolean | RegExp; + mangle?: boolean | MangleOptions; + module?: boolean; + nameCache?: object; + format?: FormatOptions; + /** @deprecated */ + output?: FormatOptions; + parse?: ParseOptions; + safari10?: boolean; + sourceMap?: boolean | SourceMapOptions; + toplevel?: boolean; +} + +export interface MinifyOutput { + code?: string; + map?: EncodedSourceMap | string; + decoded_map?: DecodedSourceMap | null; +} + +export interface SourceMapOptions { + /** Source map object, 'inline' or source map file content */ + content?: SectionedSourceMapInput | string; + includeSources?: boolean; + filename?: string; + root?: string; + asObject?: boolean; + url?: string | 'inline'; +} + +export function minify(files: string | string[] | { [file: string]: string }, options?: MinifyOptions): Promise; +export function minify_sync(files: string | string[] | { [file: string]: string }, options?: MinifyOptions): MinifyOutput; diff --git a/node_modules/to-fast-properties/index.js b/node_modules/to-fast-properties/index.js new file mode 100644 index 0000000..028c88a --- /dev/null +++ b/node_modules/to-fast-properties/index.js @@ -0,0 +1,27 @@ +'use strict'; + +let fastProto = null; + +// Creates an object with permanently fast properties in V8. See Toon Verwaest's +// post https://medium.com/@tverwaes/setting-up-prototypes-in-v8-ec9c9491dfe2#5f62 +// for more details. Use %HasFastProperties(object) and the Node.js flag +// --allow-natives-syntax to check whether an object has fast properties. +function FastObject(o) { + // A prototype object will have "fast properties" enabled once it is checked + // against the inline property cache of a function, e.g. fastProto.property: + // https://github.com/v8/v8/blob/6.0.122/test/mjsunit/fast-prototype.js#L48-L63 + if (fastProto !== null && typeof fastProto.property) { + const result = fastProto; + fastProto = FastObject.prototype = null; + return result; + } + fastProto = FastObject.prototype = o == null ? Object.create(null) : o; + return new FastObject; +} + +// Initialize the inline property cache of FastObject +FastObject(); + +module.exports = function toFastproperties(o) { + return FastObject(o); +}; diff --git a/node_modules/to-fast-properties/license b/node_modules/to-fast-properties/license new file mode 100644 index 0000000..cef79ef --- /dev/null +++ b/node_modules/to-fast-properties/license @@ -0,0 +1,10 @@ +MIT License + +Copyright (c) 2014 Petka Antonov + 2015 Sindre Sorhus + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/to-fast-properties/package.json b/node_modules/to-fast-properties/package.json new file mode 100644 index 0000000..7a64b2c --- /dev/null +++ b/node_modules/to-fast-properties/package.json @@ -0,0 +1,35 @@ +{ + "name": "to-fast-properties", + "version": "2.0.0", + "description": "Force V8 to use fast properties for an object", + "license": "MIT", + "repository": "sindresorhus/to-fast-properties", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=4" + }, + "scripts": { + "test": "node --allow-natives-syntax test.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "object", + "obj", + "properties", + "props", + "v8", + "optimize", + "fast", + "convert", + "mode" + ], + "devDependencies": { + "ava": "0.0.4" + } +} diff --git a/node_modules/to-fast-properties/readme.md b/node_modules/to-fast-properties/readme.md new file mode 100644 index 0000000..692101d --- /dev/null +++ b/node_modules/to-fast-properties/readme.md @@ -0,0 +1,37 @@ +# to-fast-properties [![Build Status](https://travis-ci.org/sindresorhus/to-fast-properties.svg?branch=master)](https://travis-ci.org/sindresorhus/to-fast-properties) + +> Force V8 to use fast properties for an object + +[Read more.](http://stackoverflow.com/questions/24987896/) + +Use `%HasFastProperties(object)` and `--allow-natives-syntax` to check whether an object already has fast properties. + + +## Install + +``` +$ npm install --save to-fast-properties +``` + + +## Usage + +```js +const toFastProperties = require('to-fast-properties'); + +const obj = { + foo: true, + bar: true +}; + +delete obj.foo; +// `obj` now has slow properties + +toFastProperties(obj); +// `obj` now has fast properties +``` + + +## License + +MIT © Petka Antonov, John-David Dalton, Sindre Sorhus diff --git a/node_modules/undici-types/LICENSE b/node_modules/undici-types/LICENSE new file mode 100644 index 0000000..e7323bb --- /dev/null +++ b/node_modules/undici-types/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Matteo Collina and Undici contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/undici-types/README.md b/node_modules/undici-types/README.md new file mode 100644 index 0000000..20a721c --- /dev/null +++ b/node_modules/undici-types/README.md @@ -0,0 +1,6 @@ +# undici-types + +This package is a dual-publish of the [undici](https://www.npmjs.com/package/undici) library types. The `undici` package **still contains types**. This package is for users who _only_ need undici types (such as for `@types/node`). It is published alongside every release of `undici`, so you can always use the same version. + +- [GitHub nodejs/undici](https://github.com/nodejs/undici) +- [Undici Documentation](https://undici.nodejs.org/#/) diff --git a/node_modules/undici-types/agent.d.ts b/node_modules/undici-types/agent.d.ts new file mode 100644 index 0000000..58081ce --- /dev/null +++ b/node_modules/undici-types/agent.d.ts @@ -0,0 +1,31 @@ +import { URL } from 'url' +import Pool from './pool' +import Dispatcher from "./dispatcher"; + +export default Agent + +declare class Agent extends Dispatcher{ + constructor(opts?: Agent.Options) + /** `true` after `dispatcher.close()` has been called. */ + closed: boolean; + /** `true` after `dispatcher.destroyed()` has been called or `dispatcher.close()` has been called and the dispatcher shutdown has completed. */ + destroyed: boolean; + /** Dispatches a request. */ + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; +} + +declare namespace Agent { + export interface Options extends Pool.Options { + /** Default: `(origin, opts) => new Pool(origin, opts)`. */ + factory?(origin: string | URL, opts: Object): Dispatcher; + /** Integer. Default: `0` */ + maxRedirections?: number; + + interceptors?: { Agent?: readonly Dispatcher.DispatchInterceptor[] } & Pool.Options["interceptors"] + } + + export interface DispatchOptions extends Dispatcher.DispatchOptions { + /** Integer. */ + maxRedirections?: number; + } +} diff --git a/node_modules/undici-types/api.d.ts b/node_modules/undici-types/api.d.ts new file mode 100644 index 0000000..400341d --- /dev/null +++ b/node_modules/undici-types/api.d.ts @@ -0,0 +1,43 @@ +import { URL, UrlObject } from 'url' +import { Duplex } from 'stream' +import Dispatcher from './dispatcher' + +export { + request, + stream, + pipeline, + connect, + upgrade, +} + +/** Performs an HTTP request. */ +declare function request( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit & Partial>, +): Promise; + +/** A faster version of `request`. */ +declare function stream( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, + factory: Dispatcher.StreamFactory +): Promise; + +/** For easy use with `stream.pipeline`. */ +declare function pipeline( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, + handler: Dispatcher.PipelineHandler +): Duplex; + +/** Starts two-way communications with the requested resource. */ +declare function connect( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit +): Promise; + +/** Upgrade to a different protocol. */ +declare function upgrade( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit +): Promise; diff --git a/node_modules/undici-types/balanced-pool.d.ts b/node_modules/undici-types/balanced-pool.d.ts new file mode 100644 index 0000000..7f930f4 --- /dev/null +++ b/node_modules/undici-types/balanced-pool.d.ts @@ -0,0 +1,29 @@ +import Pool from './pool' +import Dispatcher from './dispatcher' +import { URL } from 'url' + +export default BalancedPool + +type BalancedPoolConnectOptions = Omit; + +declare class BalancedPool extends Dispatcher { + constructor(url: string | string[] | URL | URL[], options?: Pool.Options); + + addUpstream(upstream: string | URL): BalancedPool; + removeUpstream(upstream: string | URL): BalancedPool; + upstreams: Array; + + /** `true` after `pool.close()` has been called. */ + closed: boolean; + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean; + + // Override dispatcher APIs. + override connect( + options: BalancedPoolConnectOptions + ): Promise; + override connect( + options: BalancedPoolConnectOptions, + callback: (err: Error | null, data: Dispatcher.ConnectData) => void + ): void; +} diff --git a/node_modules/undici-types/cache.d.ts b/node_modules/undici-types/cache.d.ts new file mode 100644 index 0000000..4c33335 --- /dev/null +++ b/node_modules/undici-types/cache.d.ts @@ -0,0 +1,36 @@ +import type { RequestInfo, Response, Request } from './fetch' + +export interface CacheStorage { + match (request: RequestInfo, options?: MultiCacheQueryOptions): Promise, + has (cacheName: string): Promise, + open (cacheName: string): Promise, + delete (cacheName: string): Promise, + keys (): Promise +} + +declare const CacheStorage: { + prototype: CacheStorage + new(): CacheStorage +} + +export interface Cache { + match (request: RequestInfo, options?: CacheQueryOptions): Promise, + matchAll (request?: RequestInfo, options?: CacheQueryOptions): Promise, + add (request: RequestInfo): Promise, + addAll (requests: RequestInfo[]): Promise, + put (request: RequestInfo, response: Response): Promise, + delete (request: RequestInfo, options?: CacheQueryOptions): Promise, + keys (request?: RequestInfo, options?: CacheQueryOptions): Promise +} + +export interface CacheQueryOptions { + ignoreSearch?: boolean, + ignoreMethod?: boolean, + ignoreVary?: boolean +} + +export interface MultiCacheQueryOptions extends CacheQueryOptions { + cacheName?: string +} + +export declare const caches: CacheStorage diff --git a/node_modules/undici-types/client.d.ts b/node_modules/undici-types/client.d.ts new file mode 100644 index 0000000..d0a5379 --- /dev/null +++ b/node_modules/undici-types/client.d.ts @@ -0,0 +1,108 @@ +import { URL } from 'url' +import { TlsOptions } from 'tls' +import Dispatcher from './dispatcher' +import buildConnector from "./connector"; + +type ClientConnectOptions = Omit; + +/** + * A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default. + */ +export class Client extends Dispatcher { + constructor(url: string | URL, options?: Client.Options); + /** Property to get and set the pipelining factor. */ + pipelining: number; + /** `true` after `client.close()` has been called. */ + closed: boolean; + /** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */ + destroyed: boolean; + + // Override dispatcher APIs. + override connect( + options: ClientConnectOptions + ): Promise; + override connect( + options: ClientConnectOptions, + callback: (err: Error | null, data: Dispatcher.ConnectData) => void + ): void; +} + +export declare namespace Client { + export interface OptionsInterceptors { + Client: readonly Dispatcher.DispatchInterceptor[]; + } + export interface Options { + /** TODO */ + interceptors?: OptionsInterceptors; + /** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */ + maxHeaderSize?: number; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */ + headersTimeout?: number; + /** @deprecated unsupported socketTimeout, use headersTimeout & bodyTimeout instead */ + socketTimeout?: never; + /** @deprecated unsupported requestTimeout, use headersTimeout & bodyTimeout instead */ + requestTimeout?: never; + /** TODO */ + connectTimeout?: number; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */ + bodyTimeout?: number; + /** @deprecated unsupported idleTimeout, use keepAliveTimeout instead */ + idleTimeout?: never; + /** @deprecated unsupported keepAlive, use pipelining=0 instead */ + keepAlive?: never; + /** the timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */ + keepAliveTimeout?: number; + /** @deprecated unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead */ + maxKeepAliveTimeout?: never; + /** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */ + keepAliveMaxTimeout?: number; + /** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */ + keepAliveTimeoutThreshold?: number; + /** TODO */ + socketPath?: string; + /** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */ + pipelining?: number; + /** @deprecated use the connect option instead */ + tls?: never; + /** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */ + strictContentLength?: boolean; + /** TODO */ + maxCachedSessions?: number; + /** TODO */ + maxRedirections?: number; + /** TODO */ + connect?: buildConnector.BuildOptions | buildConnector.connector; + /** TODO */ + maxRequestsPerClient?: number; + /** TODO */ + localAddress?: string; + /** Max response body size in bytes, -1 is disabled */ + maxResponseSize?: number; + /** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */ + autoSelectFamily?: boolean; + /** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */ + autoSelectFamilyAttemptTimeout?: number; + /** + * @description Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation. + * @default false + */ + allowH2?: boolean; + /** + * @description Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame. + * @default 100 + */ + maxConcurrentStreams?: number + } + export interface SocketInfo { + localAddress?: string + localPort?: number + remoteAddress?: string + remotePort?: number + remoteFamily?: string + timeout?: number + bytesWritten?: number + bytesRead?: number + } +} + +export default Client; diff --git a/node_modules/undici-types/connector.d.ts b/node_modules/undici-types/connector.d.ts new file mode 100644 index 0000000..bd92433 --- /dev/null +++ b/node_modules/undici-types/connector.d.ts @@ -0,0 +1,34 @@ +import { TLSSocket, ConnectionOptions } from 'tls' +import { IpcNetConnectOpts, Socket, TcpNetConnectOpts } from 'net' + +export default buildConnector +declare function buildConnector (options?: buildConnector.BuildOptions): buildConnector.connector + +declare namespace buildConnector { + export type BuildOptions = (ConnectionOptions | TcpNetConnectOpts | IpcNetConnectOpts) & { + allowH2?: boolean; + maxCachedSessions?: number | null; + socketPath?: string | null; + timeout?: number | null; + port?: number; + keepAlive?: boolean | null; + keepAliveInitialDelay?: number | null; + } + + export interface Options { + hostname: string + host?: string + protocol: string + port: string + servername?: string + localAddress?: string | null + httpSocket?: Socket + } + + export type Callback = (...args: CallbackArgs) => void + type CallbackArgs = [null, Socket | TLSSocket] | [Error, null] + + export interface connector { + (options: buildConnector.Options, callback: buildConnector.Callback): void + } +} diff --git a/node_modules/undici-types/content-type.d.ts b/node_modules/undici-types/content-type.d.ts new file mode 100644 index 0000000..f2a87f1 --- /dev/null +++ b/node_modules/undici-types/content-type.d.ts @@ -0,0 +1,21 @@ +/// + +interface MIMEType { + type: string + subtype: string + parameters: Map + essence: string +} + +/** + * Parse a string to a {@link MIMEType} object. Returns `failure` if the string + * couldn't be parsed. + * @see https://mimesniff.spec.whatwg.org/#parse-a-mime-type + */ +export function parseMIMEType (input: string): 'failure' | MIMEType + +/** + * Convert a MIMEType object to a string. + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +export function serializeAMimeType (mimeType: MIMEType): string diff --git a/node_modules/undici-types/cookies.d.ts b/node_modules/undici-types/cookies.d.ts new file mode 100644 index 0000000..aa38cae --- /dev/null +++ b/node_modules/undici-types/cookies.d.ts @@ -0,0 +1,28 @@ +/// + +import type { Headers } from './fetch' + +export interface Cookie { + name: string + value: string + expires?: Date | number + maxAge?: number + domain?: string + path?: string + secure?: boolean + httpOnly?: boolean + sameSite?: 'Strict' | 'Lax' | 'None' + unparsed?: string[] +} + +export function deleteCookie ( + headers: Headers, + name: string, + attributes?: { name?: string, domain?: string } +): void + +export function getCookies (headers: Headers): Record + +export function getSetCookies (headers: Headers): Cookie[] + +export function setCookie (headers: Headers, cookie: Cookie): void diff --git a/node_modules/undici-types/diagnostics-channel.d.ts b/node_modules/undici-types/diagnostics-channel.d.ts new file mode 100644 index 0000000..a037d1e --- /dev/null +++ b/node_modules/undici-types/diagnostics-channel.d.ts @@ -0,0 +1,66 @@ +import { Socket } from "net"; +import { URL } from "url"; +import Connector from "./connector"; +import Dispatcher from "./dispatcher"; + +declare namespace DiagnosticsChannel { + interface Request { + origin?: string | URL; + completed: boolean; + method?: Dispatcher.HttpMethod; + path: string; + headers: any; + } + interface Response { + statusCode: number; + statusText: string; + headers: Array; + } + type Error = unknown; + interface ConnectParams { + host: URL["host"]; + hostname: URL["hostname"]; + protocol: URL["protocol"]; + port: URL["port"]; + servername: string | null; + } + type Connector = Connector.connector; + export interface RequestCreateMessage { + request: Request; + } + export interface RequestBodySentMessage { + request: Request; + } + export interface RequestHeadersMessage { + request: Request; + response: Response; + } + export interface RequestTrailersMessage { + request: Request; + trailers: Array; + } + export interface RequestErrorMessage { + request: Request; + error: Error; + } + export interface ClientSendHeadersMessage { + request: Request; + headers: string; + socket: Socket; + } + export interface ClientBeforeConnectMessage { + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectedMessage { + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectErrorMessage { + error: Error; + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } +} diff --git a/node_modules/undici-types/dispatcher.d.ts b/node_modules/undici-types/dispatcher.d.ts new file mode 100644 index 0000000..0aa2aba --- /dev/null +++ b/node_modules/undici-types/dispatcher.d.ts @@ -0,0 +1,255 @@ +import { URL } from 'url' +import { Duplex, Readable, Writable } from 'stream' +import { EventEmitter } from 'events' +import { Blob } from 'buffer' +import { IncomingHttpHeaders } from './header' +import BodyReadable from './readable' +import { FormData } from './formdata' +import Errors from './errors' + +type AbortSignal = unknown; + +export default Dispatcher + +/** Dispatcher is the core API used to dispatch requests. */ +declare class Dispatcher extends EventEmitter { + /** Dispatches a request. This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. It is primarily intended for library developers who implement higher level APIs on top of this. */ + dispatch(options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + /** Starts two-way communications with the requested resource. */ + connect(options: Dispatcher.ConnectOptions): Promise; + connect(options: Dispatcher.ConnectOptions, callback: (err: Error | null, data: Dispatcher.ConnectData) => void): void; + /** Compose a chain of dispatchers */ + compose(dispatchers: Dispatcher.DispatcherComposeInterceptor[]): Dispatcher.ComposedDispatcher; + compose(...dispatchers: Dispatcher.DispatcherComposeInterceptor[]): Dispatcher.ComposedDispatcher; + /** Performs an HTTP request. */ + request(options: Dispatcher.RequestOptions): Promise; + request(options: Dispatcher.RequestOptions, callback: (err: Error | null, data: Dispatcher.ResponseData) => void): void; + /** For easy use with `stream.pipeline`. */ + pipeline(options: Dispatcher.PipelineOptions, handler: Dispatcher.PipelineHandler): Duplex; + /** A faster version of `Dispatcher.request`. */ + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory): Promise; + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory, callback: (err: Error | null, data: Dispatcher.StreamData) => void): void; + /** Upgrade to a different protocol. */ + upgrade(options: Dispatcher.UpgradeOptions): Promise; + upgrade(options: Dispatcher.UpgradeOptions, callback: (err: Error | null, data: Dispatcher.UpgradeData) => void): void; + /** Closes the client and gracefully waits for enqueued requests to complete before invoking the callback (or returning a promise if no callback is provided). */ + close(): Promise; + close(callback: () => void): void; + /** Destroy the client abruptly with the given err. All the pending and running requests will be asynchronously aborted and error. Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. */ + destroy(): Promise; + destroy(err: Error | null): Promise; + destroy(callback: () => void): void; + destroy(err: Error | null, callback: () => void): void; + + on(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + on(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + on(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + on(eventName: 'drain', callback: (origin: URL) => void): this; + + + once(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + once(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + once(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + once(eventName: 'drain', callback: (origin: URL) => void): this; + + + off(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + off(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + off(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + off(eventName: 'drain', callback: (origin: URL) => void): this; + + + addListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + addListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + addListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + addListener(eventName: 'drain', callback: (origin: URL) => void): this; + + removeListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + removeListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + removeListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + removeListener(eventName: 'drain', callback: (origin: URL) => void): this; + + prependListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + prependListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependListener(eventName: 'drain', callback: (origin: URL) => void): this; + + prependOnceListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + prependOnceListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependOnceListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependOnceListener(eventName: 'drain', callback: (origin: URL) => void): this; + + listeners(eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + listeners(eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + listeners(eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + listeners(eventName: 'drain'): ((origin: URL) => void)[]; + + rawListeners(eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + rawListeners(eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + rawListeners(eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + rawListeners(eventName: 'drain'): ((origin: URL) => void)[]; + + emit(eventName: 'connect', origin: URL, targets: readonly Dispatcher[]): boolean; + emit(eventName: 'disconnect', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean; + emit(eventName: 'connectionError', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean; + emit(eventName: 'drain', origin: URL): boolean; +} + +declare namespace Dispatcher { + export interface ComposedDispatcher extends Dispatcher {} + export type DispatcherComposeInterceptor = (dispatch: Dispatcher['dispatch']) => Dispatcher['dispatch']; + export interface DispatchOptions { + origin?: string | URL; + path: string; + method: HttpMethod; + /** Default: `null` */ + body?: string | Buffer | Uint8Array | Readable | null | FormData; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | Iterable<[string, string | string[] | undefined]> | null; + /** Query string params to be embedded in the request URL. Default: `null` */ + query?: Record; + /** Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline have completed. Default: `true` if `method` is `HEAD` or `GET`. */ + idempotent?: boolean; + /** Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. */ + blocking?: boolean; + /** Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. Default: `method === 'CONNECT' || null`. */ + upgrade?: boolean | string | null; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers. Defaults to 300 seconds. */ + headersTimeout?: number | null; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use 0 to disable it entirely. Defaults to 300 seconds. */ + bodyTimeout?: number | null; + /** Whether the request should stablish a keep-alive or not. Default `false` */ + reset?: boolean; + /** Whether Undici should throw an error upon receiving a 4xx or 5xx response from the server. Defaults to false */ + throwOnError?: boolean; + /** For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server*/ + expectContinue?: boolean; + } + export interface ConnectOptions { + origin: string | URL; + path: string; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** This argument parameter is passed through to `ConnectData` */ + opaque?: unknown; + /** Default: 0 */ + maxRedirections?: number; + /** Default: false */ + redirectionLimitReached?: boolean; + /** Default: `null` */ + responseHeader?: 'raw' | null; + } + export interface RequestOptions extends DispatchOptions { + /** Default: `null` */ + opaque?: unknown; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: 0 */ + maxRedirections?: number; + /** Default: false */ + redirectionLimitReached?: boolean; + /** Default: `null` */ + onInfo?: (info: { statusCode: number, headers: Record }) => void; + /** Default: `null` */ + responseHeader?: 'raw' | null; + /** Default: `64 KiB` */ + highWaterMark?: number; + } + export interface PipelineOptions extends RequestOptions { + /** `true` if the `handler` will return an object stream. Default: `false` */ + objectMode?: boolean; + } + export interface UpgradeOptions { + path: string; + /** Default: `'GET'` */ + method?: string; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** A string of comma separated protocols, in descending preference order. Default: `'Websocket'` */ + protocol?: string; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: 0 */ + maxRedirections?: number; + /** Default: false */ + redirectionLimitReached?: boolean; + /** Default: `null` */ + responseHeader?: 'raw' | null; + } + export interface ConnectData { + statusCode: number; + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: unknown; + } + export interface ResponseData { + statusCode: number; + headers: IncomingHttpHeaders; + body: BodyReadable & BodyMixin; + trailers: Record; + opaque: unknown; + context: object; + } + export interface PipelineHandlerData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: unknown; + body: BodyReadable; + context: object; + } + export interface StreamData { + opaque: unknown; + trailers: Record; + } + export interface UpgradeData { + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: unknown; + } + export interface StreamFactoryData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: unknown; + context: object; + } + export type StreamFactory = (data: StreamFactoryData) => Writable; + export interface DispatchHandlers { + /** Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. */ + onConnect?(abort: (err?: Error) => void): void; + /** Invoked when an error has occurred. */ + onError?(err: Error): void; + /** Invoked when request is upgraded either due to a `Upgrade` header or `CONNECT` method. */ + onUpgrade?(statusCode: number, headers: Buffer[] | string[] | null, socket: Duplex): void; + /** Invoked when response is received, before headers have been read. **/ + onResponseStarted?(): void; + /** Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. */ + onHeaders?(statusCode: number, headers: Buffer[], resume: () => void, statusText: string): boolean; + /** Invoked when response payload data is received. */ + onData?(chunk: Buffer): boolean; + /** Invoked when response payload and trailers have been received and the request has completed. */ + onComplete?(trailers: string[] | null): void; + /** Invoked when a body chunk is sent to the server. May be invoked multiple times for chunked requests */ + onBodySent?(chunkSize: number, totalBytesSent: number): void; + } + export type PipelineHandler = (data: PipelineHandlerData) => Readable; + export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'; + + /** + * @link https://fetch.spec.whatwg.org/#body-mixin + */ + interface BodyMixin { + readonly body?: never; + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; + } + + export interface DispatchInterceptor { + (dispatch: Dispatcher['dispatch']): Dispatcher['dispatch'] + } +} diff --git a/node_modules/undici-types/env-http-proxy-agent.d.ts b/node_modules/undici-types/env-http-proxy-agent.d.ts new file mode 100644 index 0000000..d6509dc --- /dev/null +++ b/node_modules/undici-types/env-http-proxy-agent.d.ts @@ -0,0 +1,21 @@ +import Agent from './agent' +import Dispatcher from './dispatcher' + +export default EnvHttpProxyAgent + +declare class EnvHttpProxyAgent extends Dispatcher { + constructor(opts?: EnvHttpProxyAgent.Options) + + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; +} + +declare namespace EnvHttpProxyAgent { + export interface Options extends Agent.Options { + /** Overrides the value of the HTTP_PROXY environment variable */ + httpProxy?: string; + /** Overrides the value of the HTTPS_PROXY environment variable */ + httpsProxy?: string; + /** Overrides the value of the NO_PROXY environment variable */ + noProxy?: string; + } +} diff --git a/node_modules/undici-types/errors.d.ts b/node_modules/undici-types/errors.d.ts new file mode 100644 index 0000000..f6fb73b --- /dev/null +++ b/node_modules/undici-types/errors.d.ts @@ -0,0 +1,149 @@ +import { IncomingHttpHeaders } from "./header"; +import Client from './client' + +export default Errors + +declare namespace Errors { + export class UndiciError extends Error { + name: string; + code: string; + } + + /** Connect timeout error. */ + export class ConnectTimeoutError extends UndiciError { + name: 'ConnectTimeoutError'; + code: 'UND_ERR_CONNECT_TIMEOUT'; + } + + /** A header exceeds the `headersTimeout` option. */ + export class HeadersTimeoutError extends UndiciError { + name: 'HeadersTimeoutError'; + code: 'UND_ERR_HEADERS_TIMEOUT'; + } + + /** Headers overflow error. */ + export class HeadersOverflowError extends UndiciError { + name: 'HeadersOverflowError' + code: 'UND_ERR_HEADERS_OVERFLOW' + } + + /** A body exceeds the `bodyTimeout` option. */ + export class BodyTimeoutError extends UndiciError { + name: 'BodyTimeoutError'; + code: 'UND_ERR_BODY_TIMEOUT'; + } + + export class ResponseStatusCodeError extends UndiciError { + constructor ( + message?: string, + statusCode?: number, + headers?: IncomingHttpHeaders | string[] | null, + body?: null | Record | string + ); + name: 'ResponseStatusCodeError'; + code: 'UND_ERR_RESPONSE_STATUS_CODE'; + body: null | Record | string + status: number + statusCode: number + headers: IncomingHttpHeaders | string[] | null; + } + + /** Passed an invalid argument. */ + export class InvalidArgumentError extends UndiciError { + name: 'InvalidArgumentError'; + code: 'UND_ERR_INVALID_ARG'; + } + + /** Returned an invalid value. */ + export class InvalidReturnValueError extends UndiciError { + name: 'InvalidReturnValueError'; + code: 'UND_ERR_INVALID_RETURN_VALUE'; + } + + /** The request has been aborted by the user. */ + export class RequestAbortedError extends UndiciError { + name: 'AbortError'; + code: 'UND_ERR_ABORTED'; + } + + /** Expected error with reason. */ + export class InformationalError extends UndiciError { + name: 'InformationalError'; + code: 'UND_ERR_INFO'; + } + + /** Request body length does not match content-length header. */ + export class RequestContentLengthMismatchError extends UndiciError { + name: 'RequestContentLengthMismatchError'; + code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'; + } + + /** Response body length does not match content-length header. */ + export class ResponseContentLengthMismatchError extends UndiciError { + name: 'ResponseContentLengthMismatchError'; + code: 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'; + } + + /** Trying to use a destroyed client. */ + export class ClientDestroyedError extends UndiciError { + name: 'ClientDestroyedError'; + code: 'UND_ERR_DESTROYED'; + } + + /** Trying to use a closed client. */ + export class ClientClosedError extends UndiciError { + name: 'ClientClosedError'; + code: 'UND_ERR_CLOSED'; + } + + /** There is an error with the socket. */ + export class SocketError extends UndiciError { + name: 'SocketError'; + code: 'UND_ERR_SOCKET'; + socket: Client.SocketInfo | null + } + + /** Encountered unsupported functionality. */ + export class NotSupportedError extends UndiciError { + name: 'NotSupportedError'; + code: 'UND_ERR_NOT_SUPPORTED'; + } + + /** No upstream has been added to the BalancedPool. */ + export class BalancedPoolMissingUpstreamError extends UndiciError { + name: 'MissingUpstreamError'; + code: 'UND_ERR_BPL_MISSING_UPSTREAM'; + } + + export class HTTPParserError extends UndiciError { + name: 'HTTPParserError'; + code: string; + } + + /** The response exceed the length allowed. */ + export class ResponseExceededMaxSizeError extends UndiciError { + name: 'ResponseExceededMaxSizeError'; + code: 'UND_ERR_RES_EXCEEDED_MAX_SIZE'; + } + + export class RequestRetryError extends UndiciError { + constructor ( + message: string, + statusCode: number, + headers?: IncomingHttpHeaders | string[] | null, + body?: null | Record | string + ); + name: 'RequestRetryError'; + code: 'UND_ERR_REQ_RETRY'; + statusCode: number; + data: { + count: number; + }; + headers: Record; + } + + export class SecureProxyConnectionError extends UndiciError { + name: 'SecureProxyConnectionError'; + code: 'UND_ERR_PRX_TLS'; + } +} diff --git a/node_modules/undici-types/eventsource.d.ts b/node_modules/undici-types/eventsource.d.ts new file mode 100644 index 0000000..eecda8c --- /dev/null +++ b/node_modules/undici-types/eventsource.d.ts @@ -0,0 +1,63 @@ +import { MessageEvent, ErrorEvent } from './websocket' +import Dispatcher from './dispatcher' + +import { + EventTarget, + Event, + EventListenerOptions, + AddEventListenerOptions, + EventListenerOrEventListenerObject +} from './patch' + +interface EventSourceEventMap { + error: ErrorEvent + message: MessageEvent + open: Event +} + +interface EventSource extends EventTarget { + close(): void + readonly CLOSED: 2 + readonly CONNECTING: 0 + readonly OPEN: 1 + onerror: (this: EventSource, ev: ErrorEvent) => any + onmessage: (this: EventSource, ev: MessageEvent) => any + onopen: (this: EventSource, ev: Event) => any + readonly readyState: 0 | 1 | 2 + readonly url: string + readonly withCredentials: boolean + + addEventListener( + type: K, + listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, + options?: boolean | AddEventListenerOptions + ): void + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void + removeEventListener( + type: K, + listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, + options?: boolean | EventListenerOptions + ): void + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions + ): void +} + +export declare const EventSource: { + prototype: EventSource + new (url: string | URL, init?: EventSourceInit): EventSource + readonly CLOSED: 2 + readonly CONNECTING: 0 + readonly OPEN: 1 +} + +interface EventSourceInit { + withCredentials?: boolean, + dispatcher?: Dispatcher +} diff --git a/node_modules/undici-types/fetch.d.ts b/node_modules/undici-types/fetch.d.ts new file mode 100644 index 0000000..7e94375 --- /dev/null +++ b/node_modules/undici-types/fetch.d.ts @@ -0,0 +1,209 @@ +// based on https://github.com/Ethan-Arrowood/undici-fetch/blob/249269714db874351589d2d364a0645d5160ae71/index.d.ts (MIT license) +// and https://github.com/node-fetch/node-fetch/blob/914ce6be5ec67a8bab63d68510aabf07cb818b6d/index.d.ts (MIT license) +/// + +import { Blob } from 'buffer' +import { URL, URLSearchParams } from 'url' +import { ReadableStream } from 'stream/web' +import { FormData } from './formdata' + +import Dispatcher from './dispatcher' + +export type RequestInfo = string | URL | Request + +export declare function fetch ( + input: RequestInfo, + init?: RequestInit +): Promise + +export type BodyInit = + | ArrayBuffer + | AsyncIterable + | Blob + | FormData + | Iterable + | NodeJS.ArrayBufferView + | URLSearchParams + | null + | string + +export class BodyMixin { + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + /** + * @deprecated This method is not recommended for parsing multipart/form-data bodies in server environments. + * It is recommended to use a library such as [@fastify/busboy](https://www.npmjs.com/package/@fastify/busboy) as follows: + * + * @example + * ```js + * import { Busboy } from '@fastify/busboy' + * import { Readable } from 'node:stream' + * + * const response = await fetch('...') + * const busboy = new Busboy({ headers: { 'content-type': response.headers.get('content-type') } }) + * + * // handle events emitted from `busboy` + * + * Readable.fromWeb(response.body).pipe(busboy) + * ``` + */ + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise +} + +export interface SpecIterator { + next(...args: [] | [TNext]): IteratorResult; +} + +export interface SpecIterableIterator extends SpecIterator { + [Symbol.iterator](): SpecIterableIterator; +} + +export interface SpecIterable { + [Symbol.iterator](): SpecIterator; +} + +export type HeadersInit = string[][] | Record> | Headers + +export declare class Headers implements SpecIterable<[string, string]> { + constructor (init?: HeadersInit) + readonly append: (name: string, value: string) => void + readonly delete: (name: string) => void + readonly get: (name: string) => string | null + readonly has: (name: string) => boolean + readonly set: (name: string, value: string) => void + readonly getSetCookie: () => string[] + readonly forEach: ( + callbackfn: (value: string, key: string, iterable: Headers) => void, + thisArg?: unknown + ) => void + + readonly keys: () => SpecIterableIterator + readonly values: () => SpecIterableIterator + readonly entries: () => SpecIterableIterator<[string, string]> + readonly [Symbol.iterator]: () => SpecIterableIterator<[string, string]> +} + +export type RequestCache = + | 'default' + | 'force-cache' + | 'no-cache' + | 'no-store' + | 'only-if-cached' + | 'reload' + +export type RequestCredentials = 'omit' | 'include' | 'same-origin' + +type RequestDestination = + | '' + | 'audio' + | 'audioworklet' + | 'document' + | 'embed' + | 'font' + | 'image' + | 'manifest' + | 'object' + | 'paintworklet' + | 'report' + | 'script' + | 'sharedworker' + | 'style' + | 'track' + | 'video' + | 'worker' + | 'xslt' + +export interface RequestInit { + method?: string + keepalive?: boolean + headers?: HeadersInit + body?: BodyInit | null + redirect?: RequestRedirect + integrity?: string + signal?: AbortSignal | null + credentials?: RequestCredentials + mode?: RequestMode + referrer?: string + referrerPolicy?: ReferrerPolicy + window?: null + dispatcher?: Dispatcher + duplex?: RequestDuplex +} + +export type ReferrerPolicy = + | '' + | 'no-referrer' + | 'no-referrer-when-downgrade' + | 'origin' + | 'origin-when-cross-origin' + | 'same-origin' + | 'strict-origin' + | 'strict-origin-when-cross-origin' + | 'unsafe-url'; + +export type RequestMode = 'cors' | 'navigate' | 'no-cors' | 'same-origin' + +export type RequestRedirect = 'error' | 'follow' | 'manual' + +export type RequestDuplex = 'half' + +export declare class Request extends BodyMixin { + constructor (input: RequestInfo, init?: RequestInit) + + readonly cache: RequestCache + readonly credentials: RequestCredentials + readonly destination: RequestDestination + readonly headers: Headers + readonly integrity: string + readonly method: string + readonly mode: RequestMode + readonly redirect: RequestRedirect + readonly referrer: string + readonly referrerPolicy: ReferrerPolicy + readonly url: string + + readonly keepalive: boolean + readonly signal: AbortSignal + readonly duplex: RequestDuplex + + readonly clone: () => Request +} + +export interface ResponseInit { + readonly status?: number + readonly statusText?: string + readonly headers?: HeadersInit +} + +export type ResponseType = + | 'basic' + | 'cors' + | 'default' + | 'error' + | 'opaque' + | 'opaqueredirect' + +export type ResponseRedirectStatus = 301 | 302 | 303 | 307 | 308 + +export declare class Response extends BodyMixin { + constructor (body?: BodyInit, init?: ResponseInit) + + readonly headers: Headers + readonly ok: boolean + readonly status: number + readonly statusText: string + readonly type: ResponseType + readonly url: string + readonly redirected: boolean + + readonly clone: () => Response + + static error (): Response + static json(data: any, init?: ResponseInit): Response + static redirect (url: string | URL, status: ResponseRedirectStatus): Response +} diff --git a/node_modules/undici-types/file.d.ts b/node_modules/undici-types/file.d.ts new file mode 100644 index 0000000..c695b7a --- /dev/null +++ b/node_modules/undici-types/file.d.ts @@ -0,0 +1,39 @@ +// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/File.ts (MIT) +/// + +import { Blob } from 'buffer' + +export interface BlobPropertyBag { + type?: string + endings?: 'native' | 'transparent' +} + +export interface FilePropertyBag extends BlobPropertyBag { + /** + * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. + */ + lastModified?: number +} + +export declare class File extends Blob { + /** + * Creates a new File instance. + * + * @param fileBits An `Array` strings, or [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). + * @param fileName The name of the file. + * @param options An options object containing optional attributes for the file. + */ + constructor(fileBits: ReadonlyArray, fileName: string, options?: FilePropertyBag) + + /** + * Name of the file referenced by the File object. + */ + readonly name: string + + /** + * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. + */ + readonly lastModified: number + + readonly [Symbol.toStringTag]: string +} diff --git a/node_modules/undici-types/filereader.d.ts b/node_modules/undici-types/filereader.d.ts new file mode 100644 index 0000000..f05d231 --- /dev/null +++ b/node_modules/undici-types/filereader.d.ts @@ -0,0 +1,54 @@ +/// + +import { Blob } from 'buffer' +import { DOMException, Event, EventInit, EventTarget } from './patch' + +export declare class FileReader { + __proto__: EventTarget & FileReader + + constructor () + + readAsArrayBuffer (blob: Blob): void + readAsBinaryString (blob: Blob): void + readAsText (blob: Blob, encoding?: string): void + readAsDataURL (blob: Blob): void + + abort (): void + + static readonly EMPTY = 0 + static readonly LOADING = 1 + static readonly DONE = 2 + + readonly EMPTY = 0 + readonly LOADING = 1 + readonly DONE = 2 + + readonly readyState: number + + readonly result: string | ArrayBuffer | null + + readonly error: DOMException | null + + onloadstart: null | ((this: FileReader, event: ProgressEvent) => void) + onprogress: null | ((this: FileReader, event: ProgressEvent) => void) + onload: null | ((this: FileReader, event: ProgressEvent) => void) + onabort: null | ((this: FileReader, event: ProgressEvent) => void) + onerror: null | ((this: FileReader, event: ProgressEvent) => void) + onloadend: null | ((this: FileReader, event: ProgressEvent) => void) +} + +export interface ProgressEventInit extends EventInit { + lengthComputable?: boolean + loaded?: number + total?: number +} + +export declare class ProgressEvent { + __proto__: Event & ProgressEvent + + constructor (type: string, eventInitDict?: ProgressEventInit) + + readonly lengthComputable: boolean + readonly loaded: number + readonly total: number +} diff --git a/node_modules/undici-types/formdata.d.ts b/node_modules/undici-types/formdata.d.ts new file mode 100644 index 0000000..e676b11 --- /dev/null +++ b/node_modules/undici-types/formdata.d.ts @@ -0,0 +1,108 @@ +// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/FormData.ts (MIT) +/// + +import { File } from './file' +import { SpecIterableIterator } from './fetch' + +/** + * A `string` or `File` that represents a single value from a set of `FormData` key-value pairs. + */ +declare type FormDataEntryValue = string | File + +/** + * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using fetch(). + */ +export declare class FormData { + /** + * Appends a new value onto an existing key inside a FormData object, + * or adds the key if it does not already exist. + * + * The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + */ + append(name: string, value: unknown, fileName?: string): void + + /** + * Set a new value for an existing key inside FormData, + * or add the new field if it does not already exist. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + * + */ + set(name: string, value: unknown, fileName?: string): void + + /** + * Returns the first value associated with a given key from within a `FormData` object. + * If you expect multiple values and want all of them, use the `getAll()` method instead. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns A `FormDataEntryValue` containing the value. If the key doesn't exist, the method returns null. + */ + get(name: string): FormDataEntryValue | null + + /** + * Returns all the values associated with a given key from within a `FormData` object. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list. + */ + getAll(name: string): FormDataEntryValue[] + + /** + * Returns a boolean stating whether a `FormData` object contains a certain key. + * + * @param name A string representing the name of the key you want to test for. + * + * @return A boolean value. + */ + has(name: string): boolean + + /** + * Deletes a key and its value(s) from a `FormData` object. + * + * @param name The name of the key you want to delete. + */ + delete(name: string): void + + /** + * Executes given callback function for each field of the FormData instance + */ + forEach: ( + callbackfn: (value: FormDataEntryValue, key: string, iterable: FormData) => void, + thisArg?: unknown + ) => void + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object. + * Each key is a `string`. + */ + keys: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object. + * Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + values: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs. + * The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + entries: () => SpecIterableIterator<[string, FormDataEntryValue]> + + /** + * An alias for FormData#entries() + */ + [Symbol.iterator]: () => SpecIterableIterator<[string, FormDataEntryValue]> + + readonly [Symbol.toStringTag]: string +} diff --git a/node_modules/undici-types/global-dispatcher.d.ts b/node_modules/undici-types/global-dispatcher.d.ts new file mode 100644 index 0000000..728f95c --- /dev/null +++ b/node_modules/undici-types/global-dispatcher.d.ts @@ -0,0 +1,9 @@ +import Dispatcher from "./dispatcher"; + +export { + getGlobalDispatcher, + setGlobalDispatcher +} + +declare function setGlobalDispatcher(dispatcher: DispatcherImplementation): void; +declare function getGlobalDispatcher(): Dispatcher; diff --git a/node_modules/undici-types/global-origin.d.ts b/node_modules/undici-types/global-origin.d.ts new file mode 100644 index 0000000..322542d --- /dev/null +++ b/node_modules/undici-types/global-origin.d.ts @@ -0,0 +1,7 @@ +export { + setGlobalOrigin, + getGlobalOrigin +} + +declare function setGlobalOrigin(origin: string | URL | undefined): void; +declare function getGlobalOrigin(): URL | undefined; \ No newline at end of file diff --git a/node_modules/undici-types/handlers.d.ts b/node_modules/undici-types/handlers.d.ts new file mode 100644 index 0000000..afcda9a --- /dev/null +++ b/node_modules/undici-types/handlers.d.ts @@ -0,0 +1,15 @@ +import Dispatcher from "./dispatcher"; + +export declare class RedirectHandler implements Dispatcher.DispatchHandlers { + constructor( + dispatch: Dispatcher, + maxRedirections: number, + opts: Dispatcher.DispatchOptions, + handler: Dispatcher.DispatchHandlers, + redirectionLimitReached: boolean + ); +} + +export declare class DecoratorHandler implements Dispatcher.DispatchHandlers { + constructor(handler: Dispatcher.DispatchHandlers); +} diff --git a/node_modules/undici-types/header.d.ts b/node_modules/undici-types/header.d.ts new file mode 100644 index 0000000..bfdb329 --- /dev/null +++ b/node_modules/undici-types/header.d.ts @@ -0,0 +1,4 @@ +/** + * The header type declaration of `undici`. + */ +export type IncomingHttpHeaders = Record; diff --git a/node_modules/undici-types/index.d.ts b/node_modules/undici-types/index.d.ts new file mode 100644 index 0000000..f6be35c --- /dev/null +++ b/node_modules/undici-types/index.d.ts @@ -0,0 +1,71 @@ +import Dispatcher from'./dispatcher' +import { setGlobalDispatcher, getGlobalDispatcher } from './global-dispatcher' +import { setGlobalOrigin, getGlobalOrigin } from './global-origin' +import Pool from'./pool' +import { RedirectHandler, DecoratorHandler } from './handlers' + +import BalancedPool from './balanced-pool' +import Client from'./client' +import buildConnector from'./connector' +import errors from'./errors' +import Agent from'./agent' +import MockClient from'./mock-client' +import MockPool from'./mock-pool' +import MockAgent from'./mock-agent' +import mockErrors from'./mock-errors' +import ProxyAgent from'./proxy-agent' +import EnvHttpProxyAgent from './env-http-proxy-agent' +import RetryHandler from'./retry-handler' +import RetryAgent from'./retry-agent' +import { request, pipeline, stream, connect, upgrade } from './api' +import interceptors from './interceptors' + +export * from './util' +export * from './cookies' +export * from './eventsource' +export * from './fetch' +export * from './file' +export * from './filereader' +export * from './formdata' +export * from './diagnostics-channel' +export * from './websocket' +export * from './content-type' +export * from './cache' +export { Interceptable } from './mock-interceptor' + +export { Dispatcher, BalancedPool, Pool, Client, buildConnector, errors, Agent, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, interceptors, MockClient, MockPool, MockAgent, mockErrors, ProxyAgent, EnvHttpProxyAgent, RedirectHandler, DecoratorHandler, RetryHandler, RetryAgent } +export default Undici + +declare namespace Undici { + var Dispatcher: typeof import('./dispatcher').default + var Pool: typeof import('./pool').default; + var RedirectHandler: typeof import ('./handlers').RedirectHandler + var DecoratorHandler: typeof import ('./handlers').DecoratorHandler + var RetryHandler: typeof import ('./retry-handler').default + var createRedirectInterceptor: typeof import ('./interceptors').default.createRedirectInterceptor + var BalancedPool: typeof import('./balanced-pool').default; + var Client: typeof import('./client').default; + var buildConnector: typeof import('./connector').default; + var errors: typeof import('./errors').default; + var Agent: typeof import('./agent').default; + var setGlobalDispatcher: typeof import('./global-dispatcher').setGlobalDispatcher; + var getGlobalDispatcher: typeof import('./global-dispatcher').getGlobalDispatcher; + var request: typeof import('./api').request; + var stream: typeof import('./api').stream; + var pipeline: typeof import('./api').pipeline; + var connect: typeof import('./api').connect; + var upgrade: typeof import('./api').upgrade; + var MockClient: typeof import('./mock-client').default; + var MockPool: typeof import('./mock-pool').default; + var MockAgent: typeof import('./mock-agent').default; + var mockErrors: typeof import('./mock-errors').default; + var fetch: typeof import('./fetch').fetch; + var Headers: typeof import('./fetch').Headers; + var Response: typeof import('./fetch').Response; + var Request: typeof import('./fetch').Request; + var FormData: typeof import('./formdata').FormData; + var File: typeof import('./file').File; + var FileReader: typeof import('./filereader').FileReader; + var caches: typeof import('./cache').caches; + var interceptors: typeof import('./interceptors').default; +} diff --git a/node_modules/undici-types/interceptors.d.ts b/node_modules/undici-types/interceptors.d.ts new file mode 100644 index 0000000..fab6da0 --- /dev/null +++ b/node_modules/undici-types/interceptors.d.ts @@ -0,0 +1,15 @@ +import Dispatcher from "./dispatcher"; +import RetryHandler from "./retry-handler"; + +export default Interceptors; + +declare namespace Interceptors { + export type DumpInterceptorOpts = { maxSize?: number } + export type RetryInterceptorOpts = RetryHandler.RetryOptions + export type RedirectInterceptorOpts = { maxRedirections?: number } + + export function createRedirectInterceptor(opts: RedirectInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function dump(opts?: DumpInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function retry(opts?: RetryInterceptorOpts): Dispatcher.DispatcherComposeInterceptor + export function redirect(opts?: RedirectInterceptorOpts): Dispatcher.DispatcherComposeInterceptor +} diff --git a/node_modules/undici-types/mock-agent.d.ts b/node_modules/undici-types/mock-agent.d.ts new file mode 100644 index 0000000..98cd645 --- /dev/null +++ b/node_modules/undici-types/mock-agent.d.ts @@ -0,0 +1,50 @@ +import Agent from './agent' +import Dispatcher from './dispatcher' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import MockDispatch = MockInterceptor.MockDispatch; + +export default MockAgent + +interface PendingInterceptor extends MockDispatch { + origin: string; +} + +/** A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. */ +declare class MockAgent extends Dispatcher { + constructor(options?: MockAgent.Options) + /** Creates and retrieves mock Dispatcher instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. */ + get(origin: string): TInterceptable; + get(origin: RegExp): TInterceptable; + get(origin: ((origin: string) => boolean)): TInterceptable; + /** Dispatches a mocked request. */ + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock agent and waits for registered mock pools and clients to also close before resolving. */ + close(): Promise; + /** Disables mocking in MockAgent. */ + deactivate(): void; + /** Enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. */ + activate(): void; + /** Define host matchers so only matching requests that aren't intercepted by the mock dispatchers will be attempted. */ + enableNetConnect(): void; + enableNetConnect(host: string): void; + enableNetConnect(host: RegExp): void; + enableNetConnect(host: ((host: string) => boolean)): void; + /** Causes all requests to throw when requests are not matched in a MockAgent intercept. */ + disableNetConnect(): void; + pendingInterceptors(): PendingInterceptor[]; + assertNoPendingInterceptors(options?: { + pendingInterceptorsFormatter?: PendingInterceptorsFormatter; + }): void; +} + +interface PendingInterceptorsFormatter { + format(pendingInterceptors: readonly PendingInterceptor[]): string; +} + +declare namespace MockAgent { + /** MockAgent options. */ + export interface Options extends Agent.Options { + /** A custom agent to be encapsulated by the MockAgent. */ + agent?: Agent; + } +} diff --git a/node_modules/undici-types/mock-client.d.ts b/node_modules/undici-types/mock-client.d.ts new file mode 100644 index 0000000..51d008c --- /dev/null +++ b/node_modules/undici-types/mock-client.d.ts @@ -0,0 +1,25 @@ +import Client from './client' +import Dispatcher from './dispatcher' +import MockAgent from './mock-agent' +import { MockInterceptor, Interceptable } from './mock-interceptor' + +export default MockClient + +/** MockClient extends the Client API and allows one to mock requests. */ +declare class MockClient extends Client implements Interceptable { + constructor(origin: string, options: MockClient.Options); + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept(options: MockInterceptor.Options): MockInterceptor; + /** Dispatches a mocked request. */ + dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock client and gracefully waits for enqueued requests to complete. */ + close(): Promise; +} + +declare namespace MockClient { + /** MockClient options. */ + export interface Options extends Client.Options { + /** The agent to associate this MockClient with. */ + agent: MockAgent; + } +} diff --git a/node_modules/undici-types/mock-errors.d.ts b/node_modules/undici-types/mock-errors.d.ts new file mode 100644 index 0000000..3d9e727 --- /dev/null +++ b/node_modules/undici-types/mock-errors.d.ts @@ -0,0 +1,12 @@ +import Errors from './errors' + +export default MockErrors + +declare namespace MockErrors { + /** The request does not match any registered mock dispatches. */ + export class MockNotMatchedError extends Errors.UndiciError { + constructor(message?: string); + name: 'MockNotMatchedError'; + code: 'UND_MOCK_ERR_MOCK_NOT_MATCHED'; + } +} diff --git a/node_modules/undici-types/mock-interceptor.d.ts b/node_modules/undici-types/mock-interceptor.d.ts new file mode 100644 index 0000000..33f3f14 --- /dev/null +++ b/node_modules/undici-types/mock-interceptor.d.ts @@ -0,0 +1,93 @@ +import { IncomingHttpHeaders } from './header' +import Dispatcher from './dispatcher'; +import { BodyInit, Headers } from './fetch' + +export { + Interceptable, + MockInterceptor, + MockScope +} + +/** The scope associated with a mock dispatch. */ +declare class MockScope { + constructor(mockDispatch: MockInterceptor.MockDispatch); + /** Delay a reply by a set amount of time in ms. */ + delay(waitInMs: number): MockScope; + /** Persist the defined mock data for the associated reply. It will return the defined mock data indefinitely. */ + persist(): MockScope; + /** Define a reply for a set amount of matching requests. */ + times(repeatTimes: number): MockScope; +} + +/** The interceptor for a Mock. */ +declare class MockInterceptor { + constructor(options: MockInterceptor.Options, mockDispatches: MockInterceptor.MockDispatch[]); + /** Mock an undici request with the defined reply. */ + reply(replyOptionsCallback: MockInterceptor.MockReplyOptionsCallback): MockScope; + reply( + statusCode: number, + data?: TData | Buffer | string | MockInterceptor.MockResponseDataHandler, + responseOptions?: MockInterceptor.MockResponseOptions + ): MockScope; + /** Mock an undici request by throwing the defined reply error. */ + replyWithError(error: TError): MockScope; + /** Set default reply headers on the interceptor for subsequent mocked replies. */ + defaultReplyHeaders(headers: IncomingHttpHeaders): MockInterceptor; + /** Set default reply trailers on the interceptor for subsequent mocked replies. */ + defaultReplyTrailers(trailers: Record): MockInterceptor; + /** Set automatically calculated content-length header on subsequent mocked replies. */ + replyContentLength(): MockInterceptor; +} + +declare namespace MockInterceptor { + /** MockInterceptor options. */ + export interface Options { + /** Path to intercept on. */ + path: string | RegExp | ((path: string) => boolean); + /** Method to intercept on. Defaults to GET. */ + method?: string | RegExp | ((method: string) => boolean); + /** Body to intercept on. */ + body?: string | RegExp | ((body: string) => boolean); + /** Headers to intercept on. */ + headers?: Record boolean)> | ((headers: Record) => boolean); + /** Query params to intercept on */ + query?: Record; + } + export interface MockDispatch extends Options { + times: number | null; + persist: boolean; + consumed: boolean; + data: MockDispatchData; + } + export interface MockDispatchData extends MockResponseOptions { + error: TError | null; + statusCode?: number; + data?: TData | string; + } + export interface MockResponseOptions { + headers?: IncomingHttpHeaders; + trailers?: Record; + } + + export interface MockResponseCallbackOptions { + path: string; + method: string; + headers?: Headers | Record; + origin?: string; + body?: BodyInit | Dispatcher.DispatchOptions['body'] | null; + maxRedirections?: number; + } + + export type MockResponseDataHandler = ( + opts: MockResponseCallbackOptions + ) => TData | Buffer | string; + + export type MockReplyOptionsCallback = ( + opts: MockResponseCallbackOptions + ) => { statusCode: number, data?: TData | Buffer | string, responseOptions?: MockResponseOptions } +} + +interface Interceptable extends Dispatcher { + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept(options: MockInterceptor.Options): MockInterceptor; +} diff --git a/node_modules/undici-types/mock-pool.d.ts b/node_modules/undici-types/mock-pool.d.ts new file mode 100644 index 0000000..39e709a --- /dev/null +++ b/node_modules/undici-types/mock-pool.d.ts @@ -0,0 +1,25 @@ +import Pool from './pool' +import MockAgent from './mock-agent' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import Dispatcher from './dispatcher' + +export default MockPool + +/** MockPool extends the Pool API and allows one to mock requests. */ +declare class MockPool extends Pool implements Interceptable { + constructor(origin: string, options: MockPool.Options); + /** Intercepts any matching requests that use the same origin as this mock pool. */ + intercept(options: MockInterceptor.Options): MockInterceptor; + /** Dispatches a mocked request. */ + dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock pool and gracefully waits for enqueued requests to complete. */ + close(): Promise; +} + +declare namespace MockPool { + /** MockPool options. */ + export interface Options extends Pool.Options { + /** The agent to associate this MockPool with. */ + agent: MockAgent; + } +} diff --git a/node_modules/undici-types/package.json b/node_modules/undici-types/package.json new file mode 100644 index 0000000..4010eee --- /dev/null +++ b/node_modules/undici-types/package.json @@ -0,0 +1,55 @@ +{ + "name": "undici-types", + "version": "6.19.8", + "description": "A stand-alone types package for Undici", + "homepage": "https://undici.nodejs.org", + "bugs": { + "url": "https://github.com/nodejs/undici/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/nodejs/undici.git" + }, + "license": "MIT", + "types": "index.d.ts", + "files": [ + "*.d.ts" + ], + "contributors": [ + { + "name": "Daniele Belardi", + "url": "https://github.com/dnlup", + "author": true + }, + { + "name": "Ethan Arrowood", + "url": "https://github.com/ethan-arrowood", + "author": true + }, + { + "name": "Matteo Collina", + "url": "https://github.com/mcollina", + "author": true + }, + { + "name": "Matthew Aitken", + "url": "https://github.com/KhafraDev", + "author": true + }, + { + "name": "Robert Nagy", + "url": "https://github.com/ronag", + "author": true + }, + { + "name": "Szymon Marczak", + "url": "https://github.com/szmarczak", + "author": true + }, + { + "name": "Tomas Della Vedova", + "url": "https://github.com/delvedor", + "author": true + } + ] +} \ No newline at end of file diff --git a/node_modules/undici-types/patch.d.ts b/node_modules/undici-types/patch.d.ts new file mode 100644 index 0000000..3871acf --- /dev/null +++ b/node_modules/undici-types/patch.d.ts @@ -0,0 +1,71 @@ +/// + +// See https://github.com/nodejs/undici/issues/1740 + +export type DOMException = typeof globalThis extends { DOMException: infer T } + ? T + : any + +export type EventTarget = typeof globalThis extends { EventTarget: infer T } + ? T + : { + addEventListener( + type: string, + listener: any, + options?: any, + ): void + dispatchEvent(event: Event): boolean + removeEventListener( + type: string, + listener: any, + options?: any | boolean, + ): void + } + +export type Event = typeof globalThis extends { Event: infer T } + ? T + : { + readonly bubbles: boolean + cancelBubble: () => void + readonly cancelable: boolean + readonly composed: boolean + composedPath(): [EventTarget?] + readonly currentTarget: EventTarget | null + readonly defaultPrevented: boolean + readonly eventPhase: 0 | 2 + readonly isTrusted: boolean + preventDefault(): void + returnValue: boolean + readonly srcElement: EventTarget | null + stopImmediatePropagation(): void + stopPropagation(): void + readonly target: EventTarget | null + readonly timeStamp: number + readonly type: string + } + +export interface EventInit { + bubbles?: boolean + cancelable?: boolean + composed?: boolean +} + +export interface EventListenerOptions { + capture?: boolean +} + +export interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean + passive?: boolean + signal?: AbortSignal +} + +export type EventListenerOrEventListenerObject = EventListener | EventListenerObject + +export interface EventListenerObject { + handleEvent (object: Event): void +} + +export interface EventListener { + (evt: Event): void +} diff --git a/node_modules/undici-types/pool-stats.d.ts b/node_modules/undici-types/pool-stats.d.ts new file mode 100644 index 0000000..8b6d2bf --- /dev/null +++ b/node_modules/undici-types/pool-stats.d.ts @@ -0,0 +1,19 @@ +import Pool from "./pool" + +export default PoolStats + +declare class PoolStats { + constructor(pool: Pool); + /** Number of open socket connections in this pool. */ + connected: number; + /** Number of open socket connections in this pool that do not have an active request. */ + free: number; + /** Number of pending requests across all clients in this pool. */ + pending: number; + /** Number of queued requests across all clients in this pool. */ + queued: number; + /** Number of currently active requests across all clients in this pool. */ + running: number; + /** Number of active, pending, or queued requests across all clients in this pool. */ + size: number; +} diff --git a/node_modules/undici-types/pool.d.ts b/node_modules/undici-types/pool.d.ts new file mode 100644 index 0000000..bad5ba0 --- /dev/null +++ b/node_modules/undici-types/pool.d.ts @@ -0,0 +1,39 @@ +import Client from './client' +import TPoolStats from './pool-stats' +import { URL } from 'url' +import Dispatcher from "./dispatcher"; + +export default Pool + +type PoolConnectOptions = Omit; + +declare class Pool extends Dispatcher { + constructor(url: string | URL, options?: Pool.Options) + /** `true` after `pool.close()` has been called. */ + closed: boolean; + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean; + /** Aggregate stats for a Pool. */ + readonly stats: TPoolStats; + + // Override dispatcher APIs. + override connect( + options: PoolConnectOptions + ): Promise; + override connect( + options: PoolConnectOptions, + callback: (err: Error | null, data: Dispatcher.ConnectData) => void + ): void; +} + +declare namespace Pool { + export type PoolStats = TPoolStats; + export interface Options extends Client.Options { + /** Default: `(origin, opts) => new Client(origin, opts)`. */ + factory?(origin: URL, opts: object): Dispatcher; + /** The max number of clients to create. `null` if no limit. Default `null`. */ + connections?: number | null; + + interceptors?: { Pool?: readonly Dispatcher.DispatchInterceptor[] } & Client.Options["interceptors"] + } +} diff --git a/node_modules/undici-types/proxy-agent.d.ts b/node_modules/undici-types/proxy-agent.d.ts new file mode 100644 index 0000000..32e3acb --- /dev/null +++ b/node_modules/undici-types/proxy-agent.d.ts @@ -0,0 +1,28 @@ +import Agent from './agent' +import buildConnector from './connector'; +import Dispatcher from './dispatcher' +import { IncomingHttpHeaders } from './header' + +export default ProxyAgent + +declare class ProxyAgent extends Dispatcher { + constructor(options: ProxyAgent.Options | string) + + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + close(): Promise; +} + +declare namespace ProxyAgent { + export interface Options extends Agent.Options { + uri: string; + /** + * @deprecated use opts.token + */ + auth?: string; + token?: string; + headers?: IncomingHttpHeaders; + requestTls?: buildConnector.BuildOptions; + proxyTls?: buildConnector.BuildOptions; + clientFactory?(origin: URL, opts: object): Dispatcher; + } +} diff --git a/node_modules/undici-types/readable.d.ts b/node_modules/undici-types/readable.d.ts new file mode 100644 index 0000000..a5fce8a --- /dev/null +++ b/node_modules/undici-types/readable.d.ts @@ -0,0 +1,60 @@ +import { Readable } from "stream"; +import { Blob } from 'buffer' + +export default BodyReadable + +declare class BodyReadable extends Readable { + constructor( + resume?: (this: Readable, size: number) => void | null, + abort?: () => void | null, + contentType?: string + ) + + /** Consumes and returns the body as a string + * https://fetch.spec.whatwg.org/#dom-body-text + */ + text(): Promise + + /** Consumes and returns the body as a JavaScript Object + * https://fetch.spec.whatwg.org/#dom-body-json + */ + json(): Promise + + /** Consumes and returns the body as a Blob + * https://fetch.spec.whatwg.org/#dom-body-blob + */ + blob(): Promise + + /** Consumes and returns the body as an ArrayBuffer + * https://fetch.spec.whatwg.org/#dom-body-arraybuffer + */ + arrayBuffer(): Promise + + /** Not implemented + * + * https://fetch.spec.whatwg.org/#dom-body-formdata + */ + formData(): Promise + + /** Returns true if the body is not null and the body has been consumed + * + * Otherwise, returns false + * + * https://fetch.spec.whatwg.org/#dom-body-bodyused + */ + readonly bodyUsed: boolean + + /** + * If body is null, it should return null as the body + * + * If body is not null, should return the body as a ReadableStream + * + * https://fetch.spec.whatwg.org/#dom-body-body + */ + readonly body: never | undefined + + /** Dumps the response body by reading `limit` number of bytes. + * @param opts.limit Number of bytes to read (optional) - Default: 262144 + */ + dump(opts?: { limit: number }): Promise +} diff --git a/node_modules/undici-types/retry-agent.d.ts b/node_modules/undici-types/retry-agent.d.ts new file mode 100644 index 0000000..963cea9 --- /dev/null +++ b/node_modules/undici-types/retry-agent.d.ts @@ -0,0 +1,8 @@ +import Dispatcher from './dispatcher' +import RetryHandler from './retry-handler' + +export default RetryAgent + +declare class RetryAgent extends Dispatcher { + constructor(dispatcher: Dispatcher, options?: RetryHandler.RetryOptions) +} diff --git a/node_modules/undici-types/retry-handler.d.ts b/node_modules/undici-types/retry-handler.d.ts new file mode 100644 index 0000000..e44b207 --- /dev/null +++ b/node_modules/undici-types/retry-handler.d.ts @@ -0,0 +1,116 @@ +import Dispatcher from "./dispatcher"; + +export default RetryHandler; + +declare class RetryHandler implements Dispatcher.DispatchHandlers { + constructor( + options: Dispatcher.DispatchOptions & { + retryOptions?: RetryHandler.RetryOptions; + }, + retryHandlers: RetryHandler.RetryHandlers + ); +} + +declare namespace RetryHandler { + export type RetryState = { counter: number; }; + + export type RetryContext = { + state: RetryState; + opts: Dispatcher.DispatchOptions & { + retryOptions?: RetryHandler.RetryOptions; + }; + } + + export type OnRetryCallback = (result?: Error | null) => void; + + export type RetryCallback = ( + err: Error, + context: { + state: RetryState; + opts: Dispatcher.DispatchOptions & { + retryOptions?: RetryHandler.RetryOptions; + }; + }, + callback: OnRetryCallback + ) => number | null; + + export interface RetryOptions { + /** + * Callback to be invoked on every retry iteration. + * It receives the error, current state of the retry object and the options object + * passed when instantiating the retry handler. + * + * @type {RetryCallback} + * @memberof RetryOptions + */ + retry?: RetryCallback; + /** + * Maximum number of retries to allow. + * + * @type {number} + * @memberof RetryOptions + * @default 5 + */ + maxRetries?: number; + /** + * Max number of milliseconds allow between retries + * + * @type {number} + * @memberof RetryOptions + * @default 30000 + */ + maxTimeout?: number; + /** + * Initial number of milliseconds to wait before retrying for the first time. + * + * @type {number} + * @memberof RetryOptions + * @default 500 + */ + minTimeout?: number; + /** + * Factior to multiply the timeout factor between retries. + * + * @type {number} + * @memberof RetryOptions + * @default 2 + */ + timeoutFactor?: number; + /** + * It enables to automatically infer timeout between retries based on the `Retry-After` header. + * + * @type {boolean} + * @memberof RetryOptions + * @default true + */ + retryAfter?: boolean; + /** + * HTTP methods to retry. + * + * @type {Dispatcher.HttpMethod[]} + * @memberof RetryOptions + * @default ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], + */ + methods?: Dispatcher.HttpMethod[]; + /** + * Error codes to be retried. e.g. `ECONNRESET`, `ENOTFOUND`, `ETIMEDOUT`, `ECONNREFUSED`, etc. + * + * @type {string[]} + * @default ['ECONNRESET','ECONNREFUSED','ENOTFOUND','ENETDOWN','ENETUNREACH','EHOSTDOWN','EHOSTUNREACH','EPIPE'] + */ + errorCodes?: string[]; + /** + * HTTP status codes to be retried. + * + * @type {number[]} + * @memberof RetryOptions + * @default [500, 502, 503, 504, 429], + */ + statusCodes?: number[]; + } + + export interface RetryHandlers { + dispatch: Dispatcher["dispatch"]; + handler: Dispatcher.DispatchHandlers; + } +} diff --git a/node_modules/undici-types/util.d.ts b/node_modules/undici-types/util.d.ts new file mode 100644 index 0000000..77cf147 --- /dev/null +++ b/node_modules/undici-types/util.d.ts @@ -0,0 +1,18 @@ +export namespace util { + /** + * Retrieves a header name and returns its lowercase value. + * @param value Header name + */ + export function headerNameToString(value: string | Buffer): string; + + /** + * Receives a header object and returns the parsed value. + * @param headers Header object + * @param obj Object to specify a proxy object. Used to assign parsed values. + * @returns If `obj` is specified, it is equivalent to `obj`. + */ + export function parseHeaders( + headers: (Buffer | string | (Buffer | string)[])[], + obj?: Record + ): Record; +} diff --git a/node_modules/undici-types/webidl.d.ts b/node_modules/undici-types/webidl.d.ts new file mode 100644 index 0000000..8a23a85 --- /dev/null +++ b/node_modules/undici-types/webidl.d.ts @@ -0,0 +1,222 @@ +// These types are not exported, and are only used internally + +/** + * Take in an unknown value and return one that is of type T + */ +type Converter = (object: unknown) => T + +type SequenceConverter = (object: unknown, iterable?: IterableIterator) => T[] + +type RecordConverter = (object: unknown) => Record + +interface ConvertToIntOpts { + clamp?: boolean + enforceRange?: boolean +} + +interface WebidlErrors { + exception (opts: { header: string, message: string }): TypeError + /** + * @description Throw an error when conversion from one type to another has failed + */ + conversionFailed (opts: { + prefix: string + argument: string + types: string[] + }): TypeError + /** + * @description Throw an error when an invalid argument is provided + */ + invalidArgument (opts: { + prefix: string + value: string + type: string + }): TypeError +} + +interface WebidlUtil { + /** + * @see https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values + */ + Type (object: unknown): + | 'Undefined' + | 'Boolean' + | 'String' + | 'Symbol' + | 'Number' + | 'BigInt' + | 'Null' + | 'Object' + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + */ + ConvertToInt ( + V: unknown, + bitLength: number, + signedness: 'signed' | 'unsigned', + opts?: ConvertToIntOpts + ): number + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + */ + IntegerPart (N: number): number + + /** + * Stringifies {@param V} + */ + Stringify (V: any): string +} + +interface WebidlConverters { + /** + * @see https://webidl.spec.whatwg.org/#es-DOMString + */ + DOMString (V: unknown, prefix: string, argument: string, opts?: { + legacyNullToEmptyString: boolean + }): string + + /** + * @see https://webidl.spec.whatwg.org/#es-ByteString + */ + ByteString (V: unknown, prefix: string, argument: string): string + + /** + * @see https://webidl.spec.whatwg.org/#es-USVString + */ + USVString (V: unknown): string + + /** + * @see https://webidl.spec.whatwg.org/#es-boolean + */ + boolean (V: unknown): boolean + + /** + * @see https://webidl.spec.whatwg.org/#es-any + */ + any (V: Value): Value + + /** + * @see https://webidl.spec.whatwg.org/#es-long-long + */ + ['long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long-long + */ + ['unsigned long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long + */ + ['unsigned long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-short + */ + ['unsigned short'] (V: unknown, opts?: ConvertToIntOpts): number + + /** + * @see https://webidl.spec.whatwg.org/#idl-ArrayBuffer + */ + ArrayBuffer (V: unknown): ArrayBufferLike + ArrayBuffer (V: unknown, opts: { allowShared: false }): ArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + TypedArray ( + V: unknown, + TypedArray: NodeJS.TypedArray | ArrayBufferLike + ): NodeJS.TypedArray | ArrayBufferLike + TypedArray ( + V: unknown, + TypedArray: NodeJS.TypedArray | ArrayBufferLike, + opts?: { allowShared: false } + ): NodeJS.TypedArray | ArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + DataView (V: unknown, opts?: { allowShared: boolean }): DataView + + /** + * @see https://webidl.spec.whatwg.org/#BufferSource + */ + BufferSource ( + V: unknown, + opts?: { allowShared: boolean } + ): NodeJS.TypedArray | ArrayBufferLike | DataView + + ['sequence']: SequenceConverter + + ['sequence>']: SequenceConverter + + ['record']: RecordConverter + + [Key: string]: (...args: any[]) => unknown +} + +export interface Webidl { + errors: WebidlErrors + util: WebidlUtil + converters: WebidlConverters + + /** + * @description Performs a brand-check on {@param V} to ensure it is a + * {@param cls} object. + */ + brandCheck (V: unknown, cls: Interface, opts?: { strict?: boolean }): asserts V is Interface + + /** + * @see https://webidl.spec.whatwg.org/#es-sequence + * @description Convert a value, V, to a WebIDL sequence type. + */ + sequenceConverter (C: Converter): SequenceConverter + + illegalConstructor (): never + + /** + * @see https://webidl.spec.whatwg.org/#es-to-record + * @description Convert a value, V, to a WebIDL record type. + */ + recordConverter ( + keyConverter: Converter, + valueConverter: Converter + ): RecordConverter + + /** + * Similar to {@link Webidl.brandCheck} but allows skipping the check if third party + * interfaces are allowed. + */ + interfaceConverter (cls: Interface): ( + V: unknown, + opts?: { strict: boolean } + ) => asserts V is typeof cls + + // TODO(@KhafraDev): a type could likely be implemented that can infer the return type + // from the converters given? + /** + * Converts a value, V, to a WebIDL dictionary types. Allows limiting which keys are + * allowed, values allowed, optional and required keys. Auto converts the value to + * a type given a converter. + */ + dictionaryConverter (converters: { + key: string, + defaultValue?: () => unknown, + required?: boolean, + converter: (...args: unknown[]) => unknown, + allowedValues?: unknown[] + }[]): (V: unknown) => Record + + /** + * @see https://webidl.spec.whatwg.org/#idl-nullable-type + * @description allows a type, V, to be null + */ + nullableConverter ( + converter: Converter + ): (V: unknown) => ReturnType | null + + argumentLengthCheck (args: { length: number }, min: number, context: string): void +} diff --git a/node_modules/undici-types/websocket.d.ts b/node_modules/undici-types/websocket.d.ts new file mode 100644 index 0000000..d1be452 --- /dev/null +++ b/node_modules/undici-types/websocket.d.ts @@ -0,0 +1,152 @@ +/// + +import type { Blob } from 'buffer' +import type { MessagePort } from 'worker_threads' +import { + EventTarget, + Event, + EventInit, + EventListenerOptions, + AddEventListenerOptions, + EventListenerOrEventListenerObject +} from './patch' +import Dispatcher from './dispatcher' +import { HeadersInit } from './fetch' + +export type BinaryType = 'blob' | 'arraybuffer' + +interface WebSocketEventMap { + close: CloseEvent + error: ErrorEvent + message: MessageEvent + open: Event +} + +interface WebSocket extends EventTarget { + binaryType: BinaryType + + readonly bufferedAmount: number + readonly extensions: string + + onclose: ((this: WebSocket, ev: WebSocketEventMap['close']) => any) | null + onerror: ((this: WebSocket, ev: WebSocketEventMap['error']) => any) | null + onmessage: ((this: WebSocket, ev: WebSocketEventMap['message']) => any) | null + onopen: ((this: WebSocket, ev: WebSocketEventMap['open']) => any) | null + + readonly protocol: string + readonly readyState: number + readonly url: string + + close(code?: number, reason?: string): void + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void + + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number + + addEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | AddEventListenerOptions + ): void + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void + removeEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | EventListenerOptions + ): void + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions + ): void +} + +export declare const WebSocket: { + prototype: WebSocket + new (url: string | URL, protocols?: string | string[] | WebSocketInit): WebSocket + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number +} + +interface CloseEventInit extends EventInit { + code?: number + reason?: string + wasClean?: boolean +} + +interface CloseEvent extends Event { + readonly code: number + readonly reason: string + readonly wasClean: boolean +} + +export declare const CloseEvent: { + prototype: CloseEvent + new (type: string, eventInitDict?: CloseEventInit): CloseEvent +} + +interface MessageEventInit extends EventInit { + data?: T + lastEventId?: string + origin?: string + ports?: (typeof MessagePort)[] + source?: typeof MessagePort | null +} + +interface MessageEvent extends Event { + readonly data: T + readonly lastEventId: string + readonly origin: string + readonly ports: ReadonlyArray + readonly source: typeof MessagePort | null + initMessageEvent( + type: string, + bubbles?: boolean, + cancelable?: boolean, + data?: any, + origin?: string, + lastEventId?: string, + source?: typeof MessagePort | null, + ports?: (typeof MessagePort)[] + ): void; +} + +export declare const MessageEvent: { + prototype: MessageEvent + new(type: string, eventInitDict?: MessageEventInit): MessageEvent +} + +interface ErrorEventInit extends EventInit { + message?: string + filename?: string + lineno?: number + colno?: number + error?: any +} + +interface ErrorEvent extends Event { + readonly message: string + readonly filename: string + readonly lineno: number + readonly colno: number + readonly error: any +} + +export declare const ErrorEvent: { + prototype: ErrorEvent + new (type: string, eventInitDict?: ErrorEventInit): ErrorEvent +} + +interface WebSocketInit { + protocols?: string | string[], + dispatcher?: Dispatcher, + headers?: HeadersInit +} diff --git a/node_modules/update-browserslist-db/LICENSE b/node_modules/update-browserslist-db/LICENSE new file mode 100644 index 0000000..377ae1b --- /dev/null +++ b/node_modules/update-browserslist-db/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright 2022 Andrey Sitnik and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/update-browserslist-db/README.md b/node_modules/update-browserslist-db/README.md new file mode 100644 index 0000000..c4155c9 --- /dev/null +++ b/node_modules/update-browserslist-db/README.md @@ -0,0 +1,22 @@ +# Update Browserslist DB + +Browserslist logo by Anton Popov + +CLI tool to update `caniuse-lite` with browsers DB +from [Browserslist](https://github.com/browserslist/browserslist/) config. + +Some queries like `last 2 versions` or `>1%` depend on actual data +from `caniuse-lite`. + +```sh +npx update-browserslist-db@latest +``` + + + Sponsored by Evil Martians + + +## Docs +Read full docs **[here](https://github.com/browserslist/update-db#readme)**. diff --git a/node_modules/update-browserslist-db/check-npm-version.js b/node_modules/update-browserslist-db/check-npm-version.js new file mode 100644 index 0000000..b06811a --- /dev/null +++ b/node_modules/update-browserslist-db/check-npm-version.js @@ -0,0 +1,17 @@ +let { execSync } = require('child_process') +let pico = require('picocolors') + +try { + let version = parseInt(execSync('npm -v')) + if (version <= 6) { + process.stderr.write( + pico.red( + 'Update npm or call ' + + pico.yellow('npx browserslist@latest --update-db') + + '\n' + ) + ) + process.exit(1) + } + // eslint-disable-next-line no-unused-vars +} catch (e) {} diff --git a/node_modules/update-browserslist-db/cli.js b/node_modules/update-browserslist-db/cli.js new file mode 100755 index 0000000..1388e94 --- /dev/null +++ b/node_modules/update-browserslist-db/cli.js @@ -0,0 +1,42 @@ +#!/usr/bin/env node + +let { readFileSync } = require('fs') +let { join } = require('path') + +require('./check-npm-version') +let updateDb = require('./') + +const ROOT = __dirname + +function getPackage() { + return JSON.parse(readFileSync(join(ROOT, 'package.json'))) +} + +let args = process.argv.slice(2) + +let USAGE = 'Usage:\n npx update-browserslist-db\n' + +function isArg(arg) { + return args.some(i => i === arg) +} + +function error(msg) { + process.stderr.write('update-browserslist-db: ' + msg + '\n') + process.exit(1) +} + +if (isArg('--help') || isArg('-h')) { + process.stdout.write(getPackage().description + '.\n\n' + USAGE + '\n') +} else if (isArg('--version') || isArg('-v')) { + process.stdout.write('browserslist-lint ' + getPackage().version + '\n') +} else { + try { + updateDb() + } catch (e) { + if (e.name === 'BrowserslistUpdateError') { + error(e.message) + } else { + throw e + } + } +} diff --git a/node_modules/update-browserslist-db/index.d.ts b/node_modules/update-browserslist-db/index.d.ts new file mode 100644 index 0000000..05ef411 --- /dev/null +++ b/node_modules/update-browserslist-db/index.d.ts @@ -0,0 +1,6 @@ +/** + * Run update and print output to terminal. + */ +declare function updateDb(print?: (str: string) => void): Promise + +export = updateDb diff --git a/node_modules/update-browserslist-db/index.js b/node_modules/update-browserslist-db/index.js new file mode 100644 index 0000000..f13c6e6 --- /dev/null +++ b/node_modules/update-browserslist-db/index.js @@ -0,0 +1,343 @@ +let { existsSync, readFileSync, writeFileSync } = require('fs') +let { execSync } = require('child_process') +let { join } = require('path') +let escalade = require('escalade/sync') +let pico = require('picocolors') + +const { detectEOL, detectIndent } = require('./utils') + +function BrowserslistUpdateError(message) { + this.name = 'BrowserslistUpdateError' + this.message = message + this.browserslist = true + if (Error.captureStackTrace) { + Error.captureStackTrace(this, BrowserslistUpdateError) + } +} + +BrowserslistUpdateError.prototype = Error.prototype + +// Check if HADOOP_HOME is set to determine if this is running in a Hadoop environment +const IsHadoopExists = !!process.env.HADOOP_HOME +const yarnCommand = IsHadoopExists ? 'yarnpkg' : 'yarn' + +/* c8 ignore next 3 */ +function defaultPrint(str) { + process.stdout.write(str) +} + +function detectLockfile() { + let packageDir = escalade('.', (dir, names) => { + return names.indexOf('package.json') !== -1 ? dir : '' + }) + + if (!packageDir) { + throw new BrowserslistUpdateError( + 'Cannot find package.json. ' + + 'Is this the right directory to run `npx update-browserslist-db` in?' + ) + } + + let lockfileNpm = join(packageDir, 'package-lock.json') + let lockfileShrinkwrap = join(packageDir, 'npm-shrinkwrap.json') + let lockfileYarn = join(packageDir, 'yarn.lock') + let lockfilePnpm = join(packageDir, 'pnpm-lock.yaml') + let lockfileBun = join(packageDir, 'bun.lockb') + + if (existsSync(lockfilePnpm)) { + return { file: lockfilePnpm, mode: 'pnpm' } + } else if (existsSync(lockfileBun)) { + return { file: lockfileBun, mode: 'bun' } + } else if (existsSync(lockfileNpm)) { + return { file: lockfileNpm, mode: 'npm' } + } else if (existsSync(lockfileYarn)) { + let lock = { file: lockfileYarn, mode: 'yarn' } + lock.content = readFileSync(lock.file).toString() + lock.version = /# yarn lockfile v1/.test(lock.content) ? 1 : 2 + return lock + } else if (existsSync(lockfileShrinkwrap)) { + return { file: lockfileShrinkwrap, mode: 'npm' } + } + throw new BrowserslistUpdateError( + 'No lockfile found. Run "npm install", "yarn install" or "pnpm install"' + ) +} + +function getLatestInfo(lock) { + if (lock.mode === 'yarn') { + if (lock.version === 1) { + return JSON.parse( + execSync(yarnCommand + ' info caniuse-lite --json').toString() + ).data + } else { + return JSON.parse( + execSync(yarnCommand + ' npm info caniuse-lite --json').toString() + ) + } + } + if (lock.mode === 'pnpm') { + return JSON.parse(execSync('pnpm info caniuse-lite --json').toString()) + } + if (lock.mode === 'bun') { + // TO-DO: No 'bun info' yet. Created issue: https://github.com/oven-sh/bun/issues/12280 + return JSON.parse(execSync(' npm info caniuse-lite --json').toString()) + } + + return JSON.parse(execSync('npm show caniuse-lite --json').toString()) +} + +function getBrowsers() { + let browserslist = require('browserslist') + return browserslist().reduce((result, entry) => { + if (!result[entry[0]]) { + result[entry[0]] = [] + } + result[entry[0]].push(entry[1]) + return result + }, {}) +} + +function diffBrowsers(old, current) { + let browsers = Object.keys(old).concat( + Object.keys(current).filter(browser => old[browser] === undefined) + ) + return browsers + .map(browser => { + let oldVersions = old[browser] || [] + let currentVersions = current[browser] || [] + let common = oldVersions.filter(v => currentVersions.includes(v)) + let added = currentVersions.filter(v => !common.includes(v)) + let removed = oldVersions.filter(v => !common.includes(v)) + return removed + .map(v => pico.red('- ' + browser + ' ' + v)) + .concat(added.map(v => pico.green('+ ' + browser + ' ' + v))) + }) + .reduce((result, array) => result.concat(array), []) + .join('\n') +} + +function updateNpmLockfile(lock, latest) { + let metadata = { latest, versions: [] } + let content = deletePackage(JSON.parse(lock.content), metadata) + metadata.content = JSON.stringify(content, null, detectIndent(lock.content)) + return metadata +} + +function deletePackage(node, metadata) { + if (node.dependencies) { + if (node.dependencies['caniuse-lite']) { + let version = node.dependencies['caniuse-lite'].version + metadata.versions[version] = true + delete node.dependencies['caniuse-lite'] + } + for (let i in node.dependencies) { + node.dependencies[i] = deletePackage(node.dependencies[i], metadata) + } + } + if (node.packages) { + for (let path in node.packages) { + if (path.endsWith('/caniuse-lite')) { + metadata.versions[node.packages[path].version] = true + delete node.packages[path] + } + } + } + return node +} + +let yarnVersionRe = /version "(.*?)"/ + +function updateYarnLockfile(lock, latest) { + let blocks = lock.content.split(/(\n{2,})/).map(block => { + return block.split('\n') + }) + let versions = {} + blocks.forEach(lines => { + if (lines[0].indexOf('caniuse-lite@') !== -1) { + let match = yarnVersionRe.exec(lines[1]) + versions[match[1]] = true + if (match[1] !== latest.version) { + lines[1] = lines[1].replace( + /version "[^"]+"/, + 'version "' + latest.version + '"' + ) + lines[2] = lines[2].replace( + /resolved "[^"]+"/, + 'resolved "' + latest.dist.tarball + '"' + ) + if (lines.length === 4) { + lines[3] = latest.dist.integrity + ? lines[3].replace( + /integrity .+/, + 'integrity ' + latest.dist.integrity + ) + : '' + } + } + } + }) + let content = blocks.map(lines => lines.join('\n')).join('') + return { content, versions } +} + +function updateLockfile(lock, latest) { + if (!lock.content) lock.content = readFileSync(lock.file).toString() + + let updatedLockFile + if (lock.mode === 'yarn') { + updatedLockFile = updateYarnLockfile(lock, latest) + } else { + updatedLockFile = updateNpmLockfile(lock, latest) + } + updatedLockFile.content = updatedLockFile.content.replace( + /\n/g, + detectEOL(lock.content) + ) + return updatedLockFile +} + +function updatePackageManually(print, lock, latest) { + let lockfileData = updateLockfile(lock, latest) + let caniuseVersions = Object.keys(lockfileData.versions).sort() + if (caniuseVersions.length === 1 && caniuseVersions[0] === latest.version) { + print( + 'Installed version: ' + + pico.bold(pico.green(caniuseVersions[0])) + + '\n' + + pico.bold(pico.green('caniuse-lite is up to date')) + + '\n' + ) + return + } + + if (caniuseVersions.length === 0) { + caniuseVersions[0] = 'none' + } + print( + 'Installed version' + + (caniuseVersions.length === 1 ? ': ' : 's: ') + + pico.bold(pico.red(caniuseVersions.join(', '))) + + '\n' + + 'Removing old caniuse-lite from lock file\n' + ) + writeFileSync(lock.file, lockfileData.content) + + let install = + lock.mode === 'yarn' ? yarnCommand + ' add -W' : lock.mode + ' install' + print( + 'Installing new caniuse-lite version\n' + + pico.yellow('$ ' + install + ' caniuse-lite') + + '\n' + ) + try { + execSync(install + ' caniuse-lite') + } catch (e) /* c8 ignore start */ { + print( + pico.red( + '\n' + + e.stack + + '\n\n' + + 'Problem with `' + + install + + ' caniuse-lite` call. ' + + 'Run it manually.\n' + ) + ) + process.exit(1) + } /* c8 ignore end */ + + let del = + lock.mode === 'yarn' ? yarnCommand + ' remove -W' : lock.mode + ' uninstall' + print( + 'Cleaning package.json dependencies from caniuse-lite\n' + + pico.yellow('$ ' + del + ' caniuse-lite') + + '\n' + ) + execSync(del + ' caniuse-lite') +} + +function updateWith(print, cmd) { + print('Updating caniuse-lite version\n' + pico.yellow('$ ' + cmd) + '\n') + try { + execSync(cmd) + } catch (e) /* c8 ignore start */ { + print(pico.red(e.stdout.toString())) + print( + pico.red( + '\n' + + e.stack + + '\n\n' + + 'Problem with `' + + cmd + + '` call. ' + + 'Run it manually.\n' + ) + ) + process.exit(1) + } /* c8 ignore end */ +} + +module.exports = function updateDB(print = defaultPrint) { + let lock = detectLockfile() + let latest = getLatestInfo(lock) + + let listError + let oldList + try { + oldList = getBrowsers() + } catch (e) { + listError = e + } + + print('Latest version: ' + pico.bold(pico.green(latest.version)) + '\n') + + if (lock.mode === 'yarn' && lock.version !== 1) { + updateWith(print, yarnCommand + ' up -R caniuse-lite') + } else if (lock.mode === 'pnpm') { + updateWith(print, 'pnpm up caniuse-lite') + } else if (lock.mode === 'bun') { + updateWith(print, 'bun update caniuse-lite') + } else { + updatePackageManually(print, lock, latest) + } + + print('caniuse-lite has been successfully updated\n') + + let newList + if (!listError) { + try { + newList = getBrowsers() + } catch (e) /* c8 ignore start */ { + listError = e + } /* c8 ignore end */ + } + + if (listError) { + if (listError.message.includes("Cannot find module 'browserslist'")) { + print( + pico.gray( + 'Install `browserslist` to your direct dependencies ' + + 'to see target browser changes\n' + ) + ) + } else { + print( + pico.red( + '\n' + + listError.stack + + '\n\n' + + 'Problem with browser list retrieval.\n' + + 'Target browser changes won’t be shown.\n' + ) + ) + } + } else { + let changes = diffBrowsers(oldList, newList) + if (changes) { + print('\nTarget browser changes:\n') + print(changes + '\n') + } else { + print('\n' + pico.green('No target browser changes') + '\n') + } + } +} diff --git a/node_modules/update-browserslist-db/package.json b/node_modules/update-browserslist-db/package.json new file mode 100644 index 0000000..6a577f7 --- /dev/null +++ b/node_modules/update-browserslist-db/package.json @@ -0,0 +1,40 @@ +{ + "name": "update-browserslist-db", + "version": "1.1.0", + "description": "CLI tool to update caniuse-lite to refresh target browsers from Browserslist config", + "keywords": [ + "caniuse", + "browsers", + "target" + ], + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "author": "Andrey Sitnik ", + "license": "MIT", + "repository": "browserslist/update-db", + "types": "./index.d.ts", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "dependencies": { + "escalade": "^3.1.2", + "picocolors": "^1.0.1" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + }, + "bin": "cli.js" +} diff --git a/node_modules/update-browserslist-db/utils.js b/node_modules/update-browserslist-db/utils.js new file mode 100644 index 0000000..c63b278 --- /dev/null +++ b/node_modules/update-browserslist-db/utils.js @@ -0,0 +1,25 @@ +const { EOL } = require('os') + +const getFirstRegexpMatchOrDefault = (text, regexp, defaultValue) => { + regexp.lastIndex = 0 // https://stackoverflow.com/a/11477448/4536543 + let match = regexp.exec(text) + if (match !== null) { + return match[1] + } else { + return defaultValue + } +} + +const DEFAULT_INDENT = ' ' +const INDENT_REGEXP = /^([ \t]+)[^\s]/m + +module.exports.detectIndent = text => + getFirstRegexpMatchOrDefault(text, INDENT_REGEXP, DEFAULT_INDENT) +module.exports.DEFAULT_INDENT = DEFAULT_INDENT + +const DEFAULT_EOL = EOL +const EOL_REGEXP = /(\r\n|\n|\r)/g + +module.exports.detectEOL = text => + getFirstRegexpMatchOrDefault(text, EOL_REGEXP, DEFAULT_EOL) +module.exports.DEFAULT_EOL = DEFAULT_EOL diff --git a/node_modules/uri-js/LICENSE b/node_modules/uri-js/LICENSE new file mode 100755 index 0000000..9338bde --- /dev/null +++ b/node_modules/uri-js/LICENSE @@ -0,0 +1,11 @@ +Copyright 2011 Gary Court. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY GARY COURT "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Gary Court. diff --git a/node_modules/uri-js/README.md b/node_modules/uri-js/README.md new file mode 100755 index 0000000..43e648b --- /dev/null +++ b/node_modules/uri-js/README.md @@ -0,0 +1,203 @@ +# URI.js + +URI.js is an [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt) compliant, scheme extendable URI parsing/validating/resolving library for all JavaScript environments (browsers, Node.js, etc). +It is also compliant with the IRI ([RFC 3987](http://www.ietf.org/rfc/rfc3987.txt)), IDNA ([RFC 5890](http://www.ietf.org/rfc/rfc5890.txt)), IPv6 Address ([RFC 5952](http://www.ietf.org/rfc/rfc5952.txt)), IPv6 Zone Identifier ([RFC 6874](http://www.ietf.org/rfc/rfc6874.txt)) specifications. + +URI.js has an extensive test suite, and works in all (Node.js, web) environments. It weighs in at 6.4kb (gzipped, 17kb deflated). + +## API + +### Parsing + + URI.parse("uri://user:pass@example.com:123/one/two.three?q1=a1&q2=a2#body"); + //returns: + //{ + // scheme : "uri", + // userinfo : "user:pass", + // host : "example.com", + // port : 123, + // path : "/one/two.three", + // query : "q1=a1&q2=a2", + // fragment : "body" + //} + +### Serializing + + URI.serialize({scheme : "http", host : "example.com", fragment : "footer"}) === "http://example.com/#footer" + +### Resolving + + URI.resolve("uri://a/b/c/d?q", "../../g") === "uri://a/g" + +### Normalizing + + URI.normalize("HTTP://ABC.com:80/%7Esmith/home.html") === "http://abc.com/~smith/home.html" + +### Comparison + + URI.equal("example://a/b/c/%7Bfoo%7D", "eXAMPLE://a/./b/../b/%63/%7bfoo%7d") === true + +### IP Support + + //IPv4 normalization + URI.normalize("//192.068.001.000") === "//192.68.1.0" + + //IPv6 normalization + URI.normalize("//[2001:0:0DB8::0:0001]") === "//[2001:0:db8::1]" + + //IPv6 zone identifier support + URI.parse("//[2001:db8::7%25en1]"); + //returns: + //{ + // host : "2001:db8::7%en1" + //} + +### IRI Support + + //convert IRI to URI + URI.serialize(URI.parse("http://examplé.org/rosé")) === "http://xn--exampl-gva.org/ros%C3%A9" + //convert URI to IRI + URI.serialize(URI.parse("http://xn--exampl-gva.org/ros%C3%A9"), {iri:true}) === "http://examplé.org/rosé" + +### Options + +All of the above functions can accept an additional options argument that is an object that can contain one or more of the following properties: + +* `scheme` (string) + + Indicates the scheme that the URI should be treated as, overriding the URI's normal scheme parsing behavior. + +* `reference` (string) + + If set to `"suffix"`, it indicates that the URI is in the suffix format, and the validator will use the option's `scheme` property to determine the URI's scheme. + +* `tolerant` (boolean, false) + + If set to `true`, the parser will relax URI resolving rules. + +* `absolutePath` (boolean, false) + + If set to `true`, the serializer will not resolve a relative `path` component. + +* `iri` (boolean, false) + + If set to `true`, the serializer will unescape non-ASCII characters as per [RFC 3987](http://www.ietf.org/rfc/rfc3987.txt). + +* `unicodeSupport` (boolean, false) + + If set to `true`, the parser will unescape non-ASCII characters in the parsed output as per [RFC 3987](http://www.ietf.org/rfc/rfc3987.txt). + +* `domainHost` (boolean, false) + + If set to `true`, the library will treat the `host` component as a domain name, and convert IDNs (International Domain Names) as per [RFC 5891](http://www.ietf.org/rfc/rfc5891.txt). + +## Scheme Extendable + +URI.js supports inserting custom [scheme](http://en.wikipedia.org/wiki/URI_scheme) dependent processing rules. Currently, URI.js has built in support for the following schemes: + +* http \[[RFC 2616](http://www.ietf.org/rfc/rfc2616.txt)\] +* https \[[RFC 2818](http://www.ietf.org/rfc/rfc2818.txt)\] +* ws \[[RFC 6455](http://www.ietf.org/rfc/rfc6455.txt)\] +* wss \[[RFC 6455](http://www.ietf.org/rfc/rfc6455.txt)\] +* mailto \[[RFC 6068](http://www.ietf.org/rfc/rfc6068.txt)\] +* urn \[[RFC 2141](http://www.ietf.org/rfc/rfc2141.txt)\] +* urn:uuid \[[RFC 4122](http://www.ietf.org/rfc/rfc4122.txt)\] + +### HTTP/HTTPS Support + + URI.equal("HTTP://ABC.COM:80", "http://abc.com/") === true + URI.equal("https://abc.com", "HTTPS://ABC.COM:443/") === true + +### WS/WSS Support + + URI.parse("wss://example.com/foo?bar=baz"); + //returns: + //{ + // scheme : "wss", + // host: "example.com", + // resourceName: "/foo?bar=baz", + // secure: true, + //} + + URI.equal("WS://ABC.COM:80/chat#one", "ws://abc.com/chat") === true + +### Mailto Support + + URI.parse("mailto:alpha@example.com,bravo@example.com?subject=SUBSCRIBE&body=Sign%20me%20up!"); + //returns: + //{ + // scheme : "mailto", + // to : ["alpha@example.com", "bravo@example.com"], + // subject : "SUBSCRIBE", + // body : "Sign me up!" + //} + + URI.serialize({ + scheme : "mailto", + to : ["alpha@example.com"], + subject : "REMOVE", + body : "Please remove me", + headers : { + cc : "charlie@example.com" + } + }) === "mailto:alpha@example.com?cc=charlie@example.com&subject=REMOVE&body=Please%20remove%20me" + +### URN Support + + URI.parse("urn:example:foo"); + //returns: + //{ + // scheme : "urn", + // nid : "example", + // nss : "foo", + //} + +#### URN UUID Support + + URI.parse("urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6"); + //returns: + //{ + // scheme : "urn", + // nid : "uuid", + // uuid : "f81d4fae-7dec-11d0-a765-00a0c91e6bf6", + //} + +## Usage + +To load in a browser, use the following tag: + + + +To load in a CommonJS/Module environment, first install with npm/yarn by running on the command line: + + npm install uri-js + # OR + yarn add uri-js + +Then, in your code, load it using: + + const URI = require("uri-js"); + +If you are writing your code in ES6+ (ESNEXT) or TypeScript, you would load it using: + + import * as URI from "uri-js"; + +Or you can load just what you need using named exports: + + import { parse, serialize, resolve, resolveComponents, normalize, equal, removeDotSegments, pctEncChar, pctDecChars, escapeComponent, unescapeComponent } from "uri-js"; + +## Breaking changes + +### Breaking changes from 3.x + +URN parsing has been completely changed to better align with the specification. Scheme is now always `urn`, but has two new properties: `nid` which contains the Namspace Identifier, and `nss` which contains the Namespace Specific String. The `nss` property will be removed by higher order scheme handlers, such as the UUID URN scheme handler. + +The UUID of a URN can now be found in the `uuid` property. + +### Breaking changes from 2.x + +URI validation has been removed as it was slow, exposed a vulnerabilty, and was generally not useful. + +### Breaking changes from 1.x + +The `errors` array on parsed components is now an `error` string. diff --git a/node_modules/uri-js/dist/es5/uri.all.d.ts b/node_modules/uri-js/dist/es5/uri.all.d.ts new file mode 100755 index 0000000..da51e23 --- /dev/null +++ b/node_modules/uri-js/dist/es5/uri.all.d.ts @@ -0,0 +1,59 @@ +export interface URIComponents { + scheme?: string; + userinfo?: string; + host?: string; + port?: number | string; + path?: string; + query?: string; + fragment?: string; + reference?: string; + error?: string; +} +export interface URIOptions { + scheme?: string; + reference?: string; + tolerant?: boolean; + absolutePath?: boolean; + iri?: boolean; + unicodeSupport?: boolean; + domainHost?: boolean; +} +export interface URISchemeHandler { + scheme: string; + parse(components: ParentComponents, options: Options): Components; + serialize(components: Components, options: Options): ParentComponents; + unicodeSupport?: boolean; + domainHost?: boolean; + absolutePath?: boolean; +} +export interface URIRegExps { + NOT_SCHEME: RegExp; + NOT_USERINFO: RegExp; + NOT_HOST: RegExp; + NOT_PATH: RegExp; + NOT_PATH_NOSCHEME: RegExp; + NOT_QUERY: RegExp; + NOT_FRAGMENT: RegExp; + ESCAPE: RegExp; + UNRESERVED: RegExp; + OTHER_CHARS: RegExp; + PCT_ENCODED: RegExp; + IPV4ADDRESS: RegExp; + IPV6ADDRESS: RegExp; +} +export declare const SCHEMES: { + [scheme: string]: URISchemeHandler; +}; +export declare function pctEncChar(chr: string): string; +export declare function pctDecChars(str: string): string; +export declare function parse(uriString: string, options?: URIOptions): URIComponents; +export declare function removeDotSegments(input: string): string; +export declare function serialize(components: URIComponents, options?: URIOptions): string; +export declare function resolveComponents(base: URIComponents, relative: URIComponents, options?: URIOptions, skipNormalization?: boolean): URIComponents; +export declare function resolve(baseURI: string, relativeURI: string, options?: URIOptions): string; +export declare function normalize(uri: string, options?: URIOptions): string; +export declare function normalize(uri: URIComponents, options?: URIOptions): URIComponents; +export declare function equal(uriA: string, uriB: string, options?: URIOptions): boolean; +export declare function equal(uriA: URIComponents, uriB: URIComponents, options?: URIOptions): boolean; +export declare function escapeComponent(str: string, options?: URIOptions): string; +export declare function unescapeComponent(str: string, options?: URIOptions): string; diff --git a/node_modules/uri-js/dist/es5/uri.all.js b/node_modules/uri-js/dist/es5/uri.all.js new file mode 100755 index 0000000..0706116 --- /dev/null +++ b/node_modules/uri-js/dist/es5/uri.all.js @@ -0,0 +1,1443 @@ +/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.URI = global.URI || {}))); +}(this, (function (exports) { 'use strict'; + +function merge() { + for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) { + sets[_key] = arguments[_key]; + } + + if (sets.length > 1) { + sets[0] = sets[0].slice(0, -1); + var xl = sets.length - 1; + for (var x = 1; x < xl; ++x) { + sets[x] = sets[x].slice(1, -1); + } + sets[xl] = sets[xl].slice(1); + return sets.join(''); + } else { + return sets[0]; + } +} +function subexp(str) { + return "(?:" + str + ")"; +} +function typeOf(o) { + return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase(); +} +function toUpperCase(str) { + return str.toUpperCase(); +} +function toArray(obj) { + return obj !== undefined && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : []; +} +function assign(target, source) { + var obj = target; + if (source) { + for (var key in source) { + obj[key] = source[key]; + } + } + return obj; +} + +function buildExps(isIRI) { + var ALPHA$$ = "[A-Za-z]", + CR$ = "[\\x0D]", + DIGIT$$ = "[0-9]", + DQUOTE$$ = "[\\x22]", + HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"), + //case-insensitive + LF$$ = "[\\x0A]", + SP$$ = "[\\x20]", + PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)), + //expanded + GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", + SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", + RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), + UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", + //subset, excludes bidi control characters + IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", + //subset + UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$), + SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"), + USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"), + DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$), + DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), + //relaxed parsing rules + IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), + H16$ = subexp(HEXDIG$$ + "{1,4}"), + LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), + IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), + // 6( h16 ":" ) ls32 + IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), + // "::" 5( h16 ":" ) ls32 + IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), + //[ h16 ] "::" 4( h16 ":" ) ls32 + IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), + //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), + //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), + //[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), + //[ *4( h16 ":" ) h16 ] "::" ls32 + IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), + //[ *5( h16 ":" ) h16 ] "::" h16 + IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), + //[ *6( h16 ":" ) h16 ] "::" + IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), + ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"), + //RFC 6874 + IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$), + //RFC 6874 + IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$), + //RFC 6874, with relaxed parsing rules + IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"), + IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"), + //RFC 6874 + REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"), + HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")" + "|" + REG_NAME$), + PORT$ = subexp(DIGIT$$ + "*"), + AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"), + PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")), + SEGMENT$ = subexp(PCHAR$ + "*"), + SEGMENT_NZ$ = subexp(PCHAR$ + "+"), + SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"), + PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"), + PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"), + //simplified + PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), + //simplified + PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), + //simplified + PATH_EMPTY$ = "(?!" + PCHAR$ + ")", + PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), + QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"), + FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"), + HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), + URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), + RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$), + RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), + URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$), + ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"), + GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$", + SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$"; + return { + NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"), + NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"), + NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"), + ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"), + UNRESERVED: new RegExp(UNRESERVED$$, "g"), + OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"), + PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"), + IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"), + IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules + }; +} +var URI_PROTOCOL = buildExps(false); + +var IRI_PROTOCOL = buildExps(true); + +var slicedToArray = function () { + function sliceIterator(arr, i) { + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"]) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; + } + + return function (arr, i) { + if (Array.isArray(arr)) { + return arr; + } else if (Symbol.iterator in Object(arr)) { + return sliceIterator(arr, i); + } else { + throw new TypeError("Invalid attempt to destructure non-iterable instance"); + } + }; +}(); + + + + + + + + + + + + + +var toConsumableArray = function (arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } else { + return Array.from(arr); + } +}; + +/** Highest positive signed 32-bit float value */ + +var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +var base = 36; +var tMin = 1; +var tMax = 26; +var skew = 38; +var damp = 700; +var initialBias = 72; +var initialN = 128; // 0x80 +var delimiter = '-'; // '\x2D' + +/** Regular expressions */ +var regexPunycode = /^xn--/; +var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars +var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +var errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +var baseMinusTMin = base - tMin; +var floor = Math.floor; +var stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error$1(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, fn) { + var result = []; + var length = array.length; + while (length--) { + result[length] = fn(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ +function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + var output = []; + var counter = 0; + var length = string.length; + while (counter < length) { + var value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + var extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { + // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +var ucs2encode = function ucs2encode(array) { + return String.fromCodePoint.apply(String, toConsumableArray(array)); +}; + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +var basicToDigit = function basicToDigit(codePoint) { + if (codePoint - 0x30 < 0x0A) { + return codePoint - 0x16; + } + if (codePoint - 0x41 < 0x1A) { + return codePoint - 0x41; + } + if (codePoint - 0x61 < 0x1A) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +var digitToBasic = function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +var adapt = function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +var decode = function decode(input) { + // Don't use UCS-2. + var output = []; + var inputLength = input.length; + var i = 0; + var n = initialN; + var bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + var basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (var j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error$1('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{ + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + var oldi = i; + for (var w = 1, k = base;; /* no condition */k += base) { + + if (index >= inputLength) { + error$1('invalid-input'); + } + + var digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error$1('overflow'); + } + + i += digit * w; + var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + + if (digit < t) { + break; + } + + var baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error$1('overflow'); + } + + w *= baseMinusT; + } + + var out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error$1('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + } + + return String.fromCodePoint.apply(String, output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +var encode = function encode(input) { + var output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + var inputLength = input.length; + + // Initialize the state. + var n = initialN; + var delta = 0; + var bias = initialBias; + + // Handle the basic code points. + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _currentValue2 = _step.value; + + if (_currentValue2 < 0x80) { + output.push(stringFromCharCode(_currentValue2)); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var basicLength = output.length; + var handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + var m = maxInt; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var currentValue = _step2.value; + + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + var handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error$1('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _currentValue = _step3.value; + + if (_currentValue < n && ++delta > maxInt) { + error$1('overflow'); + } + if (_currentValue == n) { + // Represent delta as a generalized variable-length integer. + var q = delta; + for (var k = base;; /* no condition */k += base) { + var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (q < t) { + break; + } + var qMinusT = q - t; + var baseMinusT = base - t; + output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + ++delta; + ++n; + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +var toUnicode = function toUnicode(input) { + return mapDomain(input, function (string) { + return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +var toASCII = function toASCII(input) { + return mapDomain(input, function (string) { + return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +var punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.1.0', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +/** + * URI.js + * + * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript. + * @author Gary Court + * @see http://github.com/garycourt/uri-js + */ +/** + * Copyright 2011 Gary Court. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of Gary Court. + */ +var SCHEMES = {}; +function pctEncChar(chr) { + var c = chr.charCodeAt(0); + var e = void 0; + if (c < 16) e = "%0" + c.toString(16).toUpperCase();else if (c < 128) e = "%" + c.toString(16).toUpperCase();else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase(); + return e; +} +function pctDecChars(str) { + var newStr = ""; + var i = 0; + var il = str.length; + while (i < il) { + var c = parseInt(str.substr(i + 1, 2), 16); + if (c < 128) { + newStr += String.fromCharCode(c); + i += 3; + } else if (c >= 194 && c < 224) { + if (il - i >= 6) { + var c2 = parseInt(str.substr(i + 4, 2), 16); + newStr += String.fromCharCode((c & 31) << 6 | c2 & 63); + } else { + newStr += str.substr(i, 6); + } + i += 6; + } else if (c >= 224) { + if (il - i >= 9) { + var _c = parseInt(str.substr(i + 4, 2), 16); + var c3 = parseInt(str.substr(i + 7, 2), 16); + newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63); + } else { + newStr += str.substr(i, 9); + } + i += 9; + } else { + newStr += str.substr(i, 3); + i += 3; + } + } + return newStr; +} +function _normalizeComponentEncoding(components, protocol) { + function decodeUnreserved(str) { + var decStr = pctDecChars(str); + return !decStr.match(protocol.UNRESERVED) ? str : decStr; + } + if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, ""); + if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + return components; +} + +function _stripLeadingZeros(str) { + return str.replace(/^0*(.*)/, "$1") || "0"; +} +function _normalizeIPv4(host, protocol) { + var matches = host.match(protocol.IPV4ADDRESS) || []; + + var _matches = slicedToArray(matches, 2), + address = _matches[1]; + + if (address) { + return address.split(".").map(_stripLeadingZeros).join("."); + } else { + return host; + } +} +function _normalizeIPv6(host, protocol) { + var matches = host.match(protocol.IPV6ADDRESS) || []; + + var _matches2 = slicedToArray(matches, 3), + address = _matches2[1], + zone = _matches2[2]; + + if (address) { + var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(), + _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), + last = _address$toLowerCase$2[0], + first = _address$toLowerCase$2[1]; + + var firstFields = first ? first.split(":").map(_stripLeadingZeros) : []; + var lastFields = last.split(":").map(_stripLeadingZeros); + var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]); + var fieldCount = isLastFieldIPv4Address ? 7 : 8; + var lastFieldsStart = lastFields.length - fieldCount; + var fields = Array(fieldCount); + for (var x = 0; x < fieldCount; ++x) { + fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || ''; + } + if (isLastFieldIPv4Address) { + fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol); + } + var allZeroFields = fields.reduce(function (acc, field, index) { + if (!field || field === "0") { + var lastLongest = acc[acc.length - 1]; + if (lastLongest && lastLongest.index + lastLongest.length === index) { + lastLongest.length++; + } else { + acc.push({ index: index, length: 1 }); + } + } + return acc; + }, []); + var longestZeroFields = allZeroFields.sort(function (a, b) { + return b.length - a.length; + })[0]; + var newHost = void 0; + if (longestZeroFields && longestZeroFields.length > 1) { + var newFirst = fields.slice(0, longestZeroFields.index); + var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length); + newHost = newFirst.join(":") + "::" + newLast.join(":"); + } else { + newHost = fields.join(":"); + } + if (zone) { + newHost += "%" + zone; + } + return newHost; + } else { + return host; + } +} +var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i; +var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined; +function parse(uriString) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var components = {}; + var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; + if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString; + var matches = uriString.match(URI_PARSE); + if (matches) { + if (NO_MATCH_IS_UNDEFINED) { + //store each component + components.scheme = matches[1]; + components.userinfo = matches[3]; + components.host = matches[4]; + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = matches[7]; + components.fragment = matches[8]; + //fix port number + if (isNaN(components.port)) { + components.port = matches[5]; + } + } else { + //IE FIX for improper RegExp matching + //store each component + components.scheme = matches[1] || undefined; + components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined; + components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined; + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined; + components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined; + //fix port number + if (isNaN(components.port)) { + components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined; + } + } + if (components.host) { + //normalize IP hosts + components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol); + } + //determine reference type + if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) { + components.reference = "same-document"; + } else if (components.scheme === undefined) { + components.reference = "relative"; + } else if (components.fragment === undefined) { + components.reference = "absolute"; + } else { + components.reference = "uri"; + } + //check for reference errors + if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) { + components.error = components.error || "URI is not a " + options.reference + " reference."; + } + //find scheme handler + var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //check if scheme can't handle IRIs + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + //if host component is a domain name + if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) { + //convert Unicode IDN -> ASCII IDN + try { + components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()); + } catch (e) { + components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e; + } + } + //convert IRI -> URI + _normalizeComponentEncoding(components, URI_PROTOCOL); + } else { + //normalize encodings + _normalizeComponentEncoding(components, protocol); + } + //perform scheme specific parsing + if (schemeHandler && schemeHandler.parse) { + schemeHandler.parse(components, options); + } + } else { + components.error = components.error || "URI can not be parsed."; + } + return components; +} + +function _recomposeAuthority(components, options) { + var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; + var uriTokens = []; + if (components.userinfo !== undefined) { + uriTokens.push(components.userinfo); + uriTokens.push("@"); + } + if (components.host !== undefined) { + //normalize IP hosts, add brackets and escape zone separator for IPv6 + uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) { + return "[" + $1 + ($2 ? "%25" + $2 : "") + "]"; + })); + } + if (typeof components.port === "number" || typeof components.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(components.port)); + } + return uriTokens.length ? uriTokens.join("") : undefined; +} + +var RDS1 = /^\.\.?\//; +var RDS2 = /^\/\.(\/|$)/; +var RDS3 = /^\/\.\.(\/|$)/; +var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/; +function removeDotSegments(input) { + var output = []; + while (input.length) { + if (input.match(RDS1)) { + input = input.replace(RDS1, ""); + } else if (input.match(RDS2)) { + input = input.replace(RDS2, "/"); + } else if (input.match(RDS3)) { + input = input.replace(RDS3, "/"); + output.pop(); + } else if (input === "." || input === "..") { + input = ""; + } else { + var im = input.match(RDS5); + if (im) { + var s = im[0]; + input = input.slice(s.length); + output.push(s); + } else { + throw new Error("Unexpected dot segment condition"); + } + } + } + return output.join(""); +} + +function serialize(components) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL; + var uriTokens = []; + //find scheme handler + var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //perform scheme specific serialization + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options); + if (components.host) { + //if host component is an IPv6 address + if (protocol.IPV6ADDRESS.test(components.host)) {} + //TODO: normalize IPv6 address as per RFC 5952 + + //if host component is a domain name + else if (options.domainHost || schemeHandler && schemeHandler.domainHost) { + //convert IDN via punycode + try { + components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host); + } catch (e) { + components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + } + } + //normalize encoding + _normalizeComponentEncoding(components, protocol); + if (options.reference !== "suffix" && components.scheme) { + uriTokens.push(components.scheme); + uriTokens.push(":"); + } + var authority = _recomposeAuthority(components, options); + if (authority !== undefined) { + if (options.reference !== "suffix") { + uriTokens.push("//"); + } + uriTokens.push(authority); + if (components.path && components.path.charAt(0) !== "/") { + uriTokens.push("/"); + } + } + if (components.path !== undefined) { + var s = components.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { + s = removeDotSegments(s); + } + if (authority === undefined) { + s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//" + } + uriTokens.push(s); + } + if (components.query !== undefined) { + uriTokens.push("?"); + uriTokens.push(components.query); + } + if (components.fragment !== undefined) { + uriTokens.push("#"); + uriTokens.push(components.fragment); + } + return uriTokens.join(""); //merge tokens into a string +} + +function resolveComponents(base, relative) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var skipNormalization = arguments[3]; + + var target = {}; + if (!skipNormalization) { + base = parse(serialize(base, options), options); //normalize base components + relative = parse(serialize(relative, options), options); //normalize relative components + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== undefined) { + target.query = relative.query; + } else { + target.query = base.query; + } + } else { + if (relative.path.charAt(0) === "/") { + target.path = removeDotSegments(relative.path); + } else { + if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) { + target.path = "/" + relative.path; + } else if (!base.path) { + target.path = relative.path; + } else { + target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + } + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + //target.authority = base.authority; + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; +} + +function resolve(baseURI, relativeURI, options) { + var schemelessOptions = assign({ scheme: 'null' }, options); + return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions); +} + +function normalize(uri, options) { + if (typeof uri === "string") { + uri = serialize(parse(uri, options), options); + } else if (typeOf(uri) === "object") { + uri = parse(serialize(uri, options), options); + } + return uri; +} + +function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = serialize(parse(uriA, options), options); + } else if (typeOf(uriA) === "object") { + uriA = serialize(uriA, options); + } + if (typeof uriB === "string") { + uriB = serialize(parse(uriB, options), options); + } else if (typeOf(uriB) === "object") { + uriB = serialize(uriB, options); + } + return uriA === uriB; +} + +function escapeComponent(str, options) { + return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar); +} + +function unescapeComponent(str, options) { + return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars); +} + +var handler = { + scheme: "http", + domainHost: true, + parse: function parse(components, options) { + //report missing host + if (!components.host) { + components.error = components.error || "HTTP URIs must have a host."; + } + return components; + }, + serialize: function serialize(components, options) { + var secure = String(components.scheme).toLowerCase() === "https"; + //normalize the default port + if (components.port === (secure ? 443 : 80) || components.port === "") { + components.port = undefined; + } + //normalize the empty path + if (!components.path) { + components.path = "/"; + } + //NOTE: We do not parse query strings for HTTP URIs + //as WWW Form Url Encoded query strings are part of the HTML4+ spec, + //and not the HTTP spec. + return components; + } +}; + +var handler$1 = { + scheme: "https", + domainHost: handler.domainHost, + parse: handler.parse, + serialize: handler.serialize +}; + +function isSecure(wsComponents) { + return typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss"; +} +//RFC 6455 +var handler$2 = { + scheme: "ws", + domainHost: true, + parse: function parse(components, options) { + var wsComponents = components; + //indicate if the secure flag is set + wsComponents.secure = isSecure(wsComponents); + //construct resouce name + wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : ''); + wsComponents.path = undefined; + wsComponents.query = undefined; + return wsComponents; + }, + serialize: function serialize(wsComponents, options) { + //normalize the default port + if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") { + wsComponents.port = undefined; + } + //ensure scheme matches secure flag + if (typeof wsComponents.secure === 'boolean') { + wsComponents.scheme = wsComponents.secure ? 'wss' : 'ws'; + wsComponents.secure = undefined; + } + //reconstruct path from resource name + if (wsComponents.resourceName) { + var _wsComponents$resourc = wsComponents.resourceName.split('?'), + _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), + path = _wsComponents$resourc2[0], + query = _wsComponents$resourc2[1]; + + wsComponents.path = path && path !== '/' ? path : undefined; + wsComponents.query = query; + wsComponents.resourceName = undefined; + } + //forbid fragment component + wsComponents.fragment = undefined; + return wsComponents; + } +}; + +var handler$3 = { + scheme: "wss", + domainHost: handler$2.domainHost, + parse: handler$2.parse, + serialize: handler$2.serialize +}; + +var O = {}; +var isIRI = true; +//RFC 3986 +var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]"; +var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive +var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded +//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; = +//const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]"; +//const WSP$$ = "[\\x20\\x09]"; +//const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127) +//const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext +//const VCHAR$$ = "[\\x21-\\x7E]"; +//const WSP$$ = "[\\x20\\x09]"; +//const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext +//const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+"); +//const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$); +//const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"'); +var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]"; +var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]"; +var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]"); +var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"; +var UNRESERVED = new RegExp(UNRESERVED$$, "g"); +var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g"); +var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g"); +var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g"); +var NOT_HFVALUE = NOT_HFNAME; +function decodeUnreserved(str) { + var decStr = pctDecChars(str); + return !decStr.match(UNRESERVED) ? str : decStr; +} +var handler$4 = { + scheme: "mailto", + parse: function parse$$1(components, options) { + var mailtoComponents = components; + var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : []; + mailtoComponents.path = undefined; + if (mailtoComponents.query) { + var unknownHeaders = false; + var headers = {}; + var hfields = mailtoComponents.query.split("&"); + for (var x = 0, xl = hfields.length; x < xl; ++x) { + var hfield = hfields[x].split("="); + switch (hfield[0]) { + case "to": + var toAddrs = hfield[1].split(","); + for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) { + to.push(toAddrs[_x]); + } + break; + case "subject": + mailtoComponents.subject = unescapeComponent(hfield[1], options); + break; + case "body": + mailtoComponents.body = unescapeComponent(hfield[1], options); + break; + default: + unknownHeaders = true; + headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options); + break; + } + } + if (unknownHeaders) mailtoComponents.headers = headers; + } + mailtoComponents.query = undefined; + for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) { + var addr = to[_x2].split("@"); + addr[0] = unescapeComponent(addr[0]); + if (!options.unicodeSupport) { + //convert Unicode IDN -> ASCII IDN + try { + addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase()); + } catch (e) { + mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e; + } + } else { + addr[1] = unescapeComponent(addr[1], options).toLowerCase(); + } + to[_x2] = addr.join("@"); + } + return mailtoComponents; + }, + serialize: function serialize$$1(mailtoComponents, options) { + var components = mailtoComponents; + var to = toArray(mailtoComponents.to); + if (to) { + for (var x = 0, xl = to.length; x < xl; ++x) { + var toAddr = String(to[x]); + var atIdx = toAddr.lastIndexOf("@"); + var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar); + var domain = toAddr.slice(atIdx + 1); + //convert IDN via punycode + try { + domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain); + } catch (e) { + components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + to[x] = localPart + "@" + domain; + } + components.path = to.join(","); + } + var headers = mailtoComponents.headers = mailtoComponents.headers || {}; + if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject; + if (mailtoComponents.body) headers["body"] = mailtoComponents.body; + var fields = []; + for (var name in headers) { + if (headers[name] !== O[name]) { + fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)); + } + } + if (fields.length) { + components.query = fields.join("&"); + } + return components; + } +}; + +var URN_PARSE = /^([^\:]+)\:(.*)/; +//RFC 2141 +var handler$5 = { + scheme: "urn", + parse: function parse$$1(components, options) { + var matches = components.path && components.path.match(URN_PARSE); + var urnComponents = components; + if (matches) { + var scheme = options.scheme || urnComponents.scheme || "urn"; + var nid = matches[1].toLowerCase(); + var nss = matches[2]; + var urnScheme = scheme + ":" + (options.nid || nid); + var schemeHandler = SCHEMES[urnScheme]; + urnComponents.nid = nid; + urnComponents.nss = nss; + urnComponents.path = undefined; + if (schemeHandler) { + urnComponents = schemeHandler.parse(urnComponents, options); + } + } else { + urnComponents.error = urnComponents.error || "URN can not be parsed."; + } + return urnComponents; + }, + serialize: function serialize$$1(urnComponents, options) { + var scheme = options.scheme || urnComponents.scheme || "urn"; + var nid = urnComponents.nid; + var urnScheme = scheme + ":" + (options.nid || nid); + var schemeHandler = SCHEMES[urnScheme]; + if (schemeHandler) { + urnComponents = schemeHandler.serialize(urnComponents, options); + } + var uriComponents = urnComponents; + var nss = urnComponents.nss; + uriComponents.path = (nid || options.nid) + ":" + nss; + return uriComponents; + } +}; + +var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/; +//RFC 4122 +var handler$6 = { + scheme: "urn:uuid", + parse: function parse(urnComponents, options) { + var uuidComponents = urnComponents; + uuidComponents.uuid = uuidComponents.nss; + uuidComponents.nss = undefined; + if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) { + uuidComponents.error = uuidComponents.error || "UUID is not valid."; + } + return uuidComponents; + }, + serialize: function serialize(uuidComponents, options) { + var urnComponents = uuidComponents; + //normalize UUID + urnComponents.nss = (uuidComponents.uuid || "").toLowerCase(); + return urnComponents; + } +}; + +SCHEMES[handler.scheme] = handler; +SCHEMES[handler$1.scheme] = handler$1; +SCHEMES[handler$2.scheme] = handler$2; +SCHEMES[handler$3.scheme] = handler$3; +SCHEMES[handler$4.scheme] = handler$4; +SCHEMES[handler$5.scheme] = handler$5; +SCHEMES[handler$6.scheme] = handler$6; + +exports.SCHEMES = SCHEMES; +exports.pctEncChar = pctEncChar; +exports.pctDecChars = pctDecChars; +exports.parse = parse; +exports.removeDotSegments = removeDotSegments; +exports.serialize = serialize; +exports.resolveComponents = resolveComponents; +exports.resolve = resolve; +exports.normalize = normalize; +exports.equal = equal; +exports.escapeComponent = escapeComponent; +exports.unescapeComponent = unescapeComponent; + +Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=uri.all.js.map diff --git a/node_modules/uri-js/dist/es5/uri.all.js.map b/node_modules/uri-js/dist/es5/uri.all.js.map new file mode 100755 index 0000000..5b30c4e --- /dev/null +++ b/node_modules/uri-js/dist/es5/uri.all.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uri.all.js","sources":["../../src/index.ts","../../src/schemes/urn-uuid.ts","../../src/schemes/urn.ts","../../src/schemes/mailto.ts","../../src/schemes/wss.ts","../../src/schemes/ws.ts","../../src/schemes/https.ts","../../src/schemes/http.ts","../../src/uri.ts","../../node_modules/punycode/punycode.es6.js","../../src/regexps-iri.ts","../../src/regexps-uri.ts","../../src/util.ts"],"sourcesContent":["import { SCHEMES } from \"./uri\";\n\nimport http from \"./schemes/http\";\nSCHEMES[http.scheme] = http;\n\nimport https from \"./schemes/https\";\nSCHEMES[https.scheme] = https;\n\nimport ws from \"./schemes/ws\";\nSCHEMES[ws.scheme] = ws;\n\nimport wss from \"./schemes/wss\";\nSCHEMES[wss.scheme] = wss;\n\nimport mailto from \"./schemes/mailto\";\nSCHEMES[mailto.scheme] = mailto;\n\nimport urn from \"./schemes/urn\";\nSCHEMES[urn.scheme] = urn;\n\nimport uuid from \"./schemes/urn-uuid\";\nSCHEMES[uuid.scheme] = uuid;\n\nexport * from \"./uri\";\n","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport { URNComponents } from \"./urn\";\nimport { SCHEMES } from \"../uri\";\n\nexport interface UUIDComponents extends URNComponents {\n\tuuid?: string;\n}\n\nconst UUID = /^[0-9A-Fa-f]{8}(?:\\-[0-9A-Fa-f]{4}){3}\\-[0-9A-Fa-f]{12}$/;\nconst UUID_PARSE = /^[0-9A-Fa-f\\-]{36}/;\n\n//RFC 4122\nconst handler:URISchemeHandler = {\n\tscheme : \"urn:uuid\",\n\n\tparse : function (urnComponents:URNComponents, options:URIOptions):UUIDComponents {\n\t\tconst uuidComponents = urnComponents as UUIDComponents;\n\t\tuuidComponents.uuid = uuidComponents.nss;\n\t\tuuidComponents.nss = undefined;\n\n\t\tif (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) {\n\t\t\tuuidComponents.error = uuidComponents.error || \"UUID is not valid.\";\n\t\t}\n\n\t\treturn uuidComponents;\n\t},\n\n\tserialize : function (uuidComponents:UUIDComponents, options:URIOptions):URNComponents {\n\t\tconst urnComponents = uuidComponents as URNComponents;\n\t\t//normalize UUID\n\t\turnComponents.nss = (uuidComponents.uuid || \"\").toLowerCase();\n\t\treturn urnComponents;\n\t},\n};\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport { pctEncChar, SCHEMES } from \"../uri\";\n\nexport interface URNComponents extends URIComponents {\n\tnid?:string;\n\tnss?:string;\n}\n\nexport interface URNOptions extends URIOptions {\n\tnid?:string;\n}\n\nconst NID$ = \"(?:[0-9A-Za-z][0-9A-Za-z\\\\-]{1,31})\";\nconst PCT_ENCODED$ = \"(?:\\\\%[0-9A-Fa-f]{2})\";\nconst TRANS$$ = \"[0-9A-Za-z\\\\(\\\\)\\\\+\\\\,\\\\-\\\\.\\\\:\\\\=\\\\@\\\\;\\\\$\\\\_\\\\!\\\\*\\\\'\\\\/\\\\?\\\\#]\";\nconst NSS$ = \"(?:(?:\" + PCT_ENCODED$ + \"|\" + TRANS$$ + \")+)\";\nconst URN_SCHEME = new RegExp(\"^urn\\\\:(\" + NID$ + \")$\");\nconst URN_PATH = new RegExp(\"^(\" + NID$ + \")\\\\:(\" + NSS$ + \")$\");\nconst URN_PARSE = /^([^\\:]+)\\:(.*)/;\nconst URN_EXCLUDED = /[\\x00-\\x20\\\\\\\"\\&\\<\\>\\[\\]\\^\\`\\{\\|\\}\\~\\x7F-\\xFF]/g;\n\n//RFC 2141\nconst handler:URISchemeHandler = {\n\tscheme : \"urn\",\n\n\tparse : function (components:URIComponents, options:URNOptions):URNComponents {\n\t\tconst matches = components.path && components.path.match(URN_PARSE);\n\t\tlet urnComponents = components as URNComponents;\n\n\t\tif (matches) {\n\t\t\tconst scheme = options.scheme || urnComponents.scheme || \"urn\";\n\t\t\tconst nid = matches[1].toLowerCase();\n\t\t\tconst nss = matches[2];\n\t\t\tconst urnScheme = `${scheme}:${options.nid || nid}`;\n\t\t\tconst schemeHandler = SCHEMES[urnScheme];\n\n\t\t\turnComponents.nid = nid;\n\t\t\turnComponents.nss = nss;\n\t\t\turnComponents.path = undefined;\n\n\t\t\tif (schemeHandler) {\n\t\t\t\turnComponents = schemeHandler.parse(urnComponents, options) as URNComponents;\n\t\t\t}\n\t\t} else {\n\t\t\turnComponents.error = urnComponents.error || \"URN can not be parsed.\";\n\t\t}\n\n\t\treturn urnComponents;\n\t},\n\n\tserialize : function (urnComponents:URNComponents, options:URNOptions):URIComponents {\n\t\tconst scheme = options.scheme || urnComponents.scheme || \"urn\";\n\t\tconst nid = urnComponents.nid;\n\t\tconst urnScheme = `${scheme}:${options.nid || nid}`;\n\t\tconst schemeHandler = SCHEMES[urnScheme];\n\n\t\tif (schemeHandler) {\n\t\t\turnComponents = schemeHandler.serialize(urnComponents, options) as URNComponents;\n\t\t}\n\n\t\tconst uriComponents = urnComponents as URIComponents;\n\t\tconst nss = urnComponents.nss;\n\t\turiComponents.path = `${nid || options.nid}:${nss}`;\n\n\t\treturn uriComponents;\n\t},\n};\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport { pctEncChar, pctDecChars, unescapeComponent } from \"../uri\";\nimport punycode from \"punycode\";\nimport { merge, subexp, toUpperCase, toArray } from \"../util\";\n\nexport interface MailtoHeaders {\n\t[hfname:string]:string\n}\n\nexport interface MailtoComponents extends URIComponents {\n\tto:Array,\n\theaders?:MailtoHeaders,\n\tsubject?:string,\n\tbody?:string\n}\n\nconst O:MailtoHeaders = {};\nconst isIRI = true;\n\n//RFC 3986\nconst UNRESERVED$$ = \"[A-Za-z0-9\\\\-\\\\.\\\\_\\\\~\" + (isIRI ? \"\\\\xA0-\\\\u200D\\\\u2010-\\\\u2029\\\\u202F-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF\" : \"\") + \"]\";\nconst HEXDIG$$ = \"[0-9A-Fa-f]\"; //case-insensitive\nconst PCT_ENCODED$ = subexp(subexp(\"%[EFef]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%[89A-Fa-f]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%\" + HEXDIG$$ + HEXDIG$$)); //expanded\n\n//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; =\n//const ATEXT$$ = \"[A-Za-z0-9\\\\!\\\\#\\\\$\\\\%\\\\&\\\\'\\\\*\\\\+\\\\-\\\\/\\\\=\\\\?\\\\^\\\\_\\\\`\\\\{\\\\|\\\\}\\\\~]\";\n//const WSP$$ = \"[\\\\x20\\\\x09]\";\n//const OBS_QTEXT$$ = \"[\\\\x01-\\\\x08\\\\x0B\\\\x0C\\\\x0E-\\\\x1F\\\\x7F]\"; //(%d1-8 / %d11-12 / %d14-31 / %d127)\n//const QTEXT$$ = merge(\"[\\\\x21\\\\x23-\\\\x5B\\\\x5D-\\\\x7E]\", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext\n//const VCHAR$$ = \"[\\\\x21-\\\\x7E]\";\n//const WSP$$ = \"[\\\\x20\\\\x09]\";\n//const OBS_QP$ = subexp(\"\\\\\\\\\" + merge(\"[\\\\x00\\\\x0D\\\\x0A]\", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext\n//const FWS$ = subexp(subexp(WSP$$ + \"*\" + \"\\\\x0D\\\\x0A\") + \"?\" + WSP$$ + \"+\");\n//const QUOTED_PAIR$ = subexp(subexp(\"\\\\\\\\\" + subexp(VCHAR$$ + \"|\" + WSP$$)) + \"|\" + OBS_QP$);\n//const QUOTED_STRING$ = subexp('\\\\\"' + subexp(FWS$ + \"?\" + QCONTENT$) + \"*\" + FWS$ + \"?\" + '\\\\\"');\nconst ATEXT$$ = \"[A-Za-z0-9\\\\!\\\\$\\\\%\\\\'\\\\*\\\\+\\\\-\\\\^\\\\_\\\\`\\\\{\\\\|\\\\}\\\\~]\";\nconst QTEXT$$ = \"[\\\\!\\\\$\\\\%\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,\\\\-\\\\.0-9\\\\<\\\\>A-Z\\\\x5E-\\\\x7E]\";\nconst VCHAR$$ = merge(QTEXT$$, \"[\\\\\\\"\\\\\\\\]\");\nconst DOT_ATOM_TEXT$ = subexp(ATEXT$$ + \"+\" + subexp(\"\\\\.\" + ATEXT$$ + \"+\") + \"*\");\nconst QUOTED_PAIR$ = subexp(\"\\\\\\\\\" + VCHAR$$);\nconst QCONTENT$ = subexp(QTEXT$$ + \"|\" + QUOTED_PAIR$);\nconst QUOTED_STRING$ = subexp('\\\\\"' + QCONTENT$ + \"*\" + '\\\\\"');\n\n//RFC 6068\nconst DTEXT_NO_OBS$$ = \"[\\\\x21-\\\\x5A\\\\x5E-\\\\x7E]\"; //%d33-90 / %d94-126\nconst SOME_DELIMS$$ = \"[\\\\!\\\\$\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,\\\\;\\\\:\\\\@]\";\nconst QCHAR$ = subexp(UNRESERVED$$ + \"|\" + PCT_ENCODED$ + \"|\" + SOME_DELIMS$$);\nconst DOMAIN$ = subexp(DOT_ATOM_TEXT$ + \"|\" + \"\\\\[\" + DTEXT_NO_OBS$$ + \"*\" + \"\\\\]\");\nconst LOCAL_PART$ = subexp(DOT_ATOM_TEXT$ + \"|\" + QUOTED_STRING$);\nconst ADDR_SPEC$ = subexp(LOCAL_PART$ + \"\\\\@\" + DOMAIN$);\nconst TO$ = subexp(ADDR_SPEC$ + subexp(\"\\\\,\" + ADDR_SPEC$) + \"*\");\nconst HFNAME$ = subexp(QCHAR$ + \"*\");\nconst HFVALUE$ = HFNAME$;\nconst HFIELD$ = subexp(HFNAME$ + \"\\\\=\" + HFVALUE$);\nconst HFIELDS2$ = subexp(HFIELD$ + subexp(\"\\\\&\" + HFIELD$) + \"*\");\nconst HFIELDS$ = subexp(\"\\\\?\" + HFIELDS2$);\nconst MAILTO_URI = new RegExp(\"^mailto\\\\:\" + TO$ + \"?\" + HFIELDS$ + \"?$\");\n\nconst UNRESERVED = new RegExp(UNRESERVED$$, \"g\");\nconst PCT_ENCODED = new RegExp(PCT_ENCODED$, \"g\");\nconst NOT_LOCAL_PART = new RegExp(merge(\"[^]\", ATEXT$$, \"[\\\\.]\", '[\\\\\"]', VCHAR$$), \"g\");\nconst NOT_DOMAIN = new RegExp(merge(\"[^]\", ATEXT$$, \"[\\\\.]\", \"[\\\\[]\", DTEXT_NO_OBS$$, \"[\\\\]]\"), \"g\");\nconst NOT_HFNAME = new RegExp(merge(\"[^]\", UNRESERVED$$, SOME_DELIMS$$), \"g\");\nconst NOT_HFVALUE = NOT_HFNAME;\nconst TO = new RegExp(\"^\" + TO$ + \"$\");\nconst HFIELDS = new RegExp(\"^\" + HFIELDS2$ + \"$\");\n\nfunction decodeUnreserved(str:string):string {\n\tconst decStr = pctDecChars(str);\n\treturn (!decStr.match(UNRESERVED) ? str : decStr);\n}\n\nconst handler:URISchemeHandler = {\n\tscheme : \"mailto\",\n\n\tparse : function (components:URIComponents, options:URIOptions):MailtoComponents {\n\t\tconst mailtoComponents = components as MailtoComponents;\n\t\tconst to = mailtoComponents.to = (mailtoComponents.path ? mailtoComponents.path.split(\",\") : []);\n\t\tmailtoComponents.path = undefined;\n\n\t\tif (mailtoComponents.query) {\n\t\t\tlet unknownHeaders = false\n\t\t\tconst headers:MailtoHeaders = {};\n\t\t\tconst hfields = mailtoComponents.query.split(\"&\");\n\n\t\t\tfor (let x = 0, xl = hfields.length; x < xl; ++x) {\n\t\t\t\tconst hfield = hfields[x].split(\"=\");\n\n\t\t\t\tswitch (hfield[0]) {\n\t\t\t\t\tcase \"to\":\n\t\t\t\t\t\tconst toAddrs = hfield[1].split(\",\");\n\t\t\t\t\t\tfor (let x = 0, xl = toAddrs.length; x < xl; ++x) {\n\t\t\t\t\t\t\tto.push(toAddrs[x]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"subject\":\n\t\t\t\t\t\tmailtoComponents.subject = unescapeComponent(hfield[1], options);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"body\":\n\t\t\t\t\t\tmailtoComponents.body = unescapeComponent(hfield[1], options);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tunknownHeaders = true;\n\t\t\t\t\t\theaders[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (unknownHeaders) mailtoComponents.headers = headers;\n\t\t}\n\n\t\tmailtoComponents.query = undefined;\n\n\t\tfor (let x = 0, xl = to.length; x < xl; ++x) {\n\t\t\tconst addr = to[x].split(\"@\");\n\n\t\t\taddr[0] = unescapeComponent(addr[0]);\n\n\t\t\tif (!options.unicodeSupport) {\n\t\t\t\t//convert Unicode IDN -> ASCII IDN\n\t\t\t\ttry {\n\t\t\t\t\taddr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase());\n\t\t\t\t} catch (e) {\n\t\t\t\t\tmailtoComponents.error = mailtoComponents.error || \"Email address's domain name can not be converted to ASCII via punycode: \" + e;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\taddr[1] = unescapeComponent(addr[1], options).toLowerCase();\n\t\t\t}\n\n\t\t\tto[x] = addr.join(\"@\");\n\t\t}\n\n\t\treturn mailtoComponents;\n\t},\n\n\tserialize : function (mailtoComponents:MailtoComponents, options:URIOptions):URIComponents {\n\t\tconst components = mailtoComponents as URIComponents;\n\t\tconst to = toArray(mailtoComponents.to);\n\t\tif (to) {\n\t\t\tfor (let x = 0, xl = to.length; x < xl; ++x) {\n\t\t\t\tconst toAddr = String(to[x]);\n\t\t\t\tconst atIdx = toAddr.lastIndexOf(\"@\");\n\t\t\t\tconst localPart = (toAddr.slice(0, atIdx)).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar);\n\t\t\t\tlet domain = toAddr.slice(atIdx + 1);\n\n\t\t\t\t//convert IDN via punycode\n\t\t\t\ttry {\n\t\t\t\t\tdomain = (!options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain));\n\t\t\t\t} catch (e) {\n\t\t\t\t\tcomponents.error = components.error || \"Email address's domain name can not be converted to \" + (!options.iri ? \"ASCII\" : \"Unicode\") + \" via punycode: \" + e;\n\t\t\t\t}\n\n\t\t\t\tto[x] = localPart + \"@\" + domain;\n\t\t\t}\n\n\t\t\tcomponents.path = to.join(\",\");\n\t\t}\n\n\t\tconst headers = mailtoComponents.headers = mailtoComponents.headers || {};\n\n\t\tif (mailtoComponents.subject) headers[\"subject\"] = mailtoComponents.subject;\n\t\tif (mailtoComponents.body) headers[\"body\"] = mailtoComponents.body;\n\n\t\tconst fields = [];\n\t\tfor (const name in headers) {\n\t\t\tif (headers[name] !== O[name]) {\n\t\t\t\tfields.push(\n\t\t\t\t\tname.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) +\n\t\t\t\t\t\"=\" +\n\t\t\t\t\theaders[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (fields.length) {\n\t\t\tcomponents.query = fields.join(\"&\");\n\t\t}\n\n\t\treturn components;\n\t}\n}\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport ws from \"./ws\";\n\nconst handler:URISchemeHandler = {\n\tscheme : \"wss\",\n\tdomainHost : ws.domainHost,\n\tparse : ws.parse,\n\tserialize : ws.serialize\n}\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\n\nexport interface WSComponents extends URIComponents {\n\tresourceName?: string;\n\tsecure?: boolean;\n}\n\nfunction isSecure(wsComponents:WSComponents):boolean {\n\treturn typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === \"wss\";\n}\n\n//RFC 6455\nconst handler:URISchemeHandler = {\n\tscheme : \"ws\",\n\n\tdomainHost : true,\n\n\tparse : function (components:URIComponents, options:URIOptions):WSComponents {\n\t\tconst wsComponents = components as WSComponents;\n\n\t\t//indicate if the secure flag is set\n\t\twsComponents.secure = isSecure(wsComponents);\n\n\t\t//construct resouce name\n\t\twsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : '');\n\t\twsComponents.path = undefined;\n\t\twsComponents.query = undefined;\n\n\t\treturn wsComponents;\n\t},\n\n\tserialize : function (wsComponents:WSComponents, options:URIOptions):URIComponents {\n\t\t//normalize the default port\n\t\tif (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === \"\") {\n\t\t\twsComponents.port = undefined;\n\t\t}\n\n\t\t//ensure scheme matches secure flag\n\t\tif (typeof wsComponents.secure === 'boolean') {\n\t\t\twsComponents.scheme = (wsComponents.secure ? 'wss' : 'ws');\n\t\t\twsComponents.secure = undefined;\n\t\t}\n\n\t\t//reconstruct path from resource name\n\t\tif (wsComponents.resourceName) {\n\t\t\tconst [path, query] = wsComponents.resourceName.split('?');\n\t\t\twsComponents.path = (path && path !== '/' ? path : undefined);\n\t\t\twsComponents.query = query;\n\t\t\twsComponents.resourceName = undefined;\n\t\t}\n\n\t\t//forbid fragment component\n\t\twsComponents.fragment = undefined;\n\n\t\treturn wsComponents;\n\t}\n};\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport http from \"./http\";\n\nconst handler:URISchemeHandler = {\n\tscheme : \"https\",\n\tdomainHost : http.domainHost,\n\tparse : http.parse,\n\tserialize : http.serialize\n}\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\n\nconst handler:URISchemeHandler = {\n\tscheme : \"http\",\n\n\tdomainHost : true,\n\n\tparse : function (components:URIComponents, options:URIOptions):URIComponents {\n\t\t//report missing host\n\t\tif (!components.host) {\n\t\t\tcomponents.error = components.error || \"HTTP URIs must have a host.\";\n\t\t}\n\n\t\treturn components;\n\t},\n\n\tserialize : function (components:URIComponents, options:URIOptions):URIComponents {\n\t\tconst secure = String(components.scheme).toLowerCase() === \"https\";\n\n\t\t//normalize the default port\n\t\tif (components.port === (secure ? 443 : 80) || components.port === \"\") {\n\t\t\tcomponents.port = undefined;\n\t\t}\n\t\t\n\t\t//normalize the empty path\n\t\tif (!components.path) {\n\t\t\tcomponents.path = \"/\";\n\t\t}\n\n\t\t//NOTE: We do not parse query strings for HTTP URIs\n\t\t//as WWW Form Url Encoded query strings are part of the HTML4+ spec,\n\t\t//and not the HTTP spec.\n\n\t\treturn components;\n\t}\n};\n\nexport default handler;","/**\n * URI.js\n *\n * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript.\n * @author Gary Court\n * @see http://github.com/garycourt/uri-js\n */\n\n/**\n * Copyright 2011 Gary Court. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are\n * permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this list of\n * conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice, this list\n * of conditions and the following disclaimer in the documentation and/or other materials\n * provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are those of the\n * authors and should not be interpreted as representing official policies, either expressed\n * or implied, of Gary Court.\n */\n\nimport URI_PROTOCOL from \"./regexps-uri\";\nimport IRI_PROTOCOL from \"./regexps-iri\";\nimport punycode from \"punycode\";\nimport { toUpperCase, typeOf, assign } from \"./util\";\n\nexport interface URIComponents {\n\tscheme?:string;\n\tuserinfo?:string;\n\thost?:string;\n\tport?:number|string;\n\tpath?:string;\n\tquery?:string;\n\tfragment?:string;\n\treference?:string;\n\terror?:string;\n}\n\nexport interface URIOptions {\n\tscheme?:string;\n\treference?:string;\n\ttolerant?:boolean;\n\tabsolutePath?:boolean;\n\tiri?:boolean;\n\tunicodeSupport?:boolean;\n\tdomainHost?:boolean;\n}\n\nexport interface URISchemeHandler {\n\tscheme:string;\n\tparse(components:ParentComponents, options:Options):Components;\n\tserialize(components:Components, options:Options):ParentComponents;\n\tunicodeSupport?:boolean;\n\tdomainHost?:boolean;\n\tabsolutePath?:boolean;\n}\n\nexport interface URIRegExps {\n\tNOT_SCHEME : RegExp,\n\tNOT_USERINFO : RegExp,\n\tNOT_HOST : RegExp,\n\tNOT_PATH : RegExp,\n\tNOT_PATH_NOSCHEME : RegExp,\n\tNOT_QUERY : RegExp,\n\tNOT_FRAGMENT : RegExp,\n\tESCAPE : RegExp,\n\tUNRESERVED : RegExp,\n\tOTHER_CHARS : RegExp,\n\tPCT_ENCODED : RegExp,\n\tIPV4ADDRESS : RegExp,\n\tIPV6ADDRESS : RegExp,\n}\n\nexport const SCHEMES:{[scheme:string]:URISchemeHandler} = {};\n\nexport function pctEncChar(chr:string):string {\n\tconst c = chr.charCodeAt(0);\n\tlet e:string;\n\n\tif (c < 16) e = \"%0\" + c.toString(16).toUpperCase();\n\telse if (c < 128) e = \"%\" + c.toString(16).toUpperCase();\n\telse if (c < 2048) e = \"%\" + ((c >> 6) | 192).toString(16).toUpperCase() + \"%\" + ((c & 63) | 128).toString(16).toUpperCase();\n\telse e = \"%\" + ((c >> 12) | 224).toString(16).toUpperCase() + \"%\" + (((c >> 6) & 63) | 128).toString(16).toUpperCase() + \"%\" + ((c & 63) | 128).toString(16).toUpperCase();\n\n\treturn e;\n}\n\nexport function pctDecChars(str:string):string {\n\tlet newStr = \"\";\n\tlet i = 0;\n\tconst il = str.length;\n\n\twhile (i < il) {\n\t\tconst c = parseInt(str.substr(i + 1, 2), 16);\n\n\t\tif (c < 128) {\n\t\t\tnewStr += String.fromCharCode(c);\n\t\t\ti += 3;\n\t\t}\n\t\telse if (c >= 194 && c < 224) {\n\t\t\tif ((il - i) >= 6) {\n\t\t\t\tconst c2 = parseInt(str.substr(i + 4, 2), 16);\n\t\t\t\tnewStr += String.fromCharCode(((c & 31) << 6) | (c2 & 63));\n\t\t\t} else {\n\t\t\t\tnewStr += str.substr(i, 6);\n\t\t\t}\n\t\t\ti += 6;\n\t\t}\n\t\telse if (c >= 224) {\n\t\t\tif ((il - i) >= 9) {\n\t\t\t\tconst c2 = parseInt(str.substr(i + 4, 2), 16);\n\t\t\t\tconst c3 = parseInt(str.substr(i + 7, 2), 16);\n\t\t\t\tnewStr += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));\n\t\t\t} else {\n\t\t\t\tnewStr += str.substr(i, 9);\n\t\t\t}\n\t\t\ti += 9;\n\t\t}\n\t\telse {\n\t\t\tnewStr += str.substr(i, 3);\n\t\t\ti += 3;\n\t\t}\n\t}\n\n\treturn newStr;\n}\n\nfunction _normalizeComponentEncoding(components:URIComponents, protocol:URIRegExps) {\n\tfunction decodeUnreserved(str:string):string {\n\t\tconst decStr = pctDecChars(str);\n\t\treturn (!decStr.match(protocol.UNRESERVED) ? str : decStr);\n\t}\n\n\tif (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, \"\");\n\tif (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace((components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME), pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\n\treturn components;\n};\n\nfunction _stripLeadingZeros(str:string):string {\n\treturn str.replace(/^0*(.*)/, \"$1\") || \"0\";\n}\n\nfunction _normalizeIPv4(host:string, protocol:URIRegExps):string {\n\tconst matches = host.match(protocol.IPV4ADDRESS) || [];\n\tconst [, address] = matches;\n\t\n\tif (address) {\n\t\treturn address.split(\".\").map(_stripLeadingZeros).join(\".\");\n\t} else {\n\t\treturn host;\n\t}\n}\n\nfunction _normalizeIPv6(host:string, protocol:URIRegExps):string {\n\tconst matches = host.match(protocol.IPV6ADDRESS) || [];\n\tconst [, address, zone] = matches;\n\n\tif (address) {\n\t\tconst [last, first] = address.toLowerCase().split('::').reverse();\n\t\tconst firstFields = first ? first.split(\":\").map(_stripLeadingZeros) : [];\n\t\tconst lastFields = last.split(\":\").map(_stripLeadingZeros);\n\t\tconst isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]);\n\t\tconst fieldCount = isLastFieldIPv4Address ? 7 : 8;\n\t\tconst lastFieldsStart = lastFields.length - fieldCount;\n\t\tconst fields = Array(fieldCount);\n\n\t\tfor (let x = 0; x < fieldCount; ++x) {\n\t\t\tfields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || '';\n\t\t}\n\n\t\tif (isLastFieldIPv4Address) {\n\t\t\tfields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol);\n\t\t}\n\n\t\tconst allZeroFields = fields.reduce>((acc, field, index) => {\n\t\t\tif (!field || field === \"0\") {\n\t\t\t\tconst lastLongest = acc[acc.length - 1];\n\t\t\t\tif (lastLongest && lastLongest.index + lastLongest.length === index) {\n\t\t\t\t\tlastLongest.length++;\n\t\t\t\t} else {\n\t\t\t\t\tacc.push({ index, length : 1 });\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn acc;\n\t\t}, []);\n\n\t\tconst longestZeroFields = allZeroFields.sort((a, b) => b.length - a.length)[0];\n\n\t\tlet newHost:string;\n\t\tif (longestZeroFields && longestZeroFields.length > 1) {\n\t\t\tconst newFirst = fields.slice(0, longestZeroFields.index) ;\n\t\t\tconst newLast = fields.slice(longestZeroFields.index + longestZeroFields.length);\n\t\t\tnewHost = newFirst.join(\":\") + \"::\" + newLast.join(\":\");\n\t\t} else {\n\t\t\tnewHost = fields.join(\":\");\n\t\t}\n\n\t\tif (zone) {\n\t\t\tnewHost += \"%\" + zone;\n\t\t}\n\n\t\treturn newHost;\n\t} else {\n\t\treturn host;\n\t}\n}\n\nconst URI_PARSE = /^(?:([^:\\/?#]+):)?(?:\\/\\/((?:([^\\/?#@]*)@)?(\\[[^\\/?#\\]]+\\]|[^\\/?#:]*)(?:\\:(\\d*))?))?([^?#]*)(?:\\?([^#]*))?(?:#((?:.|\\n|\\r)*))?/i;\nconst NO_MATCH_IS_UNDEFINED = ((\"\").match(/(){0}/))[1] === undefined;\n\nexport function parse(uriString:string, options:URIOptions = {}):URIComponents {\n\tconst components:URIComponents = {};\n\tconst protocol = (options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL);\n\n\tif (options.reference === \"suffix\") uriString = (options.scheme ? options.scheme + \":\" : \"\") + \"//\" + uriString;\n\n\tconst matches = uriString.match(URI_PARSE);\n\n\tif (matches) {\n\t\tif (NO_MATCH_IS_UNDEFINED) {\n\t\t\t//store each component\n\t\t\tcomponents.scheme = matches[1];\n\t\t\tcomponents.userinfo = matches[3];\n\t\t\tcomponents.host = matches[4];\n\t\t\tcomponents.port = parseInt(matches[5], 10);\n\t\t\tcomponents.path = matches[6] || \"\";\n\t\t\tcomponents.query = matches[7];\n\t\t\tcomponents.fragment = matches[8];\n\n\t\t\t//fix port number\n\t\t\tif (isNaN(components.port)) {\n\t\t\t\tcomponents.port = matches[5];\n\t\t\t}\n\t\t} else { //IE FIX for improper RegExp matching\n\t\t\t//store each component\n\t\t\tcomponents.scheme = matches[1] || undefined;\n\t\t\tcomponents.userinfo = (uriString.indexOf(\"@\") !== -1 ? matches[3] : undefined);\n\t\t\tcomponents.host = (uriString.indexOf(\"//\") !== -1 ? matches[4] : undefined);\n\t\t\tcomponents.port = parseInt(matches[5], 10);\n\t\t\tcomponents.path = matches[6] || \"\";\n\t\t\tcomponents.query = (uriString.indexOf(\"?\") !== -1 ? matches[7] : undefined);\n\t\t\tcomponents.fragment = (uriString.indexOf(\"#\") !== -1 ? matches[8] : undefined);\n\n\t\t\t//fix port number\n\t\t\tif (isNaN(components.port)) {\n\t\t\t\tcomponents.port = (uriString.match(/\\/\\/(?:.|\\n)*\\:(?:\\/|\\?|\\#|$)/) ? matches[4] : undefined);\n\t\t\t}\n\t\t}\n\n\t\tif (components.host) {\n\t\t\t//normalize IP hosts\n\t\t\tcomponents.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol);\n\t\t}\n\n\t\t//determine reference type\n\t\tif (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) {\n\t\t\tcomponents.reference = \"same-document\";\n\t\t} else if (components.scheme === undefined) {\n\t\t\tcomponents.reference = \"relative\";\n\t\t} else if (components.fragment === undefined) {\n\t\t\tcomponents.reference = \"absolute\";\n\t\t} else {\n\t\t\tcomponents.reference = \"uri\";\n\t\t}\n\n\t\t//check for reference errors\n\t\tif (options.reference && options.reference !== \"suffix\" && options.reference !== components.reference) {\n\t\t\tcomponents.error = components.error || \"URI is not a \" + options.reference + \" reference.\";\n\t\t}\n\n\t\t//find scheme handler\n\t\tconst schemeHandler = SCHEMES[(options.scheme || components.scheme || \"\").toLowerCase()];\n\n\t\t//check if scheme can't handle IRIs\n\t\tif (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {\n\t\t\t//if host component is a domain name\n\t\t\tif (components.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost))) {\n\t\t\t\t//convert Unicode IDN -> ASCII IDN\n\t\t\t\ttry {\n\t\t\t\t\tcomponents.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());\n\t\t\t\t} catch (e) {\n\t\t\t\t\tcomponents.error = components.error || \"Host's domain name can not be converted to ASCII via punycode: \" + e;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//convert IRI -> URI\n\t\t\t_normalizeComponentEncoding(components, URI_PROTOCOL);\n\t\t} else {\n\t\t\t//normalize encodings\n\t\t\t_normalizeComponentEncoding(components, protocol);\n\t\t}\n\n\t\t//perform scheme specific parsing\n\t\tif (schemeHandler && schemeHandler.parse) {\n\t\t\tschemeHandler.parse(components, options);\n\t\t}\n\t} else {\n\t\tcomponents.error = components.error || \"URI can not be parsed.\";\n\t}\n\n\treturn components;\n};\n\nfunction _recomposeAuthority(components:URIComponents, options:URIOptions):string|undefined {\n\tconst protocol = (options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL);\n\tconst uriTokens:Array = [];\n\n\tif (components.userinfo !== undefined) {\n\t\turiTokens.push(components.userinfo);\n\t\turiTokens.push(\"@\");\n\t}\n\n\tif (components.host !== undefined) {\n\t\t//normalize IP hosts, add brackets and escape zone separator for IPv6\n\t\turiTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, (_, $1, $2) => \"[\" + $1 + ($2 ? \"%25\" + $2 : \"\") + \"]\"));\n\t}\n\n\tif (typeof components.port === \"number\" || typeof components.port === \"string\") {\n\t\turiTokens.push(\":\");\n\t\turiTokens.push(String(components.port));\n\t}\n\n\treturn uriTokens.length ? uriTokens.join(\"\") : undefined;\n};\n\nconst RDS1 = /^\\.\\.?\\//;\nconst RDS2 = /^\\/\\.(\\/|$)/;\nconst RDS3 = /^\\/\\.\\.(\\/|$)/;\nconst RDS4 = /^\\.\\.?$/;\nconst RDS5 = /^\\/?(?:.|\\n)*?(?=\\/|$)/;\n\nexport function removeDotSegments(input:string):string {\n\tconst output:Array = [];\n\n\twhile (input.length) {\n\t\tif (input.match(RDS1)) {\n\t\t\tinput = input.replace(RDS1, \"\");\n\t\t} else if (input.match(RDS2)) {\n\t\t\tinput = input.replace(RDS2, \"/\");\n\t\t} else if (input.match(RDS3)) {\n\t\t\tinput = input.replace(RDS3, \"/\");\n\t\t\toutput.pop();\n\t\t} else if (input === \".\" || input === \"..\") {\n\t\t\tinput = \"\";\n\t\t} else {\n\t\t\tconst im = input.match(RDS5);\n\t\t\tif (im) {\n\t\t\t\tconst s = im[0];\n\t\t\t\tinput = input.slice(s.length);\n\t\t\t\toutput.push(s);\n\t\t\t} else {\n\t\t\t\tthrow new Error(\"Unexpected dot segment condition\");\n\t\t\t}\n\t\t}\n\t}\n\n\treturn output.join(\"\");\n};\n\nexport function serialize(components:URIComponents, options:URIOptions = {}):string {\n\tconst protocol = (options.iri ? IRI_PROTOCOL : URI_PROTOCOL);\n\tconst uriTokens:Array = [];\n\n\t//find scheme handler\n\tconst schemeHandler = SCHEMES[(options.scheme || components.scheme || \"\").toLowerCase()];\n\n\t//perform scheme specific serialization\n\tif (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options);\n\n\tif (components.host) {\n\t\t//if host component is an IPv6 address\n\t\tif (protocol.IPV6ADDRESS.test(components.host)) {\n\t\t\t//TODO: normalize IPv6 address as per RFC 5952\n\t\t}\n\n\t\t//if host component is a domain name\n\t\telse if (options.domainHost || (schemeHandler && schemeHandler.domainHost)) {\n\t\t\t//convert IDN via punycode\n\t\t\ttry {\n\t\t\t\tcomponents.host = (!options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host));\n\t\t\t} catch (e) {\n\t\t\t\tcomponents.error = components.error || \"Host's domain name can not be converted to \" + (!options.iri ? \"ASCII\" : \"Unicode\") + \" via punycode: \" + e;\n\t\t\t}\n\t\t}\n\t}\n\n\t//normalize encoding\n\t_normalizeComponentEncoding(components, protocol);\n\n\tif (options.reference !== \"suffix\" && components.scheme) {\n\t\turiTokens.push(components.scheme);\n\t\turiTokens.push(\":\");\n\t}\n\n\tconst authority = _recomposeAuthority(components, options);\n\tif (authority !== undefined) {\n\t\tif (options.reference !== \"suffix\") {\n\t\t\turiTokens.push(\"//\");\n\t\t}\n\n\t\turiTokens.push(authority);\n\n\t\tif (components.path && components.path.charAt(0) !== \"/\") {\n\t\t\turiTokens.push(\"/\");\n\t\t}\n\t}\n\n\tif (components.path !== undefined) {\n\t\tlet s = components.path;\n\n\t\tif (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {\n\t\t\ts = removeDotSegments(s);\n\t\t}\n\n\t\tif (authority === undefined) {\n\t\t\ts = s.replace(/^\\/\\//, \"/%2F\"); //don't allow the path to start with \"//\"\n\t\t}\n\n\t\turiTokens.push(s);\n\t}\n\n\tif (components.query !== undefined) {\n\t\turiTokens.push(\"?\");\n\t\turiTokens.push(components.query);\n\t}\n\n\tif (components.fragment !== undefined) {\n\t\turiTokens.push(\"#\");\n\t\turiTokens.push(components.fragment);\n\t}\n\n\treturn uriTokens.join(\"\"); //merge tokens into a string\n};\n\nexport function resolveComponents(base:URIComponents, relative:URIComponents, options:URIOptions = {}, skipNormalization?:boolean):URIComponents {\n\tconst target:URIComponents = {};\n\n\tif (!skipNormalization) {\n\t\tbase = parse(serialize(base, options), options); //normalize base components\n\t\trelative = parse(serialize(relative, options), options); //normalize relative components\n\t}\n\toptions = options || {};\n\n\tif (!options.tolerant && relative.scheme) {\n\t\ttarget.scheme = relative.scheme;\n\t\t//target.authority = relative.authority;\n\t\ttarget.userinfo = relative.userinfo;\n\t\ttarget.host = relative.host;\n\t\ttarget.port = relative.port;\n\t\ttarget.path = removeDotSegments(relative.path || \"\");\n\t\ttarget.query = relative.query;\n\t} else {\n\t\tif (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {\n\t\t\t//target.authority = relative.authority;\n\t\t\ttarget.userinfo = relative.userinfo;\n\t\t\ttarget.host = relative.host;\n\t\t\ttarget.port = relative.port;\n\t\t\ttarget.path = removeDotSegments(relative.path || \"\");\n\t\t\ttarget.query = relative.query;\n\t\t} else {\n\t\t\tif (!relative.path) {\n\t\t\t\ttarget.path = base.path;\n\t\t\t\tif (relative.query !== undefined) {\n\t\t\t\t\ttarget.query = relative.query;\n\t\t\t\t} else {\n\t\t\t\t\ttarget.query = base.query;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (relative.path.charAt(0) === \"/\") {\n\t\t\t\t\ttarget.path = removeDotSegments(relative.path);\n\t\t\t\t} else {\n\t\t\t\t\tif ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {\n\t\t\t\t\t\ttarget.path = \"/\" + relative.path;\n\t\t\t\t\t} else if (!base.path) {\n\t\t\t\t\t\ttarget.path = relative.path;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttarget.path = base.path.slice(0, base.path.lastIndexOf(\"/\") + 1) + relative.path;\n\t\t\t\t\t}\n\t\t\t\t\ttarget.path = removeDotSegments(target.path);\n\t\t\t\t}\n\t\t\t\ttarget.query = relative.query;\n\t\t\t}\n\t\t\t//target.authority = base.authority;\n\t\t\ttarget.userinfo = base.userinfo;\n\t\t\ttarget.host = base.host;\n\t\t\ttarget.port = base.port;\n\t\t}\n\t\ttarget.scheme = base.scheme;\n\t}\n\n\ttarget.fragment = relative.fragment;\n\n\treturn target;\n};\n\nexport function resolve(baseURI:string, relativeURI:string, options?:URIOptions):string {\n\tconst schemelessOptions = assign({ scheme : 'null' }, options);\n\treturn serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);\n};\n\nexport function normalize(uri:string, options?:URIOptions):string;\nexport function normalize(uri:URIComponents, options?:URIOptions):URIComponents;\nexport function normalize(uri:any, options?:URIOptions):any {\n\tif (typeof uri === \"string\") {\n\t\turi = serialize(parse(uri, options), options);\n\t} else if (typeOf(uri) === \"object\") {\n\t\turi = parse(serialize(uri, options), options);\n\t}\n\n\treturn uri;\n};\n\nexport function equal(uriA:string, uriB:string, options?: URIOptions):boolean;\nexport function equal(uriA:URIComponents, uriB:URIComponents, options?:URIOptions):boolean;\nexport function equal(uriA:any, uriB:any, options?:URIOptions):boolean {\n\tif (typeof uriA === \"string\") {\n\t\turiA = serialize(parse(uriA, options), options);\n\t} else if (typeOf(uriA) === \"object\") {\n\t\turiA = serialize(uriA, options);\n\t}\n\n\tif (typeof uriB === \"string\") {\n\t\turiB = serialize(parse(uriB, options), options);\n\t} else if (typeOf(uriB) === \"object\") {\n\t\turiB = serialize(uriB, options);\n\t}\n\n\treturn uriA === uriB;\n};\n\nexport function escapeComponent(str:string, options?:URIOptions):string {\n\treturn str && str.toString().replace((!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE), pctEncChar);\n};\n\nexport function unescapeComponent(str:string, options?:URIOptions):string {\n\treturn str && str.toString().replace((!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED), pctDecChars);\n};\n","'use strict';\n\n/** Highest positive signed 32-bit float value */\nconst maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1\n\n/** Bootstring parameters */\nconst base = 36;\nconst tMin = 1;\nconst tMax = 26;\nconst skew = 38;\nconst damp = 700;\nconst initialBias = 72;\nconst initialN = 128; // 0x80\nconst delimiter = '-'; // '\\x2D'\n\n/** Regular expressions */\nconst regexPunycode = /^xn--/;\nconst regexNonASCII = /[^\\0-\\x7E]/; // non-ASCII chars\nconst regexSeparators = /[\\x2E\\u3002\\uFF0E\\uFF61]/g; // RFC 3490 separators\n\n/** Error messages */\nconst errors = {\n\t'overflow': 'Overflow: input needs wider integers to process',\n\t'not-basic': 'Illegal input >= 0x80 (not a basic code point)',\n\t'invalid-input': 'Invalid input'\n};\n\n/** Convenience shortcuts */\nconst baseMinusTMin = base - tMin;\nconst floor = Math.floor;\nconst stringFromCharCode = String.fromCharCode;\n\n/*--------------------------------------------------------------------------*/\n\n/**\n * A generic error utility function.\n * @private\n * @param {String} type The error type.\n * @returns {Error} Throws a `RangeError` with the applicable error message.\n */\nfunction error(type) {\n\tthrow new RangeError(errors[type]);\n}\n\n/**\n * A generic `Array#map` utility function.\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} callback The function that gets called for every array\n * item.\n * @returns {Array} A new array of values returned by the callback function.\n */\nfunction map(array, fn) {\n\tconst result = [];\n\tlet length = array.length;\n\twhile (length--) {\n\t\tresult[length] = fn(array[length]);\n\t}\n\treturn result;\n}\n\n/**\n * A simple `Array#map`-like wrapper to work with domain name strings or email\n * addresses.\n * @private\n * @param {String} domain The domain name or email address.\n * @param {Function} callback The function that gets called for every\n * character.\n * @returns {Array} A new string of characters returned by the callback\n * function.\n */\nfunction mapDomain(string, fn) {\n\tconst parts = string.split('@');\n\tlet result = '';\n\tif (parts.length > 1) {\n\t\t// In email addresses, only the domain name should be punycoded. Leave\n\t\t// the local part (i.e. everything up to `@`) intact.\n\t\tresult = parts[0] + '@';\n\t\tstring = parts[1];\n\t}\n\t// Avoid `split(regex)` for IE8 compatibility. See #17.\n\tstring = string.replace(regexSeparators, '\\x2E');\n\tconst labels = string.split('.');\n\tconst encoded = map(labels, fn).join('.');\n\treturn result + encoded;\n}\n\n/**\n * Creates an array containing the numeric code points of each Unicode\n * character in the string. While JavaScript uses UCS-2 internally,\n * this function will convert a pair of surrogate halves (each of which\n * UCS-2 exposes as separate characters) into a single code point,\n * matching UTF-16.\n * @see `punycode.ucs2.encode`\n * @see \n * @memberOf punycode.ucs2\n * @name decode\n * @param {String} string The Unicode input string (UCS-2).\n * @returns {Array} The new array of code points.\n */\nfunction ucs2decode(string) {\n\tconst output = [];\n\tlet counter = 0;\n\tconst length = string.length;\n\twhile (counter < length) {\n\t\tconst value = string.charCodeAt(counter++);\n\t\tif (value >= 0xD800 && value <= 0xDBFF && counter < length) {\n\t\t\t// It's a high surrogate, and there is a next character.\n\t\t\tconst extra = string.charCodeAt(counter++);\n\t\t\tif ((extra & 0xFC00) == 0xDC00) { // Low surrogate.\n\t\t\t\toutput.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);\n\t\t\t} else {\n\t\t\t\t// It's an unmatched surrogate; only append this code unit, in case the\n\t\t\t\t// next code unit is the high surrogate of a surrogate pair.\n\t\t\t\toutput.push(value);\n\t\t\t\tcounter--;\n\t\t\t}\n\t\t} else {\n\t\t\toutput.push(value);\n\t\t}\n\t}\n\treturn output;\n}\n\n/**\n * Creates a string based on an array of numeric code points.\n * @see `punycode.ucs2.decode`\n * @memberOf punycode.ucs2\n * @name encode\n * @param {Array} codePoints The array of numeric code points.\n * @returns {String} The new Unicode string (UCS-2).\n */\nconst ucs2encode = array => String.fromCodePoint(...array);\n\n/**\n * Converts a basic code point into a digit/integer.\n * @see `digitToBasic()`\n * @private\n * @param {Number} codePoint The basic numeric code point value.\n * @returns {Number} The numeric value of a basic code point (for use in\n * representing integers) in the range `0` to `base - 1`, or `base` if\n * the code point does not represent a value.\n */\nconst basicToDigit = function(codePoint) {\n\tif (codePoint - 0x30 < 0x0A) {\n\t\treturn codePoint - 0x16;\n\t}\n\tif (codePoint - 0x41 < 0x1A) {\n\t\treturn codePoint - 0x41;\n\t}\n\tif (codePoint - 0x61 < 0x1A) {\n\t\treturn codePoint - 0x61;\n\t}\n\treturn base;\n};\n\n/**\n * Converts a digit/integer into a basic code point.\n * @see `basicToDigit()`\n * @private\n * @param {Number} digit The numeric value of a basic code point.\n * @returns {Number} The basic code point whose value (when used for\n * representing integers) is `digit`, which needs to be in the range\n * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is\n * used; else, the lowercase form is used. The behavior is undefined\n * if `flag` is non-zero and `digit` has no uppercase form.\n */\nconst digitToBasic = function(digit, flag) {\n\t// 0..25 map to ASCII a..z or A..Z\n\t// 26..35 map to ASCII 0..9\n\treturn digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);\n};\n\n/**\n * Bias adaptation function as per section 3.4 of RFC 3492.\n * https://tools.ietf.org/html/rfc3492#section-3.4\n * @private\n */\nconst adapt = function(delta, numPoints, firstTime) {\n\tlet k = 0;\n\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\tdelta += floor(delta / numPoints);\n\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\tdelta = floor(delta / baseMinusTMin);\n\t}\n\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n};\n\n/**\n * Converts a Punycode string of ASCII-only symbols to a string of Unicode\n * symbols.\n * @memberOf punycode\n * @param {String} input The Punycode string of ASCII-only symbols.\n * @returns {String} The resulting string of Unicode symbols.\n */\nconst decode = function(input) {\n\t// Don't use UCS-2.\n\tconst output = [];\n\tconst inputLength = input.length;\n\tlet i = 0;\n\tlet n = initialN;\n\tlet bias = initialBias;\n\n\t// Handle the basic code points: let `basic` be the number of input code\n\t// points before the last delimiter, or `0` if there is none, then copy\n\t// the first basic code points to the output.\n\n\tlet basic = input.lastIndexOf(delimiter);\n\tif (basic < 0) {\n\t\tbasic = 0;\n\t}\n\n\tfor (let j = 0; j < basic; ++j) {\n\t\t// if it's not a basic code point\n\t\tif (input.charCodeAt(j) >= 0x80) {\n\t\t\terror('not-basic');\n\t\t}\n\t\toutput.push(input.charCodeAt(j));\n\t}\n\n\t// Main decoding loop: start just after the last delimiter if any basic code\n\t// points were copied; start at the beginning otherwise.\n\n\tfor (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {\n\n\t\t// `index` is the index of the next character to be consumed.\n\t\t// Decode a generalized variable-length integer into `delta`,\n\t\t// which gets added to `i`. The overflow checking is easier\n\t\t// if we increase `i` as we go, then subtract off its starting\n\t\t// value at the end to obtain `delta`.\n\t\tlet oldi = i;\n\t\tfor (let w = 1, k = base; /* no condition */; k += base) {\n\n\t\t\tif (index >= inputLength) {\n\t\t\t\terror('invalid-input');\n\t\t\t}\n\n\t\t\tconst digit = basicToDigit(input.charCodeAt(index++));\n\n\t\t\tif (digit >= base || digit > floor((maxInt - i) / w)) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\ti += digit * w;\n\t\t\tconst t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\n\t\t\tif (digit < t) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst baseMinusT = base - t;\n\t\t\tif (w > floor(maxInt / baseMinusT)) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\tw *= baseMinusT;\n\n\t\t}\n\n\t\tconst out = output.length + 1;\n\t\tbias = adapt(i - oldi, out, oldi == 0);\n\n\t\t// `i` was supposed to wrap around from `out` to `0`,\n\t\t// incrementing `n` each time, so we'll fix that now:\n\t\tif (floor(i / out) > maxInt - n) {\n\t\t\terror('overflow');\n\t\t}\n\n\t\tn += floor(i / out);\n\t\ti %= out;\n\n\t\t// Insert `n` at position `i` of the output.\n\t\toutput.splice(i++, 0, n);\n\n\t}\n\n\treturn String.fromCodePoint(...output);\n};\n\n/**\n * Converts a string of Unicode symbols (e.g. a domain name label) to a\n * Punycode string of ASCII-only symbols.\n * @memberOf punycode\n * @param {String} input The string of Unicode symbols.\n * @returns {String} The resulting Punycode string of ASCII-only symbols.\n */\nconst encode = function(input) {\n\tconst output = [];\n\n\t// Convert the input in UCS-2 to an array of Unicode code points.\n\tinput = ucs2decode(input);\n\n\t// Cache the length.\n\tlet inputLength = input.length;\n\n\t// Initialize the state.\n\tlet n = initialN;\n\tlet delta = 0;\n\tlet bias = initialBias;\n\n\t// Handle the basic code points.\n\tfor (const currentValue of input) {\n\t\tif (currentValue < 0x80) {\n\t\t\toutput.push(stringFromCharCode(currentValue));\n\t\t}\n\t}\n\n\tlet basicLength = output.length;\n\tlet handledCPCount = basicLength;\n\n\t// `handledCPCount` is the number of code points that have been handled;\n\t// `basicLength` is the number of basic code points.\n\n\t// Finish the basic string with a delimiter unless it's empty.\n\tif (basicLength) {\n\t\toutput.push(delimiter);\n\t}\n\n\t// Main encoding loop:\n\twhile (handledCPCount < inputLength) {\n\n\t\t// All non-basic code points < n have been handled already. Find the next\n\t\t// larger one:\n\t\tlet m = maxInt;\n\t\tfor (const currentValue of input) {\n\t\t\tif (currentValue >= n && currentValue < m) {\n\t\t\t\tm = currentValue;\n\t\t\t}\n\t\t}\n\n\t\t// Increase `delta` enough to advance the decoder's state to ,\n\t\t// but guard against overflow.\n\t\tconst handledCPCountPlusOne = handledCPCount + 1;\n\t\tif (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {\n\t\t\terror('overflow');\n\t\t}\n\n\t\tdelta += (m - n) * handledCPCountPlusOne;\n\t\tn = m;\n\n\t\tfor (const currentValue of input) {\n\t\t\tif (currentValue < n && ++delta > maxInt) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\t\t\tif (currentValue == n) {\n\t\t\t\t// Represent delta as a generalized variable-length integer.\n\t\t\t\tlet q = delta;\n\t\t\t\tfor (let k = base; /* no condition */; k += base) {\n\t\t\t\t\tconst t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\t\t\t\t\tif (q < t) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst qMinusT = q - t;\n\t\t\t\t\tconst baseMinusT = base - t;\n\t\t\t\t\toutput.push(\n\t\t\t\t\t\tstringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))\n\t\t\t\t\t);\n\t\t\t\t\tq = floor(qMinusT / baseMinusT);\n\t\t\t\t}\n\n\t\t\t\toutput.push(stringFromCharCode(digitToBasic(q, 0)));\n\t\t\t\tbias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);\n\t\t\t\tdelta = 0;\n\t\t\t\t++handledCPCount;\n\t\t\t}\n\t\t}\n\n\t\t++delta;\n\t\t++n;\n\n\t}\n\treturn output.join('');\n};\n\n/**\n * Converts a Punycode string representing a domain name or an email address\n * to Unicode. Only the Punycoded parts of the input will be converted, i.e.\n * it doesn't matter if you call it on a string that has already been\n * converted to Unicode.\n * @memberOf punycode\n * @param {String} input The Punycoded domain name or email address to\n * convert to Unicode.\n * @returns {String} The Unicode representation of the given Punycode\n * string.\n */\nconst toUnicode = function(input) {\n\treturn mapDomain(input, function(string) {\n\t\treturn regexPunycode.test(string)\n\t\t\t? decode(string.slice(4).toLowerCase())\n\t\t\t: string;\n\t});\n};\n\n/**\n * Converts a Unicode string representing a domain name or an email address to\n * Punycode. Only the non-ASCII parts of the domain name will be converted,\n * i.e. it doesn't matter if you call it with a domain that's already in\n * ASCII.\n * @memberOf punycode\n * @param {String} input The domain name or email address to convert, as a\n * Unicode string.\n * @returns {String} The Punycode representation of the given domain name or\n * email address.\n */\nconst toASCII = function(input) {\n\treturn mapDomain(input, function(string) {\n\t\treturn regexNonASCII.test(string)\n\t\t\t? 'xn--' + encode(string)\n\t\t\t: string;\n\t});\n};\n\n/*--------------------------------------------------------------------------*/\n\n/** Define the public API */\nconst punycode = {\n\t/**\n\t * A string representing the current Punycode.js version number.\n\t * @memberOf punycode\n\t * @type String\n\t */\n\t'version': '2.1.0',\n\t/**\n\t * An object of methods to convert from JavaScript's internal character\n\t * representation (UCS-2) to Unicode code points, and back.\n\t * @see \n\t * @memberOf punycode\n\t * @type Object\n\t */\n\t'ucs2': {\n\t\t'decode': ucs2decode,\n\t\t'encode': ucs2encode\n\t},\n\t'decode': decode,\n\t'encode': encode,\n\t'toASCII': toASCII,\n\t'toUnicode': toUnicode\n};\n\nexport default punycode;\n","import { URIRegExps } from \"./uri\";\nimport { buildExps } from \"./regexps-uri\";\n\nexport default buildExps(true);\n","import { URIRegExps } from \"./uri\";\nimport { merge, subexp } from \"./util\";\n\nexport function buildExps(isIRI:boolean):URIRegExps {\n\tconst\n\t\tALPHA$$ = \"[A-Za-z]\",\n\t\tCR$ = \"[\\\\x0D]\",\n\t\tDIGIT$$ = \"[0-9]\",\n\t\tDQUOTE$$ = \"[\\\\x22]\",\n\t\tHEXDIG$$ = merge(DIGIT$$, \"[A-Fa-f]\"), //case-insensitive\n\t\tLF$$ = \"[\\\\x0A]\",\n\t\tSP$$ = \"[\\\\x20]\",\n\t\tPCT_ENCODED$ = subexp(subexp(\"%[EFef]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%[89A-Fa-f]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%\" + HEXDIG$$ + HEXDIG$$)), //expanded\n\t\tGEN_DELIMS$$ = \"[\\\\:\\\\/\\\\?\\\\#\\\\[\\\\]\\\\@]\",\n\t\tSUB_DELIMS$$ = \"[\\\\!\\\\$\\\\&\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,\\\\;\\\\=]\",\n\t\tRESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$),\n\t\tUCSCHAR$$ = isIRI ? \"[\\\\xA0-\\\\u200D\\\\u2010-\\\\u2029\\\\u202F-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF]\" : \"[]\", //subset, excludes bidi control characters\n\t\tIPRIVATE$$ = isIRI ? \"[\\\\uE000-\\\\uF8FF]\" : \"[]\", //subset\n\t\tUNRESERVED$$ = merge(ALPHA$$, DIGIT$$, \"[\\\\-\\\\.\\\\_\\\\~]\", UCSCHAR$$),\n\t\tSCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, \"[\\\\+\\\\-\\\\.]\") + \"*\"),\n\t\tUSERINFO$ = subexp(subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:]\")) + \"*\"),\n\t\tDEC_OCTET$ = subexp(subexp(\"25[0-5]\") + \"|\" + subexp(\"2[0-4]\" + DIGIT$$) + \"|\" + subexp(\"1\" + DIGIT$$ + DIGIT$$) + \"|\" + subexp(\"[1-9]\" + DIGIT$$) + \"|\" + DIGIT$$),\n\t\tDEC_OCTET_RELAXED$ = subexp(subexp(\"25[0-5]\") + \"|\" + subexp(\"2[0-4]\" + DIGIT$$) + \"|\" + subexp(\"1\" + DIGIT$$ + DIGIT$$) + \"|\" + subexp(\"0?[1-9]\" + DIGIT$$) + \"|0?0?\" + DIGIT$$), //relaxed parsing rules\n\t\tIPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + \"\\\\.\" + DEC_OCTET_RELAXED$ + \"\\\\.\" + DEC_OCTET_RELAXED$ + \"\\\\.\" + DEC_OCTET_RELAXED$),\n\t\tH16$ = subexp(HEXDIG$$ + \"{1,4}\"),\n\t\tLS32$ = subexp(subexp(H16$ + \"\\\\:\" + H16$) + \"|\" + IPV4ADDRESS$),\n\t\tIPV6ADDRESS1$ = subexp( subexp(H16$ + \"\\\\:\") + \"{6}\" + LS32$), // 6( h16 \":\" ) ls32\n\t\tIPV6ADDRESS2$ = subexp( \"\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{5}\" + LS32$), // \"::\" 5( h16 \":\" ) ls32\n\t\tIPV6ADDRESS3$ = subexp(subexp( H16$) + \"?\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{4}\" + LS32$), //[ h16 ] \"::\" 4( h16 \":\" ) ls32\n\t\tIPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,1}\" + H16$) + \"?\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{3}\" + LS32$), //[ *1( h16 \":\" ) h16 ] \"::\" 3( h16 \":\" ) ls32\n\t\tIPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,2}\" + H16$) + \"?\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{2}\" + LS32$), //[ *2( h16 \":\" ) h16 ] \"::\" 2( h16 \":\" ) ls32\n\t\tIPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,3}\" + H16$) + \"?\\\\:\\\\:\" + H16$ + \"\\\\:\" + LS32$), //[ *3( h16 \":\" ) h16 ] \"::\" h16 \":\" ls32\n\t\tIPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,4}\" + H16$) + \"?\\\\:\\\\:\" + LS32$), //[ *4( h16 \":\" ) h16 ] \"::\" ls32\n\t\tIPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,5}\" + H16$) + \"?\\\\:\\\\:\" + H16$ ), //[ *5( h16 \":\" ) h16 ] \"::\" h16\n\t\tIPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,6}\" + H16$) + \"?\\\\:\\\\:\" ), //[ *6( h16 \":\" ) h16 ] \"::\"\n\t\tIPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join(\"|\")),\n\t\tZONEID$ = subexp(subexp(UNRESERVED$$ + \"|\" + PCT_ENCODED$) + \"+\"), //RFC 6874\n\t\tIPV6ADDRZ$ = subexp(IPV6ADDRESS$ + \"\\\\%25\" + ZONEID$), //RFC 6874\n\t\tIPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp(\"\\\\%25|\\\\%(?!\" + HEXDIG$$ + \"{2})\") + ZONEID$), //RFC 6874, with relaxed parsing rules\n\t\tIPVFUTURE$ = subexp(\"[vV]\" + HEXDIG$$ + \"+\\\\.\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:]\") + \"+\"),\n\t\tIP_LITERAL$ = subexp(\"\\\\[\" + subexp(IPV6ADDRZ_RELAXED$ + \"|\" + IPV6ADDRESS$ + \"|\" + IPVFUTURE$) + \"\\\\]\"), //RFC 6874\n\t\tREG_NAME$ = subexp(subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$)) + \"*\"),\n\t\tHOST$ = subexp(IP_LITERAL$ + \"|\" + IPV4ADDRESS$ + \"(?!\" + REG_NAME$ + \")\" + \"|\" + REG_NAME$),\n\t\tPORT$ = subexp(DIGIT$$ + \"*\"),\n\t\tAUTHORITY$ = subexp(subexp(USERINFO$ + \"@\") + \"?\" + HOST$ + subexp(\"\\\\:\" + PORT$) + \"?\"),\n\t\tPCHAR$ = subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:\\\\@]\")),\n\t\tSEGMENT$ = subexp(PCHAR$ + \"*\"),\n\t\tSEGMENT_NZ$ = subexp(PCHAR$ + \"+\"),\n\t\tSEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\@]\")) + \"+\"),\n\t\tPATH_ABEMPTY$ = subexp(subexp(\"\\\\/\" + SEGMENT$) + \"*\"),\n\t\tPATH_ABSOLUTE$ = subexp(\"\\\\/\" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + \"?\"), //simplified\n\t\tPATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), //simplified\n\t\tPATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), //simplified\n\t\tPATH_EMPTY$ = \"(?!\" + PCHAR$ + \")\",\n\t\tPATH$ = subexp(PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_NOSCHEME$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$),\n\t\tQUERY$ = subexp(subexp(PCHAR$ + \"|\" + merge(\"[\\\\/\\\\?]\", IPRIVATE$$)) + \"*\"),\n\t\tFRAGMENT$ = subexp(subexp(PCHAR$ + \"|[\\\\/\\\\?]\") + \"*\"),\n\t\tHIER_PART$ = subexp(subexp(\"\\\\/\\\\/\" + AUTHORITY$ + PATH_ABEMPTY$) + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$),\n\t\tURI$ = subexp(SCHEME$ + \"\\\\:\" + HIER_PART$ + subexp(\"\\\\?\" + QUERY$) + \"?\" + subexp(\"\\\\#\" + FRAGMENT$) + \"?\"),\n\t\tRELATIVE_PART$ = subexp(subexp(\"\\\\/\\\\/\" + AUTHORITY$ + PATH_ABEMPTY$) + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_NOSCHEME$ + \"|\" + PATH_EMPTY$),\n\t\tRELATIVE$ = subexp(RELATIVE_PART$ + subexp(\"\\\\?\" + QUERY$) + \"?\" + subexp(\"\\\\#\" + FRAGMENT$) + \"?\"),\n\t\tURI_REFERENCE$ = subexp(URI$ + \"|\" + RELATIVE$),\n\t\tABSOLUTE_URI$ = subexp(SCHEME$ + \"\\\\:\" + HIER_PART$ + subexp(\"\\\\?\" + QUERY$) + \"?\"),\n\n\t\tGENERIC_REF$ = \"^(\" + SCHEME$ + \")\\\\:\" + subexp(subexp(\"\\\\/\\\\/(\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?)\") + \"?(\" + PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$ + \")\") + subexp(\"\\\\?(\" + QUERY$ + \")\") + \"?\" + subexp(\"\\\\#(\" + FRAGMENT$ + \")\") + \"?$\",\n\t\tRELATIVE_REF$ = \"^(){0}\" + subexp(subexp(\"\\\\/\\\\/(\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?)\") + \"?(\" + PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_NOSCHEME$ + \"|\" + PATH_EMPTY$ + \")\") + subexp(\"\\\\?(\" + QUERY$ + \")\") + \"?\" + subexp(\"\\\\#(\" + FRAGMENT$ + \")\") + \"?$\",\n\t\tABSOLUTE_REF$ = \"^(\" + SCHEME$ + \")\\\\:\" + subexp(subexp(\"\\\\/\\\\/(\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?)\") + \"?(\" + PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$ + \")\") + subexp(\"\\\\?(\" + QUERY$ + \")\") + \"?$\",\n\t\tSAMEDOC_REF$ = \"^\" + subexp(\"\\\\#(\" + FRAGMENT$ + \")\") + \"?$\",\n\t\tAUTHORITY_REF$ = \"^\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?$\"\n\t;\n\n\treturn {\n\t\tNOT_SCHEME : new RegExp(merge(\"[^]\", ALPHA$$, DIGIT$$, \"[\\\\+\\\\-\\\\.]\"), \"g\"),\n\t\tNOT_USERINFO : new RegExp(merge(\"[^\\\\%\\\\:]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_HOST : new RegExp(merge(\"[^\\\\%\\\\[\\\\]\\\\:]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_PATH : new RegExp(merge(\"[^\\\\%\\\\/\\\\:\\\\@]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_PATH_NOSCHEME : new RegExp(merge(\"[^\\\\%\\\\/\\\\@]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_QUERY : new RegExp(merge(\"[^\\\\%]\", UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:\\\\@\\\\/\\\\?]\", IPRIVATE$$), \"g\"),\n\t\tNOT_FRAGMENT : new RegExp(merge(\"[^\\\\%]\", UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:\\\\@\\\\/\\\\?]\"), \"g\"),\n\t\tESCAPE : new RegExp(merge(\"[^]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tUNRESERVED : new RegExp(UNRESERVED$$, \"g\"),\n\t\tOTHER_CHARS : new RegExp(merge(\"[^\\\\%]\", UNRESERVED$$, RESERVED$$), \"g\"),\n\t\tPCT_ENCODED : new RegExp(PCT_ENCODED$, \"g\"),\n\t\tIPV4ADDRESS : new RegExp(\"^(\" + IPV4ADDRESS$ + \")$\"),\n\t\tIPV6ADDRESS : new RegExp(\"^\\\\[?(\" + IPV6ADDRESS$ + \")\" + subexp(subexp(\"\\\\%25|\\\\%(?!\" + HEXDIG$$ + \"{2})\") + \"(\" + ZONEID$ + \")\") + \"?\\\\]?$\") //RFC 6874, with relaxed parsing rules\n\t};\n}\n\nexport default buildExps(false);\n","export function merge(...sets:Array):string {\n\tif (sets.length > 1) {\n\t\tsets[0] = sets[0].slice(0, -1);\n\t\tconst xl = sets.length - 1;\n\t\tfor (let x = 1; x < xl; ++x) {\n\t\t\tsets[x] = sets[x].slice(1, -1);\n\t\t}\n\t\tsets[xl] = sets[xl].slice(1);\n\t\treturn sets.join('');\n\t} else {\n\t\treturn sets[0];\n\t}\n}\n\nexport function subexp(str:string):string {\n\treturn \"(?:\" + str + \")\";\n}\n\nexport function typeOf(o:any):string {\n\treturn o === undefined ? \"undefined\" : (o === null ? \"null\" : Object.prototype.toString.call(o).split(\" \").pop().split(\"]\").shift().toLowerCase());\n}\n\nexport function toUpperCase(str:string):string {\n\treturn str.toUpperCase();\n}\n\nexport function toArray(obj:any):Array {\n\treturn obj !== undefined && obj !== null ? (obj instanceof Array ? obj : (typeof obj.length !== \"number\" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj))) : [];\n}\n\n\nexport function assign(target: object, source: any): any {\n\tconst obj = target as any;\n\tif (source) {\n\t\tfor (const key in source) {\n\t\t\tobj[key] = source[key];\n\t\t}\n\t}\n\treturn obj;\n}"],"names":["SCHEMES","uuid","scheme","urn","mailto","wss","ws","https","http","urnComponents","nss","uuidComponents","toLowerCase","options","error","tolerant","match","UUID","undefined","handler","uriComponents","path","nid","schemeHandler","serialize","urnScheme","parse","matches","components","URN_PARSE","query","fields","join","length","push","name","replace","PCT_ENCODED","decodeUnreserved","toUpperCase","NOT_HFNAME","pctEncChar","headers","NOT_HFVALUE","O","mailtoComponents","body","subject","to","x","localPart","domain","iri","e","punycode","toASCII","unescapeComponent","toUnicode","toAddr","slice","atIdx","NOT_LOCAL_PART","lastIndexOf","String","xl","toArray","addr","unicodeSupport","split","unknownHeaders","hfield","toAddrs","hfields","decStr","UNRESERVED","str","pctDecChars","RegExp","merge","UNRESERVED$$","SOME_DELIMS$$","ATEXT$$","VCHAR$$","PCT_ENCODED$","QTEXT$$","subexp","HEXDIG$$","isIRI","domainHost","wsComponents","fragment","resourceName","secure","port","isSecure","host","toString","URI_PROTOCOL","IRI_PROTOCOL","ESCAPE","escapeComponent","uriA","uriB","typeOf","equal","uri","normalize","resolveComponents","baseURI","schemelessOptions","relativeURI","assign","resolve","target","relative","base","userinfo","removeDotSegments","charAt","skipNormalization","uriTokens","s","authority","absolutePath","reference","_recomposeAuthority","protocol","IPV6ADDRESS","test","output","Error","input","im","RDS5","pop","RDS3","RDS2","RDS1","$1","$2","_normalizeIPv6","_normalizeIPv4","_","uriString","isNaN","indexOf","parseInt","NO_MATCH_IS_UNDEFINED","URI_PARSE","newHost","zone","newFirst","newLast","longestZeroFields","index","b","a","allZeroFields","sort","acc","lastLongest","field","reduce","fieldCount","isLastFieldIPv4Address","firstFields","lastFields","lastFieldsStart","Array","IPV4ADDRESS","last","map","_stripLeadingZeros","first","address","reverse","NOT_FRAGMENT","NOT_QUERY","NOT_PATH","NOT_PATH_NOSCHEME","NOT_HOST","NOT_USERINFO","NOT_SCHEME","_normalizeComponentEncoding","newStr","substr","i","fromCharCode","c","c2","c3","il","chr","charCodeAt","encode","decode","ucs2encode","ucs2decode","regexNonASCII","string","mapDomain","regexPunycode","n","delta","handledCPCount","adapt","handledCPCountPlusOne","basicLength","stringFromCharCode","digitToBasic","q","floor","qMinusT","baseMinusT","t","k","bias","tMin","tMax","currentValue","maxInt","m","inputLength","delimiter","initialBias","initialN","fromCodePoint","splice","out","oldi","w","digit","basicToDigit","basic","j","baseMinusTMin","skew","numPoints","firstTime","damp","flag","codePoint","array","value","extra","counter","result","encoded","labels","fn","regexSeparators","parts","RangeError","errors","type","Math","buildExps","IPV6ADDRESS$","ZONEID$","IPV4ADDRESS$","RESERVED$$","SUB_DELIMS$$","IPRIVATE$$","ALPHA$$","DIGIT$$","AUTHORITY_REF$","USERINFO$","HOST$","PORT$","SAMEDOC_REF$","FRAGMENT$","ABSOLUTE_REF$","SCHEME$","PATH_ABEMPTY$","PATH_ABSOLUTE$","PATH_ROOTLESS$","PATH_EMPTY$","QUERY$","RELATIVE_REF$","PATH_NOSCHEME$","GENERIC_REF$","ABSOLUTE_URI$","HIER_PART$","URI_REFERENCE$","URI$","RELATIVE$","RELATIVE_PART$","AUTHORITY$","PCHAR$","PATH$","SEGMENT_NZ$","SEGMENT_NZ_NC$","SEGMENT$","IP_LITERAL$","REG_NAME$","IPV6ADDRZ_RELAXED$","IPVFUTURE$","IPV6ADDRESS1$","IPV6ADDRESS2$","IPV6ADDRESS3$","IPV6ADDRESS4$","IPV6ADDRESS5$","IPV6ADDRESS6$","IPV6ADDRESS7$","IPV6ADDRESS8$","IPV6ADDRESS9$","H16$","LS32$","DEC_OCTET_RELAXED$","DEC_OCTET$","UCSCHAR$$","GEN_DELIMS$$","SP$$","DQUOTE$$","CR$","obj","key","source","setInterval","call","prototype","o","Object","shift","sets"],"mappings":";;;;;;;AYAA,SAAA8E,KAAA,GAAA;sCAAyBsP,IAAzB;YAAA;;;QACKA,KAAKnS,MAAL,GAAc,CAA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eR,IAAf,GAAsBU,eAAeD,GAArC;uBACeA,GAAf,GAAqBQ,SAArB;YAEI,CAACL,QAAQE,QAAT,KAAsB,CAACJ,eAAeV,IAAhB,IAAwB,CAACU,eAAeV,IAAf,CAAoBe,KAApB,CAA0BC,IAA1B,CAA/C,CAAJ,EAAqF;2BACrEH,KAAf,GAAuBH,eAAeG,KAAf,IAAwB,oBAA/C;;eAGMH,cAAP;KAZ0E;eAe/D,mBAAUA,cAAV,EAAyCE,OAAzC,EAAb;YACQJ,gBAAgBE,cAAtB;;sBAEcD,GAAd,GAAoB,CAACC,eAAeV,IAAf,IAAuB,EAAxB,EAA4BW,WAA5B,EAApB;eACOH,aAAP;;CAnBF,CAuBA;;ADhCAT,QAAQQ,QAAKN,MAAb,IAAuBM,OAAvB;AAEA,AACAR,QAAQO,UAAML,MAAd,IAAwBK,SAAxB;AAEA,AACAP,QAAQM,UAAGJ,MAAX,IAAqBI,SAArB;AAEA,AACAN,QAAQK,UAAIH,MAAZ,IAAsBG,SAAtB;AAEA,AACAL,QAAQI,UAAOF,MAAf,IAAyBE,SAAzB;AAEA,AACAJ,QAAQG,UAAID,MAAZ,IAAsBC,SAAtB;AAEA,AACAH,QAAQC,UAAKC,MAAb,IAAuBD,SAAvB,CAEA;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/uri-js/dist/es5/uri.all.min.d.ts b/node_modules/uri-js/dist/es5/uri.all.min.d.ts new file mode 100755 index 0000000..da51e23 --- /dev/null +++ b/node_modules/uri-js/dist/es5/uri.all.min.d.ts @@ -0,0 +1,59 @@ +export interface URIComponents { + scheme?: string; + userinfo?: string; + host?: string; + port?: number | string; + path?: string; + query?: string; + fragment?: string; + reference?: string; + error?: string; +} +export interface URIOptions { + scheme?: string; + reference?: string; + tolerant?: boolean; + absolutePath?: boolean; + iri?: boolean; + unicodeSupport?: boolean; + domainHost?: boolean; +} +export interface URISchemeHandler { + scheme: string; + parse(components: ParentComponents, options: Options): Components; + serialize(components: Components, options: Options): ParentComponents; + unicodeSupport?: boolean; + domainHost?: boolean; + absolutePath?: boolean; +} +export interface URIRegExps { + NOT_SCHEME: RegExp; + NOT_USERINFO: RegExp; + NOT_HOST: RegExp; + NOT_PATH: RegExp; + NOT_PATH_NOSCHEME: RegExp; + NOT_QUERY: RegExp; + NOT_FRAGMENT: RegExp; + ESCAPE: RegExp; + UNRESERVED: RegExp; + OTHER_CHARS: RegExp; + PCT_ENCODED: RegExp; + IPV4ADDRESS: RegExp; + IPV6ADDRESS: RegExp; +} +export declare const SCHEMES: { + [scheme: string]: URISchemeHandler; +}; +export declare function pctEncChar(chr: string): string; +export declare function pctDecChars(str: string): string; +export declare function parse(uriString: string, options?: URIOptions): URIComponents; +export declare function removeDotSegments(input: string): string; +export declare function serialize(components: URIComponents, options?: URIOptions): string; +export declare function resolveComponents(base: URIComponents, relative: URIComponents, options?: URIOptions, skipNormalization?: boolean): URIComponents; +export declare function resolve(baseURI: string, relativeURI: string, options?: URIOptions): string; +export declare function normalize(uri: string, options?: URIOptions): string; +export declare function normalize(uri: URIComponents, options?: URIOptions): URIComponents; +export declare function equal(uriA: string, uriB: string, options?: URIOptions): boolean; +export declare function equal(uriA: URIComponents, uriB: URIComponents, options?: URIOptions): boolean; +export declare function escapeComponent(str: string, options?: URIOptions): string; +export declare function unescapeComponent(str: string, options?: URIOptions): string; diff --git a/node_modules/uri-js/dist/es5/uri.all.min.js b/node_modules/uri-js/dist/es5/uri.all.min.js new file mode 100755 index 0000000..fcd8458 --- /dev/null +++ b/node_modules/uri-js/dist/es5/uri.all.min.js @@ -0,0 +1,3 @@ +/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */ +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r(e.URI=e.URI||{})}(this,function(e){"use strict";function r(){for(var e=arguments.length,r=Array(e),n=0;n1){r[0]=r[0].slice(0,-1);for(var t=r.length-1,o=1;o1&&(t=n[0]+"@",e=n[1]),e=e.replace(j,"."),t+f(e.split("."),r).join(".")}function p(e){for(var r=[],n=0,t=e.length;n=55296&&o<=56319&&n>6|192).toString(16).toUpperCase()+"%"+(63&r|128).toString(16).toUpperCase():"%"+(r>>12|224).toString(16).toUpperCase()+"%"+(r>>6&63|128).toString(16).toUpperCase()+"%"+(63&r|128).toString(16).toUpperCase()}function d(e){for(var r="",n=0,t=e.length;n=194&&o<224){if(t-n>=6){var a=parseInt(e.substr(n+4,2),16);r+=String.fromCharCode((31&o)<<6|63&a)}else r+=e.substr(n,6);n+=6}else if(o>=224){if(t-n>=9){var i=parseInt(e.substr(n+4,2),16),u=parseInt(e.substr(n+7,2),16);r+=String.fromCharCode((15&o)<<12|(63&i)<<6|63&u)}else r+=e.substr(n,9);n+=9}else r+=e.substr(n,3),n+=3}return r}function l(e,r){function n(e){var n=d(e);return n.match(r.UNRESERVED)?n:e}return e.scheme&&(e.scheme=String(e.scheme).replace(r.PCT_ENCODED,n).toLowerCase().replace(r.NOT_SCHEME,"")),e.userinfo!==undefined&&(e.userinfo=String(e.userinfo).replace(r.PCT_ENCODED,n).replace(r.NOT_USERINFO,h).replace(r.PCT_ENCODED,o)),e.host!==undefined&&(e.host=String(e.host).replace(r.PCT_ENCODED,n).toLowerCase().replace(r.NOT_HOST,h).replace(r.PCT_ENCODED,o)),e.path!==undefined&&(e.path=String(e.path).replace(r.PCT_ENCODED,n).replace(e.scheme?r.NOT_PATH:r.NOT_PATH_NOSCHEME,h).replace(r.PCT_ENCODED,o)),e.query!==undefined&&(e.query=String(e.query).replace(r.PCT_ENCODED,n).replace(r.NOT_QUERY,h).replace(r.PCT_ENCODED,o)),e.fragment!==undefined&&(e.fragment=String(e.fragment).replace(r.PCT_ENCODED,n).replace(r.NOT_FRAGMENT,h).replace(r.PCT_ENCODED,o)),e}function m(e){return e.replace(/^0*(.*)/,"$1")||"0"}function g(e,r){var n=e.match(r.IPV4ADDRESS)||[],t=T(n,2),o=t[1];return o?o.split(".").map(m).join("."):e}function v(e,r){var n=e.match(r.IPV6ADDRESS)||[],t=T(n,3),o=t[1],a=t[2];if(o){for(var i=o.toLowerCase().split("::").reverse(),u=T(i,2),s=u[0],f=u[1],c=f?f.split(":").map(m):[],p=s.split(":").map(m),h=r.IPV4ADDRESS.test(p[p.length-1]),d=h?7:8,l=p.length-d,v=Array(d),E=0;E1){var A=v.slice(0,y.index),D=v.slice(y.index+y.length);S=A.join(":")+"::"+D.join(":")}else S=v.join(":");return a&&(S+="%"+a),S}return e}function E(e){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},n={},t=!1!==r.iri?R:F;"suffix"===r.reference&&(e=(r.scheme?r.scheme+":":"")+"//"+e);var o=e.match(K);if(o){W?(n.scheme=o[1],n.userinfo=o[3],n.host=o[4],n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=o[7],n.fragment=o[8],isNaN(n.port)&&(n.port=o[5])):(n.scheme=o[1]||undefined,n.userinfo=-1!==e.indexOf("@")?o[3]:undefined,n.host=-1!==e.indexOf("//")?o[4]:undefined,n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=-1!==e.indexOf("?")?o[7]:undefined,n.fragment=-1!==e.indexOf("#")?o[8]:undefined,isNaN(n.port)&&(n.port=e.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?o[4]:undefined)),n.host&&(n.host=v(g(n.host,t),t)),n.scheme!==undefined||n.userinfo!==undefined||n.host!==undefined||n.port!==undefined||n.path||n.query!==undefined?n.scheme===undefined?n.reference="relative":n.fragment===undefined?n.reference="absolute":n.reference="uri":n.reference="same-document",r.reference&&"suffix"!==r.reference&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");var a=J[(r.scheme||n.scheme||"").toLowerCase()];if(r.unicodeSupport||a&&a.unicodeSupport)l(n,t);else{if(n.host&&(r.domainHost||a&&a.domainHost))try{n.host=B.toASCII(n.host.replace(t.PCT_ENCODED,d).toLowerCase())}catch(i){n.error=n.error||"Host's domain name can not be converted to ASCII via punycode: "+i}l(n,F)}a&&a.parse&&a.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}function C(e,r){var n=!1!==r.iri?R:F,t=[];return e.userinfo!==undefined&&(t.push(e.userinfo),t.push("@")),e.host!==undefined&&t.push(v(g(String(e.host),n),n).replace(n.IPV6ADDRESS,function(e,r,n){return"["+r+(n?"%25"+n:"")+"]"})),"number"!=typeof e.port&&"string"!=typeof e.port||(t.push(":"),t.push(String(e.port))),t.length?t.join(""):undefined}function y(e){for(var r=[];e.length;)if(e.match(X))e=e.replace(X,"");else if(e.match(ee))e=e.replace(ee,"/");else if(e.match(re))e=e.replace(re,"/"),r.pop();else if("."===e||".."===e)e="";else{var n=e.match(ne);if(!n)throw new Error("Unexpected dot segment condition");var t=n[0];e=e.slice(t.length),r.push(t)}return r.join("")}function S(e){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},n=r.iri?R:F,t=[],o=J[(r.scheme||e.scheme||"").toLowerCase()];if(o&&o.serialize&&o.serialize(e,r),e.host)if(n.IPV6ADDRESS.test(e.host));else if(r.domainHost||o&&o.domainHost)try{e.host=r.iri?B.toUnicode(e.host):B.toASCII(e.host.replace(n.PCT_ENCODED,d).toLowerCase())}catch(u){e.error=e.error||"Host's domain name can not be converted to "+(r.iri?"Unicode":"ASCII")+" via punycode: "+u}l(e,n),"suffix"!==r.reference&&e.scheme&&(t.push(e.scheme),t.push(":"));var a=C(e,r);if(a!==undefined&&("suffix"!==r.reference&&t.push("//"),t.push(a),e.path&&"/"!==e.path.charAt(0)&&t.push("/")),e.path!==undefined){var i=e.path;r.absolutePath||o&&o.absolutePath||(i=y(i)),a===undefined&&(i=i.replace(/^\/\//,"/%2F")),t.push(i)}return e.query!==undefined&&(t.push("?"),t.push(e.query)),e.fragment!==undefined&&(t.push("#"),t.push(e.fragment)),t.join("")}function A(e,r){var n=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{},t=arguments[3],o={};return t||(e=E(S(e,n),n),r=E(S(r,n),n)),n=n||{},!n.tolerant&&r.scheme?(o.scheme=r.scheme,o.userinfo=r.userinfo,o.host=r.host,o.port=r.port,o.path=y(r.path||""),o.query=r.query):(r.userinfo!==undefined||r.host!==undefined||r.port!==undefined?(o.userinfo=r.userinfo,o.host=r.host,o.port=r.port,o.path=y(r.path||""),o.query=r.query):(r.path?("/"===r.path.charAt(0)?o.path=y(r.path):(e.userinfo===undefined&&e.host===undefined&&e.port===undefined||e.path?e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+r.path:o.path=r.path:o.path="/"+r.path,o.path=y(o.path)),o.query=r.query):(o.path=e.path,r.query!==undefined?o.query=r.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=r.fragment,o}function D(e,r,n){var t=i({scheme:"null"},n);return S(A(E(e,t),E(r,t),t,!0),t)}function w(e,r){return"string"==typeof e?e=S(E(e,r),r):"object"===t(e)&&(e=E(S(e,r),r)),e}function b(e,r,n){return"string"==typeof e?e=S(E(e,n),n):"object"===t(e)&&(e=S(e,n)),"string"==typeof r?r=S(E(r,n),n):"object"===t(r)&&(r=S(r,n)),e===r}function x(e,r){return e&&e.toString().replace(r&&r.iri?R.ESCAPE:F.ESCAPE,h)}function O(e,r){return e&&e.toString().replace(r&&r.iri?R.PCT_ENCODED:F.PCT_ENCODED,d)}function N(e){return"boolean"==typeof e.secure?e.secure:"wss"===String(e.scheme).toLowerCase()}function I(e){var r=d(e);return r.match(he)?r:e}var F=u(!1),R=u(!0),T=function(){function e(e,r){var n=[],t=!0,o=!1,a=undefined;try{for(var i,u=e[Symbol.iterator]();!(t=(i=u.next()).done)&&(n.push(i.value),!r||n.length!==r);t=!0);}catch(s){o=!0,a=s}finally{try{!t&&u["return"]&&u["return"]()}finally{if(o)throw a}}return n}return function(r,n){if(Array.isArray(r))return r;if(Symbol.iterator in Object(r))return e(r,n);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),_=function(e){if(Array.isArray(e)){for(var r=0,n=Array(e.length);r= 0x80 (not a basic code point)","invalid-input":"Invalid input"},z=Math.floor,L=String.fromCharCode,$=function(e){return String.fromCodePoint.apply(String,_(e))},M=function(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:36},V=function(e,r){return e+22+75*(e<26)-((0!=r)<<5)},k=function(e,r,n){var t=0;for(e=n?z(e/700):e>>1,e+=z(e/r);e>455;t+=36)e=z(e/35);return z(t+36*e/(e+38))},Z=function(e){var r=[],n=e.length,t=0,o=128,a=72,i=e.lastIndexOf("-");i<0&&(i=0);for(var u=0;u=128&&s("not-basic"),r.push(e.charCodeAt(u));for(var f=i>0?i+1:0;f=n&&s("invalid-input");var d=M(e.charCodeAt(f++));(d>=36||d>z((P-t)/p))&&s("overflow"),t+=d*p;var l=h<=a?1:h>=a+26?26:h-a;if(dz(P/m)&&s("overflow"),p*=m}var g=r.length+1;a=k(t-c,g,0==c),z(t/g)>P-o&&s("overflow"),o+=z(t/g),t%=g,r.splice(t++,0,o)}return String.fromCodePoint.apply(String,r)},G=function(e){var r=[];e=p(e);var n=e.length,t=128,o=0,a=72,i=!0,u=!1,f=undefined;try{for(var c,h=e[Symbol.iterator]();!(i=(c=h.next()).done);i=!0){var d=c.value;d<128&&r.push(L(d))}}catch(U){u=!0,f=U}finally{try{!i&&h["return"]&&h["return"]()}finally{if(u)throw f}}var l=r.length,m=l;for(l&&r.push("-");m=t&&Az((P-o)/D)&&s("overflow"),o+=(g-t)*D,t=g;var w=!0,b=!1,x=undefined;try{for(var O,N=e[Symbol.iterator]();!(w=(O=N.next()).done);w=!0){var I=O.value;if(IP&&s("overflow"),I==t){for(var F=o,R=36;;R+=36){var T=R<=a?1:R>=a+26?26:R-a;if(FA-Z\\x5E-\\x7E]",'[\\"\\\\]'),he=new RegExp(se,"g"),de=new RegExp(ce,"g"),le=new RegExp(r("[^]","[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]","[\\.]",'[\\"]',pe),"g"),me=new RegExp(r("[^]",se,"[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"),"g"),ge=me,ve={scheme:"mailto",parse:function(e,r){var n=e,t=n.to=n.path?n.path.split(","):[];if(n.path=undefined,n.query){for(var o=!1,a={},i=n.query.split("&"),u=0,s=i.length;u):string {\n\tif (sets.length > 1) {\n\t\tsets[0] = sets[0].slice(0, -1);\n\t\tconst xl = sets.length - 1;\n\t\tfor (let x = 1; x < xl; ++x) {\n\t\t\tsets[x] = sets[x].slice(1, -1);\n\t\t}\n\t\tsets[xl] = sets[xl].slice(1);\n\t\treturn sets.join('');\n\t} else {\n\t\treturn sets[0];\n\t}\n}\n\nexport function subexp(str:string):string {\n\treturn \"(?:\" + str + \")\";\n}\n\nexport function typeOf(o:any):string {\n\treturn o === undefined ? \"undefined\" : (o === null ? \"null\" : Object.prototype.toString.call(o).split(\" \").pop().split(\"]\").shift().toLowerCase());\n}\n\nexport function toUpperCase(str:string):string {\n\treturn str.toUpperCase();\n}\n\nexport function toArray(obj:any):Array {\n\treturn obj !== undefined && obj !== null ? (obj instanceof Array ? obj : (typeof obj.length !== \"number\" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj))) : [];\n}\n\n\nexport function assign(target: object, source: any): any {\n\tconst obj = target as any;\n\tif (source) {\n\t\tfor (const key in source) {\n\t\t\tobj[key] = source[key];\n\t\t}\n\t}\n\treturn obj;\n}","import { URIRegExps } from \"./uri\";\nimport { merge, subexp } from \"./util\";\n\nexport function buildExps(isIRI:boolean):URIRegExps {\n\tconst\n\t\tALPHA$$ = \"[A-Za-z]\",\n\t\tCR$ = \"[\\\\x0D]\",\n\t\tDIGIT$$ = \"[0-9]\",\n\t\tDQUOTE$$ = \"[\\\\x22]\",\n\t\tHEXDIG$$ = merge(DIGIT$$, \"[A-Fa-f]\"), //case-insensitive\n\t\tLF$$ = \"[\\\\x0A]\",\n\t\tSP$$ = \"[\\\\x20]\",\n\t\tPCT_ENCODED$ = subexp(subexp(\"%[EFef]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%[89A-Fa-f]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%\" + HEXDIG$$ + HEXDIG$$)), //expanded\n\t\tGEN_DELIMS$$ = \"[\\\\:\\\\/\\\\?\\\\#\\\\[\\\\]\\\\@]\",\n\t\tSUB_DELIMS$$ = \"[\\\\!\\\\$\\\\&\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,\\\\;\\\\=]\",\n\t\tRESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$),\n\t\tUCSCHAR$$ = isIRI ? \"[\\\\xA0-\\\\u200D\\\\u2010-\\\\u2029\\\\u202F-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF]\" : \"[]\", //subset, excludes bidi control characters\n\t\tIPRIVATE$$ = isIRI ? \"[\\\\uE000-\\\\uF8FF]\" : \"[]\", //subset\n\t\tUNRESERVED$$ = merge(ALPHA$$, DIGIT$$, \"[\\\\-\\\\.\\\\_\\\\~]\", UCSCHAR$$),\n\t\tSCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, \"[\\\\+\\\\-\\\\.]\") + \"*\"),\n\t\tUSERINFO$ = subexp(subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:]\")) + \"*\"),\n\t\tDEC_OCTET$ = subexp(subexp(\"25[0-5]\") + \"|\" + subexp(\"2[0-4]\" + DIGIT$$) + \"|\" + subexp(\"1\" + DIGIT$$ + DIGIT$$) + \"|\" + subexp(\"[1-9]\" + DIGIT$$) + \"|\" + DIGIT$$),\n\t\tDEC_OCTET_RELAXED$ = subexp(subexp(\"25[0-5]\") + \"|\" + subexp(\"2[0-4]\" + DIGIT$$) + \"|\" + subexp(\"1\" + DIGIT$$ + DIGIT$$) + \"|\" + subexp(\"0?[1-9]\" + DIGIT$$) + \"|0?0?\" + DIGIT$$), //relaxed parsing rules\n\t\tIPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + \"\\\\.\" + DEC_OCTET_RELAXED$ + \"\\\\.\" + DEC_OCTET_RELAXED$ + \"\\\\.\" + DEC_OCTET_RELAXED$),\n\t\tH16$ = subexp(HEXDIG$$ + \"{1,4}\"),\n\t\tLS32$ = subexp(subexp(H16$ + \"\\\\:\" + H16$) + \"|\" + IPV4ADDRESS$),\n\t\tIPV6ADDRESS1$ = subexp( subexp(H16$ + \"\\\\:\") + \"{6}\" + LS32$), // 6( h16 \":\" ) ls32\n\t\tIPV6ADDRESS2$ = subexp( \"\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{5}\" + LS32$), // \"::\" 5( h16 \":\" ) ls32\n\t\tIPV6ADDRESS3$ = subexp(subexp( H16$) + \"?\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{4}\" + LS32$), //[ h16 ] \"::\" 4( h16 \":\" ) ls32\n\t\tIPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,1}\" + H16$) + \"?\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{3}\" + LS32$), //[ *1( h16 \":\" ) h16 ] \"::\" 3( h16 \":\" ) ls32\n\t\tIPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,2}\" + H16$) + \"?\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{2}\" + LS32$), //[ *2( h16 \":\" ) h16 ] \"::\" 2( h16 \":\" ) ls32\n\t\tIPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,3}\" + H16$) + \"?\\\\:\\\\:\" + H16$ + \"\\\\:\" + LS32$), //[ *3( h16 \":\" ) h16 ] \"::\" h16 \":\" ls32\n\t\tIPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,4}\" + H16$) + \"?\\\\:\\\\:\" + LS32$), //[ *4( h16 \":\" ) h16 ] \"::\" ls32\n\t\tIPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,5}\" + H16$) + \"?\\\\:\\\\:\" + H16$ ), //[ *5( h16 \":\" ) h16 ] \"::\" h16\n\t\tIPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,6}\" + H16$) + \"?\\\\:\\\\:\" ), //[ *6( h16 \":\" ) h16 ] \"::\"\n\t\tIPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join(\"|\")),\n\t\tZONEID$ = subexp(subexp(UNRESERVED$$ + \"|\" + PCT_ENCODED$) + \"+\"), //RFC 6874\n\t\tIPV6ADDRZ$ = subexp(IPV6ADDRESS$ + \"\\\\%25\" + ZONEID$), //RFC 6874\n\t\tIPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp(\"\\\\%25|\\\\%(?!\" + HEXDIG$$ + \"{2})\") + ZONEID$), //RFC 6874, with relaxed parsing rules\n\t\tIPVFUTURE$ = subexp(\"[vV]\" + HEXDIG$$ + \"+\\\\.\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:]\") + \"+\"),\n\t\tIP_LITERAL$ = subexp(\"\\\\[\" + subexp(IPV6ADDRZ_RELAXED$ + \"|\" + IPV6ADDRESS$ + \"|\" + IPVFUTURE$) + \"\\\\]\"), //RFC 6874\n\t\tREG_NAME$ = subexp(subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$)) + \"*\"),\n\t\tHOST$ = subexp(IP_LITERAL$ + \"|\" + IPV4ADDRESS$ + \"(?!\" + REG_NAME$ + \")\" + \"|\" + REG_NAME$),\n\t\tPORT$ = subexp(DIGIT$$ + \"*\"),\n\t\tAUTHORITY$ = subexp(subexp(USERINFO$ + \"@\") + \"?\" + HOST$ + subexp(\"\\\\:\" + PORT$) + \"?\"),\n\t\tPCHAR$ = subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:\\\\@]\")),\n\t\tSEGMENT$ = subexp(PCHAR$ + \"*\"),\n\t\tSEGMENT_NZ$ = subexp(PCHAR$ + \"+\"),\n\t\tSEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\@]\")) + \"+\"),\n\t\tPATH_ABEMPTY$ = subexp(subexp(\"\\\\/\" + SEGMENT$) + \"*\"),\n\t\tPATH_ABSOLUTE$ = subexp(\"\\\\/\" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + \"?\"), //simplified\n\t\tPATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), //simplified\n\t\tPATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), //simplified\n\t\tPATH_EMPTY$ = \"(?!\" + PCHAR$ + \")\",\n\t\tPATH$ = subexp(PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_NOSCHEME$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$),\n\t\tQUERY$ = subexp(subexp(PCHAR$ + \"|\" + merge(\"[\\\\/\\\\?]\", IPRIVATE$$)) + \"*\"),\n\t\tFRAGMENT$ = subexp(subexp(PCHAR$ + \"|[\\\\/\\\\?]\") + \"*\"),\n\t\tHIER_PART$ = subexp(subexp(\"\\\\/\\\\/\" + AUTHORITY$ + PATH_ABEMPTY$) + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$),\n\t\tURI$ = subexp(SCHEME$ + \"\\\\:\" + HIER_PART$ + subexp(\"\\\\?\" + QUERY$) + \"?\" + subexp(\"\\\\#\" + FRAGMENT$) + \"?\"),\n\t\tRELATIVE_PART$ = subexp(subexp(\"\\\\/\\\\/\" + AUTHORITY$ + PATH_ABEMPTY$) + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_NOSCHEME$ + \"|\" + PATH_EMPTY$),\n\t\tRELATIVE$ = subexp(RELATIVE_PART$ + subexp(\"\\\\?\" + QUERY$) + \"?\" + subexp(\"\\\\#\" + FRAGMENT$) + \"?\"),\n\t\tURI_REFERENCE$ = subexp(URI$ + \"|\" + RELATIVE$),\n\t\tABSOLUTE_URI$ = subexp(SCHEME$ + \"\\\\:\" + HIER_PART$ + subexp(\"\\\\?\" + QUERY$) + \"?\"),\n\n\t\tGENERIC_REF$ = \"^(\" + SCHEME$ + \")\\\\:\" + subexp(subexp(\"\\\\/\\\\/(\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?)\") + \"?(\" + PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$ + \")\") + subexp(\"\\\\?(\" + QUERY$ + \")\") + \"?\" + subexp(\"\\\\#(\" + FRAGMENT$ + \")\") + \"?$\",\n\t\tRELATIVE_REF$ = \"^(){0}\" + subexp(subexp(\"\\\\/\\\\/(\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?)\") + \"?(\" + PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_NOSCHEME$ + \"|\" + PATH_EMPTY$ + \")\") + subexp(\"\\\\?(\" + QUERY$ + \")\") + \"?\" + subexp(\"\\\\#(\" + FRAGMENT$ + \")\") + \"?$\",\n\t\tABSOLUTE_REF$ = \"^(\" + SCHEME$ + \")\\\\:\" + subexp(subexp(\"\\\\/\\\\/(\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?)\") + \"?(\" + PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$ + \")\") + subexp(\"\\\\?(\" + QUERY$ + \")\") + \"?$\",\n\t\tSAMEDOC_REF$ = \"^\" + subexp(\"\\\\#(\" + FRAGMENT$ + \")\") + \"?$\",\n\t\tAUTHORITY_REF$ = \"^\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?$\"\n\t;\n\n\treturn {\n\t\tNOT_SCHEME : new RegExp(merge(\"[^]\", ALPHA$$, DIGIT$$, \"[\\\\+\\\\-\\\\.]\"), \"g\"),\n\t\tNOT_USERINFO : new RegExp(merge(\"[^\\\\%\\\\:]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_HOST : new RegExp(merge(\"[^\\\\%\\\\[\\\\]\\\\:]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_PATH : new RegExp(merge(\"[^\\\\%\\\\/\\\\:\\\\@]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_PATH_NOSCHEME : new RegExp(merge(\"[^\\\\%\\\\/\\\\@]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_QUERY : new RegExp(merge(\"[^\\\\%]\", UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:\\\\@\\\\/\\\\?]\", IPRIVATE$$), \"g\"),\n\t\tNOT_FRAGMENT : new RegExp(merge(\"[^\\\\%]\", UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:\\\\@\\\\/\\\\?]\"), \"g\"),\n\t\tESCAPE : new RegExp(merge(\"[^]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tUNRESERVED : new RegExp(UNRESERVED$$, \"g\"),\n\t\tOTHER_CHARS : new RegExp(merge(\"[^\\\\%]\", UNRESERVED$$, RESERVED$$), \"g\"),\n\t\tPCT_ENCODED : new RegExp(PCT_ENCODED$, \"g\"),\n\t\tIPV4ADDRESS : new RegExp(\"^(\" + IPV4ADDRESS$ + \")$\"),\n\t\tIPV6ADDRESS : new RegExp(\"^\\\\[?(\" + IPV6ADDRESS$ + \")\" + subexp(subexp(\"\\\\%25|\\\\%(?!\" + HEXDIG$$ + \"{2})\") + \"(\" + ZONEID$ + \")\") + \"?\\\\]?$\") //RFC 6874, with relaxed parsing rules\n\t};\n}\n\nexport default buildExps(false);\n","'use strict';\n\n/** Highest positive signed 32-bit float value */\nconst maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1\n\n/** Bootstring parameters */\nconst base = 36;\nconst tMin = 1;\nconst tMax = 26;\nconst skew = 38;\nconst damp = 700;\nconst initialBias = 72;\nconst initialN = 128; // 0x80\nconst delimiter = '-'; // '\\x2D'\n\n/** Regular expressions */\nconst regexPunycode = /^xn--/;\nconst regexNonASCII = /[^\\0-\\x7E]/; // non-ASCII chars\nconst regexSeparators = /[\\x2E\\u3002\\uFF0E\\uFF61]/g; // RFC 3490 separators\n\n/** Error messages */\nconst errors = {\n\t'overflow': 'Overflow: input needs wider integers to process',\n\t'not-basic': 'Illegal input >= 0x80 (not a basic code point)',\n\t'invalid-input': 'Invalid input'\n};\n\n/** Convenience shortcuts */\nconst baseMinusTMin = base - tMin;\nconst floor = Math.floor;\nconst stringFromCharCode = String.fromCharCode;\n\n/*--------------------------------------------------------------------------*/\n\n/**\n * A generic error utility function.\n * @private\n * @param {String} type The error type.\n * @returns {Error} Throws a `RangeError` with the applicable error message.\n */\nfunction error(type) {\n\tthrow new RangeError(errors[type]);\n}\n\n/**\n * A generic `Array#map` utility function.\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} callback The function that gets called for every array\n * item.\n * @returns {Array} A new array of values returned by the callback function.\n */\nfunction map(array, fn) {\n\tconst result = [];\n\tlet length = array.length;\n\twhile (length--) {\n\t\tresult[length] = fn(array[length]);\n\t}\n\treturn result;\n}\n\n/**\n * A simple `Array#map`-like wrapper to work with domain name strings or email\n * addresses.\n * @private\n * @param {String} domain The domain name or email address.\n * @param {Function} callback The function that gets called for every\n * character.\n * @returns {Array} A new string of characters returned by the callback\n * function.\n */\nfunction mapDomain(string, fn) {\n\tconst parts = string.split('@');\n\tlet result = '';\n\tif (parts.length > 1) {\n\t\t// In email addresses, only the domain name should be punycoded. Leave\n\t\t// the local part (i.e. everything up to `@`) intact.\n\t\tresult = parts[0] + '@';\n\t\tstring = parts[1];\n\t}\n\t// Avoid `split(regex)` for IE8 compatibility. See #17.\n\tstring = string.replace(regexSeparators, '\\x2E');\n\tconst labels = string.split('.');\n\tconst encoded = map(labels, fn).join('.');\n\treturn result + encoded;\n}\n\n/**\n * Creates an array containing the numeric code points of each Unicode\n * character in the string. While JavaScript uses UCS-2 internally,\n * this function will convert a pair of surrogate halves (each of which\n * UCS-2 exposes as separate characters) into a single code point,\n * matching UTF-16.\n * @see `punycode.ucs2.encode`\n * @see \n * @memberOf punycode.ucs2\n * @name decode\n * @param {String} string The Unicode input string (UCS-2).\n * @returns {Array} The new array of code points.\n */\nfunction ucs2decode(string) {\n\tconst output = [];\n\tlet counter = 0;\n\tconst length = string.length;\n\twhile (counter < length) {\n\t\tconst value = string.charCodeAt(counter++);\n\t\tif (value >= 0xD800 && value <= 0xDBFF && counter < length) {\n\t\t\t// It's a high surrogate, and there is a next character.\n\t\t\tconst extra = string.charCodeAt(counter++);\n\t\t\tif ((extra & 0xFC00) == 0xDC00) { // Low surrogate.\n\t\t\t\toutput.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);\n\t\t\t} else {\n\t\t\t\t// It's an unmatched surrogate; only append this code unit, in case the\n\t\t\t\t// next code unit is the high surrogate of a surrogate pair.\n\t\t\t\toutput.push(value);\n\t\t\t\tcounter--;\n\t\t\t}\n\t\t} else {\n\t\t\toutput.push(value);\n\t\t}\n\t}\n\treturn output;\n}\n\n/**\n * Creates a string based on an array of numeric code points.\n * @see `punycode.ucs2.decode`\n * @memberOf punycode.ucs2\n * @name encode\n * @param {Array} codePoints The array of numeric code points.\n * @returns {String} The new Unicode string (UCS-2).\n */\nconst ucs2encode = array => String.fromCodePoint(...array);\n\n/**\n * Converts a basic code point into a digit/integer.\n * @see `digitToBasic()`\n * @private\n * @param {Number} codePoint The basic numeric code point value.\n * @returns {Number} The numeric value of a basic code point (for use in\n * representing integers) in the range `0` to `base - 1`, or `base` if\n * the code point does not represent a value.\n */\nconst basicToDigit = function(codePoint) {\n\tif (codePoint - 0x30 < 0x0A) {\n\t\treturn codePoint - 0x16;\n\t}\n\tif (codePoint - 0x41 < 0x1A) {\n\t\treturn codePoint - 0x41;\n\t}\n\tif (codePoint - 0x61 < 0x1A) {\n\t\treturn codePoint - 0x61;\n\t}\n\treturn base;\n};\n\n/**\n * Converts a digit/integer into a basic code point.\n * @see `basicToDigit()`\n * @private\n * @param {Number} digit The numeric value of a basic code point.\n * @returns {Number} The basic code point whose value (when used for\n * representing integers) is `digit`, which needs to be in the range\n * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is\n * used; else, the lowercase form is used. The behavior is undefined\n * if `flag` is non-zero and `digit` has no uppercase form.\n */\nconst digitToBasic = function(digit, flag) {\n\t// 0..25 map to ASCII a..z or A..Z\n\t// 26..35 map to ASCII 0..9\n\treturn digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);\n};\n\n/**\n * Bias adaptation function as per section 3.4 of RFC 3492.\n * https://tools.ietf.org/html/rfc3492#section-3.4\n * @private\n */\nconst adapt = function(delta, numPoints, firstTime) {\n\tlet k = 0;\n\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\tdelta += floor(delta / numPoints);\n\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\tdelta = floor(delta / baseMinusTMin);\n\t}\n\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n};\n\n/**\n * Converts a Punycode string of ASCII-only symbols to a string of Unicode\n * symbols.\n * @memberOf punycode\n * @param {String} input The Punycode string of ASCII-only symbols.\n * @returns {String} The resulting string of Unicode symbols.\n */\nconst decode = function(input) {\n\t// Don't use UCS-2.\n\tconst output = [];\n\tconst inputLength = input.length;\n\tlet i = 0;\n\tlet n = initialN;\n\tlet bias = initialBias;\n\n\t// Handle the basic code points: let `basic` be the number of input code\n\t// points before the last delimiter, or `0` if there is none, then copy\n\t// the first basic code points to the output.\n\n\tlet basic = input.lastIndexOf(delimiter);\n\tif (basic < 0) {\n\t\tbasic = 0;\n\t}\n\n\tfor (let j = 0; j < basic; ++j) {\n\t\t// if it's not a basic code point\n\t\tif (input.charCodeAt(j) >= 0x80) {\n\t\t\terror('not-basic');\n\t\t}\n\t\toutput.push(input.charCodeAt(j));\n\t}\n\n\t// Main decoding loop: start just after the last delimiter if any basic code\n\t// points were copied; start at the beginning otherwise.\n\n\tfor (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {\n\n\t\t// `index` is the index of the next character to be consumed.\n\t\t// Decode a generalized variable-length integer into `delta`,\n\t\t// which gets added to `i`. The overflow checking is easier\n\t\t// if we increase `i` as we go, then subtract off its starting\n\t\t// value at the end to obtain `delta`.\n\t\tlet oldi = i;\n\t\tfor (let w = 1, k = base; /* no condition */; k += base) {\n\n\t\t\tif (index >= inputLength) {\n\t\t\t\terror('invalid-input');\n\t\t\t}\n\n\t\t\tconst digit = basicToDigit(input.charCodeAt(index++));\n\n\t\t\tif (digit >= base || digit > floor((maxInt - i) / w)) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\ti += digit * w;\n\t\t\tconst t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\n\t\t\tif (digit < t) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst baseMinusT = base - t;\n\t\t\tif (w > floor(maxInt / baseMinusT)) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\tw *= baseMinusT;\n\n\t\t}\n\n\t\tconst out = output.length + 1;\n\t\tbias = adapt(i - oldi, out, oldi == 0);\n\n\t\t// `i` was supposed to wrap around from `out` to `0`,\n\t\t// incrementing `n` each time, so we'll fix that now:\n\t\tif (floor(i / out) > maxInt - n) {\n\t\t\terror('overflow');\n\t\t}\n\n\t\tn += floor(i / out);\n\t\ti %= out;\n\n\t\t// Insert `n` at position `i` of the output.\n\t\toutput.splice(i++, 0, n);\n\n\t}\n\n\treturn String.fromCodePoint(...output);\n};\n\n/**\n * Converts a string of Unicode symbols (e.g. a domain name label) to a\n * Punycode string of ASCII-only symbols.\n * @memberOf punycode\n * @param {String} input The string of Unicode symbols.\n * @returns {String} The resulting Punycode string of ASCII-only symbols.\n */\nconst encode = function(input) {\n\tconst output = [];\n\n\t// Convert the input in UCS-2 to an array of Unicode code points.\n\tinput = ucs2decode(input);\n\n\t// Cache the length.\n\tlet inputLength = input.length;\n\n\t// Initialize the state.\n\tlet n = initialN;\n\tlet delta = 0;\n\tlet bias = initialBias;\n\n\t// Handle the basic code points.\n\tfor (const currentValue of input) {\n\t\tif (currentValue < 0x80) {\n\t\t\toutput.push(stringFromCharCode(currentValue));\n\t\t}\n\t}\n\n\tlet basicLength = output.length;\n\tlet handledCPCount = basicLength;\n\n\t// `handledCPCount` is the number of code points that have been handled;\n\t// `basicLength` is the number of basic code points.\n\n\t// Finish the basic string with a delimiter unless it's empty.\n\tif (basicLength) {\n\t\toutput.push(delimiter);\n\t}\n\n\t// Main encoding loop:\n\twhile (handledCPCount < inputLength) {\n\n\t\t// All non-basic code points < n have been handled already. Find the next\n\t\t// larger one:\n\t\tlet m = maxInt;\n\t\tfor (const currentValue of input) {\n\t\t\tif (currentValue >= n && currentValue < m) {\n\t\t\t\tm = currentValue;\n\t\t\t}\n\t\t}\n\n\t\t// Increase `delta` enough to advance the decoder's state to ,\n\t\t// but guard against overflow.\n\t\tconst handledCPCountPlusOne = handledCPCount + 1;\n\t\tif (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {\n\t\t\terror('overflow');\n\t\t}\n\n\t\tdelta += (m - n) * handledCPCountPlusOne;\n\t\tn = m;\n\n\t\tfor (const currentValue of input) {\n\t\t\tif (currentValue < n && ++delta > maxInt) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\t\t\tif (currentValue == n) {\n\t\t\t\t// Represent delta as a generalized variable-length integer.\n\t\t\t\tlet q = delta;\n\t\t\t\tfor (let k = base; /* no condition */; k += base) {\n\t\t\t\t\tconst t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\t\t\t\t\tif (q < t) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst qMinusT = q - t;\n\t\t\t\t\tconst baseMinusT = base - t;\n\t\t\t\t\toutput.push(\n\t\t\t\t\t\tstringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))\n\t\t\t\t\t);\n\t\t\t\t\tq = floor(qMinusT / baseMinusT);\n\t\t\t\t}\n\n\t\t\t\toutput.push(stringFromCharCode(digitToBasic(q, 0)));\n\t\t\t\tbias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);\n\t\t\t\tdelta = 0;\n\t\t\t\t++handledCPCount;\n\t\t\t}\n\t\t}\n\n\t\t++delta;\n\t\t++n;\n\n\t}\n\treturn output.join('');\n};\n\n/**\n * Converts a Punycode string representing a domain name or an email address\n * to Unicode. Only the Punycoded parts of the input will be converted, i.e.\n * it doesn't matter if you call it on a string that has already been\n * converted to Unicode.\n * @memberOf punycode\n * @param {String} input The Punycoded domain name or email address to\n * convert to Unicode.\n * @returns {String} The Unicode representation of the given Punycode\n * string.\n */\nconst toUnicode = function(input) {\n\treturn mapDomain(input, function(string) {\n\t\treturn regexPunycode.test(string)\n\t\t\t? decode(string.slice(4).toLowerCase())\n\t\t\t: string;\n\t});\n};\n\n/**\n * Converts a Unicode string representing a domain name or an email address to\n * Punycode. Only the non-ASCII parts of the domain name will be converted,\n * i.e. it doesn't matter if you call it with a domain that's already in\n * ASCII.\n * @memberOf punycode\n * @param {String} input The domain name or email address to convert, as a\n * Unicode string.\n * @returns {String} The Punycode representation of the given domain name or\n * email address.\n */\nconst toASCII = function(input) {\n\treturn mapDomain(input, function(string) {\n\t\treturn regexNonASCII.test(string)\n\t\t\t? 'xn--' + encode(string)\n\t\t\t: string;\n\t});\n};\n\n/*--------------------------------------------------------------------------*/\n\n/** Define the public API */\nconst punycode = {\n\t/**\n\t * A string representing the current Punycode.js version number.\n\t * @memberOf punycode\n\t * @type String\n\t */\n\t'version': '2.1.0',\n\t/**\n\t * An object of methods to convert from JavaScript's internal character\n\t * representation (UCS-2) to Unicode code points, and back.\n\t * @see \n\t * @memberOf punycode\n\t * @type Object\n\t */\n\t'ucs2': {\n\t\t'decode': ucs2decode,\n\t\t'encode': ucs2encode\n\t},\n\t'decode': decode,\n\t'encode': encode,\n\t'toASCII': toASCII,\n\t'toUnicode': toUnicode\n};\n\nexport default punycode;\n","/**\n * URI.js\n *\n * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript.\n * @author Gary Court\n * @see http://github.com/garycourt/uri-js\n */\n\n/**\n * Copyright 2011 Gary Court. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are\n * permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this list of\n * conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice, this list\n * of conditions and the following disclaimer in the documentation and/or other materials\n * provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are those of the\n * authors and should not be interpreted as representing official policies, either expressed\n * or implied, of Gary Court.\n */\n\nimport URI_PROTOCOL from \"./regexps-uri\";\nimport IRI_PROTOCOL from \"./regexps-iri\";\nimport punycode from \"punycode\";\nimport { toUpperCase, typeOf, assign } from \"./util\";\n\nexport interface URIComponents {\n\tscheme?:string;\n\tuserinfo?:string;\n\thost?:string;\n\tport?:number|string;\n\tpath?:string;\n\tquery?:string;\n\tfragment?:string;\n\treference?:string;\n\terror?:string;\n}\n\nexport interface URIOptions {\n\tscheme?:string;\n\treference?:string;\n\ttolerant?:boolean;\n\tabsolutePath?:boolean;\n\tiri?:boolean;\n\tunicodeSupport?:boolean;\n\tdomainHost?:boolean;\n}\n\nexport interface URISchemeHandler {\n\tscheme:string;\n\tparse(components:ParentComponents, options:Options):Components;\n\tserialize(components:Components, options:Options):ParentComponents;\n\tunicodeSupport?:boolean;\n\tdomainHost?:boolean;\n\tabsolutePath?:boolean;\n}\n\nexport interface URIRegExps {\n\tNOT_SCHEME : RegExp,\n\tNOT_USERINFO : RegExp,\n\tNOT_HOST : RegExp,\n\tNOT_PATH : RegExp,\n\tNOT_PATH_NOSCHEME : RegExp,\n\tNOT_QUERY : RegExp,\n\tNOT_FRAGMENT : RegExp,\n\tESCAPE : RegExp,\n\tUNRESERVED : RegExp,\n\tOTHER_CHARS : RegExp,\n\tPCT_ENCODED : RegExp,\n\tIPV4ADDRESS : RegExp,\n\tIPV6ADDRESS : RegExp,\n}\n\nexport const SCHEMES:{[scheme:string]:URISchemeHandler} = {};\n\nexport function pctEncChar(chr:string):string {\n\tconst c = chr.charCodeAt(0);\n\tlet e:string;\n\n\tif (c < 16) e = \"%0\" + c.toString(16).toUpperCase();\n\telse if (c < 128) e = \"%\" + c.toString(16).toUpperCase();\n\telse if (c < 2048) e = \"%\" + ((c >> 6) | 192).toString(16).toUpperCase() + \"%\" + ((c & 63) | 128).toString(16).toUpperCase();\n\telse e = \"%\" + ((c >> 12) | 224).toString(16).toUpperCase() + \"%\" + (((c >> 6) & 63) | 128).toString(16).toUpperCase() + \"%\" + ((c & 63) | 128).toString(16).toUpperCase();\n\n\treturn e;\n}\n\nexport function pctDecChars(str:string):string {\n\tlet newStr = \"\";\n\tlet i = 0;\n\tconst il = str.length;\n\n\twhile (i < il) {\n\t\tconst c = parseInt(str.substr(i + 1, 2), 16);\n\n\t\tif (c < 128) {\n\t\t\tnewStr += String.fromCharCode(c);\n\t\t\ti += 3;\n\t\t}\n\t\telse if (c >= 194 && c < 224) {\n\t\t\tif ((il - i) >= 6) {\n\t\t\t\tconst c2 = parseInt(str.substr(i + 4, 2), 16);\n\t\t\t\tnewStr += String.fromCharCode(((c & 31) << 6) | (c2 & 63));\n\t\t\t} else {\n\t\t\t\tnewStr += str.substr(i, 6);\n\t\t\t}\n\t\t\ti += 6;\n\t\t}\n\t\telse if (c >= 224) {\n\t\t\tif ((il - i) >= 9) {\n\t\t\t\tconst c2 = parseInt(str.substr(i + 4, 2), 16);\n\t\t\t\tconst c3 = parseInt(str.substr(i + 7, 2), 16);\n\t\t\t\tnewStr += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));\n\t\t\t} else {\n\t\t\t\tnewStr += str.substr(i, 9);\n\t\t\t}\n\t\t\ti += 9;\n\t\t}\n\t\telse {\n\t\t\tnewStr += str.substr(i, 3);\n\t\t\ti += 3;\n\t\t}\n\t}\n\n\treturn newStr;\n}\n\nfunction _normalizeComponentEncoding(components:URIComponents, protocol:URIRegExps) {\n\tfunction decodeUnreserved(str:string):string {\n\t\tconst decStr = pctDecChars(str);\n\t\treturn (!decStr.match(protocol.UNRESERVED) ? str : decStr);\n\t}\n\n\tif (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, \"\");\n\tif (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace((components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME), pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\n\treturn components;\n};\n\nfunction _stripLeadingZeros(str:string):string {\n\treturn str.replace(/^0*(.*)/, \"$1\") || \"0\";\n}\n\nfunction _normalizeIPv4(host:string, protocol:URIRegExps):string {\n\tconst matches = host.match(protocol.IPV4ADDRESS) || [];\n\tconst [, address] = matches;\n\t\n\tif (address) {\n\t\treturn address.split(\".\").map(_stripLeadingZeros).join(\".\");\n\t} else {\n\t\treturn host;\n\t}\n}\n\nfunction _normalizeIPv6(host:string, protocol:URIRegExps):string {\n\tconst matches = host.match(protocol.IPV6ADDRESS) || [];\n\tconst [, address, zone] = matches;\n\n\tif (address) {\n\t\tconst [last, first] = address.toLowerCase().split('::').reverse();\n\t\tconst firstFields = first ? first.split(\":\").map(_stripLeadingZeros) : [];\n\t\tconst lastFields = last.split(\":\").map(_stripLeadingZeros);\n\t\tconst isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]);\n\t\tconst fieldCount = isLastFieldIPv4Address ? 7 : 8;\n\t\tconst lastFieldsStart = lastFields.length - fieldCount;\n\t\tconst fields = Array(fieldCount);\n\n\t\tfor (let x = 0; x < fieldCount; ++x) {\n\t\t\tfields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || '';\n\t\t}\n\n\t\tif (isLastFieldIPv4Address) {\n\t\t\tfields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol);\n\t\t}\n\n\t\tconst allZeroFields = fields.reduce>((acc, field, index) => {\n\t\t\tif (!field || field === \"0\") {\n\t\t\t\tconst lastLongest = acc[acc.length - 1];\n\t\t\t\tif (lastLongest && lastLongest.index + lastLongest.length === index) {\n\t\t\t\t\tlastLongest.length++;\n\t\t\t\t} else {\n\t\t\t\t\tacc.push({ index, length : 1 });\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn acc;\n\t\t}, []);\n\n\t\tconst longestZeroFields = allZeroFields.sort((a, b) => b.length - a.length)[0];\n\n\t\tlet newHost:string;\n\t\tif (longestZeroFields && longestZeroFields.length > 1) {\n\t\t\tconst newFirst = fields.slice(0, longestZeroFields.index) ;\n\t\t\tconst newLast = fields.slice(longestZeroFields.index + longestZeroFields.length);\n\t\t\tnewHost = newFirst.join(\":\") + \"::\" + newLast.join(\":\");\n\t\t} else {\n\t\t\tnewHost = fields.join(\":\");\n\t\t}\n\n\t\tif (zone) {\n\t\t\tnewHost += \"%\" + zone;\n\t\t}\n\n\t\treturn newHost;\n\t} else {\n\t\treturn host;\n\t}\n}\n\nconst URI_PARSE = /^(?:([^:\\/?#]+):)?(?:\\/\\/((?:([^\\/?#@]*)@)?(\\[[^\\/?#\\]]+\\]|[^\\/?#:]*)(?:\\:(\\d*))?))?([^?#]*)(?:\\?([^#]*))?(?:#((?:.|\\n|\\r)*))?/i;\nconst NO_MATCH_IS_UNDEFINED = ((\"\").match(/(){0}/))[1] === undefined;\n\nexport function parse(uriString:string, options:URIOptions = {}):URIComponents {\n\tconst components:URIComponents = {};\n\tconst protocol = (options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL);\n\n\tif (options.reference === \"suffix\") uriString = (options.scheme ? options.scheme + \":\" : \"\") + \"//\" + uriString;\n\n\tconst matches = uriString.match(URI_PARSE);\n\n\tif (matches) {\n\t\tif (NO_MATCH_IS_UNDEFINED) {\n\t\t\t//store each component\n\t\t\tcomponents.scheme = matches[1];\n\t\t\tcomponents.userinfo = matches[3];\n\t\t\tcomponents.host = matches[4];\n\t\t\tcomponents.port = parseInt(matches[5], 10);\n\t\t\tcomponents.path = matches[6] || \"\";\n\t\t\tcomponents.query = matches[7];\n\t\t\tcomponents.fragment = matches[8];\n\n\t\t\t//fix port number\n\t\t\tif (isNaN(components.port)) {\n\t\t\t\tcomponents.port = matches[5];\n\t\t\t}\n\t\t} else { //IE FIX for improper RegExp matching\n\t\t\t//store each component\n\t\t\tcomponents.scheme = matches[1] || undefined;\n\t\t\tcomponents.userinfo = (uriString.indexOf(\"@\") !== -1 ? matches[3] : undefined);\n\t\t\tcomponents.host = (uriString.indexOf(\"//\") !== -1 ? matches[4] : undefined);\n\t\t\tcomponents.port = parseInt(matches[5], 10);\n\t\t\tcomponents.path = matches[6] || \"\";\n\t\t\tcomponents.query = (uriString.indexOf(\"?\") !== -1 ? matches[7] : undefined);\n\t\t\tcomponents.fragment = (uriString.indexOf(\"#\") !== -1 ? matches[8] : undefined);\n\n\t\t\t//fix port number\n\t\t\tif (isNaN(components.port)) {\n\t\t\t\tcomponents.port = (uriString.match(/\\/\\/(?:.|\\n)*\\:(?:\\/|\\?|\\#|$)/) ? matches[4] : undefined);\n\t\t\t}\n\t\t}\n\n\t\tif (components.host) {\n\t\t\t//normalize IP hosts\n\t\t\tcomponents.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol);\n\t\t}\n\n\t\t//determine reference type\n\t\tif (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) {\n\t\t\tcomponents.reference = \"same-document\";\n\t\t} else if (components.scheme === undefined) {\n\t\t\tcomponents.reference = \"relative\";\n\t\t} else if (components.fragment === undefined) {\n\t\t\tcomponents.reference = \"absolute\";\n\t\t} else {\n\t\t\tcomponents.reference = \"uri\";\n\t\t}\n\n\t\t//check for reference errors\n\t\tif (options.reference && options.reference !== \"suffix\" && options.reference !== components.reference) {\n\t\t\tcomponents.error = components.error || \"URI is not a \" + options.reference + \" reference.\";\n\t\t}\n\n\t\t//find scheme handler\n\t\tconst schemeHandler = SCHEMES[(options.scheme || components.scheme || \"\").toLowerCase()];\n\n\t\t//check if scheme can't handle IRIs\n\t\tif (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {\n\t\t\t//if host component is a domain name\n\t\t\tif (components.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost))) {\n\t\t\t\t//convert Unicode IDN -> ASCII IDN\n\t\t\t\ttry {\n\t\t\t\t\tcomponents.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());\n\t\t\t\t} catch (e) {\n\t\t\t\t\tcomponents.error = components.error || \"Host's domain name can not be converted to ASCII via punycode: \" + e;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//convert IRI -> URI\n\t\t\t_normalizeComponentEncoding(components, URI_PROTOCOL);\n\t\t} else {\n\t\t\t//normalize encodings\n\t\t\t_normalizeComponentEncoding(components, protocol);\n\t\t}\n\n\t\t//perform scheme specific parsing\n\t\tif (schemeHandler && schemeHandler.parse) {\n\t\t\tschemeHandler.parse(components, options);\n\t\t}\n\t} else {\n\t\tcomponents.error = components.error || \"URI can not be parsed.\";\n\t}\n\n\treturn components;\n};\n\nfunction _recomposeAuthority(components:URIComponents, options:URIOptions):string|undefined {\n\tconst protocol = (options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL);\n\tconst uriTokens:Array = [];\n\n\tif (components.userinfo !== undefined) {\n\t\turiTokens.push(components.userinfo);\n\t\turiTokens.push(\"@\");\n\t}\n\n\tif (components.host !== undefined) {\n\t\t//normalize IP hosts, add brackets and escape zone separator for IPv6\n\t\turiTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, (_, $1, $2) => \"[\" + $1 + ($2 ? \"%25\" + $2 : \"\") + \"]\"));\n\t}\n\n\tif (typeof components.port === \"number\" || typeof components.port === \"string\") {\n\t\turiTokens.push(\":\");\n\t\turiTokens.push(String(components.port));\n\t}\n\n\treturn uriTokens.length ? uriTokens.join(\"\") : undefined;\n};\n\nconst RDS1 = /^\\.\\.?\\//;\nconst RDS2 = /^\\/\\.(\\/|$)/;\nconst RDS3 = /^\\/\\.\\.(\\/|$)/;\nconst RDS4 = /^\\.\\.?$/;\nconst RDS5 = /^\\/?(?:.|\\n)*?(?=\\/|$)/;\n\nexport function removeDotSegments(input:string):string {\n\tconst output:Array = [];\n\n\twhile (input.length) {\n\t\tif (input.match(RDS1)) {\n\t\t\tinput = input.replace(RDS1, \"\");\n\t\t} else if (input.match(RDS2)) {\n\t\t\tinput = input.replace(RDS2, \"/\");\n\t\t} else if (input.match(RDS3)) {\n\t\t\tinput = input.replace(RDS3, \"/\");\n\t\t\toutput.pop();\n\t\t} else if (input === \".\" || input === \"..\") {\n\t\t\tinput = \"\";\n\t\t} else {\n\t\t\tconst im = input.match(RDS5);\n\t\t\tif (im) {\n\t\t\t\tconst s = im[0];\n\t\t\t\tinput = input.slice(s.length);\n\t\t\t\toutput.push(s);\n\t\t\t} else {\n\t\t\t\tthrow new Error(\"Unexpected dot segment condition\");\n\t\t\t}\n\t\t}\n\t}\n\n\treturn output.join(\"\");\n};\n\nexport function serialize(components:URIComponents, options:URIOptions = {}):string {\n\tconst protocol = (options.iri ? IRI_PROTOCOL : URI_PROTOCOL);\n\tconst uriTokens:Array = [];\n\n\t//find scheme handler\n\tconst schemeHandler = SCHEMES[(options.scheme || components.scheme || \"\").toLowerCase()];\n\n\t//perform scheme specific serialization\n\tif (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options);\n\n\tif (components.host) {\n\t\t//if host component is an IPv6 address\n\t\tif (protocol.IPV6ADDRESS.test(components.host)) {\n\t\t\t//TODO: normalize IPv6 address as per RFC 5952\n\t\t}\n\n\t\t//if host component is a domain name\n\t\telse if (options.domainHost || (schemeHandler && schemeHandler.domainHost)) {\n\t\t\t//convert IDN via punycode\n\t\t\ttry {\n\t\t\t\tcomponents.host = (!options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host));\n\t\t\t} catch (e) {\n\t\t\t\tcomponents.error = components.error || \"Host's domain name can not be converted to \" + (!options.iri ? \"ASCII\" : \"Unicode\") + \" via punycode: \" + e;\n\t\t\t}\n\t\t}\n\t}\n\n\t//normalize encoding\n\t_normalizeComponentEncoding(components, protocol);\n\n\tif (options.reference !== \"suffix\" && components.scheme) {\n\t\turiTokens.push(components.scheme);\n\t\turiTokens.push(\":\");\n\t}\n\n\tconst authority = _recomposeAuthority(components, options);\n\tif (authority !== undefined) {\n\t\tif (options.reference !== \"suffix\") {\n\t\t\turiTokens.push(\"//\");\n\t\t}\n\n\t\turiTokens.push(authority);\n\n\t\tif (components.path && components.path.charAt(0) !== \"/\") {\n\t\t\turiTokens.push(\"/\");\n\t\t}\n\t}\n\n\tif (components.path !== undefined) {\n\t\tlet s = components.path;\n\n\t\tif (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {\n\t\t\ts = removeDotSegments(s);\n\t\t}\n\n\t\tif (authority === undefined) {\n\t\t\ts = s.replace(/^\\/\\//, \"/%2F\"); //don't allow the path to start with \"//\"\n\t\t}\n\n\t\turiTokens.push(s);\n\t}\n\n\tif (components.query !== undefined) {\n\t\turiTokens.push(\"?\");\n\t\turiTokens.push(components.query);\n\t}\n\n\tif (components.fragment !== undefined) {\n\t\turiTokens.push(\"#\");\n\t\turiTokens.push(components.fragment);\n\t}\n\n\treturn uriTokens.join(\"\"); //merge tokens into a string\n};\n\nexport function resolveComponents(base:URIComponents, relative:URIComponents, options:URIOptions = {}, skipNormalization?:boolean):URIComponents {\n\tconst target:URIComponents = {};\n\n\tif (!skipNormalization) {\n\t\tbase = parse(serialize(base, options), options); //normalize base components\n\t\trelative = parse(serialize(relative, options), options); //normalize relative components\n\t}\n\toptions = options || {};\n\n\tif (!options.tolerant && relative.scheme) {\n\t\ttarget.scheme = relative.scheme;\n\t\t//target.authority = relative.authority;\n\t\ttarget.userinfo = relative.userinfo;\n\t\ttarget.host = relative.host;\n\t\ttarget.port = relative.port;\n\t\ttarget.path = removeDotSegments(relative.path || \"\");\n\t\ttarget.query = relative.query;\n\t} else {\n\t\tif (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {\n\t\t\t//target.authority = relative.authority;\n\t\t\ttarget.userinfo = relative.userinfo;\n\t\t\ttarget.host = relative.host;\n\t\t\ttarget.port = relative.port;\n\t\t\ttarget.path = removeDotSegments(relative.path || \"\");\n\t\t\ttarget.query = relative.query;\n\t\t} else {\n\t\t\tif (!relative.path) {\n\t\t\t\ttarget.path = base.path;\n\t\t\t\tif (relative.query !== undefined) {\n\t\t\t\t\ttarget.query = relative.query;\n\t\t\t\t} else {\n\t\t\t\t\ttarget.query = base.query;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (relative.path.charAt(0) === \"/\") {\n\t\t\t\t\ttarget.path = removeDotSegments(relative.path);\n\t\t\t\t} else {\n\t\t\t\t\tif ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {\n\t\t\t\t\t\ttarget.path = \"/\" + relative.path;\n\t\t\t\t\t} else if (!base.path) {\n\t\t\t\t\t\ttarget.path = relative.path;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttarget.path = base.path.slice(0, base.path.lastIndexOf(\"/\") + 1) + relative.path;\n\t\t\t\t\t}\n\t\t\t\t\ttarget.path = removeDotSegments(target.path);\n\t\t\t\t}\n\t\t\t\ttarget.query = relative.query;\n\t\t\t}\n\t\t\t//target.authority = base.authority;\n\t\t\ttarget.userinfo = base.userinfo;\n\t\t\ttarget.host = base.host;\n\t\t\ttarget.port = base.port;\n\t\t}\n\t\ttarget.scheme = base.scheme;\n\t}\n\n\ttarget.fragment = relative.fragment;\n\n\treturn target;\n};\n\nexport function resolve(baseURI:string, relativeURI:string, options?:URIOptions):string {\n\tconst schemelessOptions = assign({ scheme : 'null' }, options);\n\treturn serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);\n};\n\nexport function normalize(uri:string, options?:URIOptions):string;\nexport function normalize(uri:URIComponents, options?:URIOptions):URIComponents;\nexport function normalize(uri:any, options?:URIOptions):any {\n\tif (typeof uri === \"string\") {\n\t\turi = serialize(parse(uri, options), options);\n\t} else if (typeOf(uri) === \"object\") {\n\t\turi = parse(serialize(uri, options), options);\n\t}\n\n\treturn uri;\n};\n\nexport function equal(uriA:string, uriB:string, options?: URIOptions):boolean;\nexport function equal(uriA:URIComponents, uriB:URIComponents, options?:URIOptions):boolean;\nexport function equal(uriA:any, uriB:any, options?:URIOptions):boolean {\n\tif (typeof uriA === \"string\") {\n\t\turiA = serialize(parse(uriA, options), options);\n\t} else if (typeOf(uriA) === \"object\") {\n\t\turiA = serialize(uriA, options);\n\t}\n\n\tif (typeof uriB === \"string\") {\n\t\turiB = serialize(parse(uriB, options), options);\n\t} else if (typeOf(uriB) === \"object\") {\n\t\turiB = serialize(uriB, options);\n\t}\n\n\treturn uriA === uriB;\n};\n\nexport function escapeComponent(str:string, options?:URIOptions):string {\n\treturn str && str.toString().replace((!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE), pctEncChar);\n};\n\nexport function unescapeComponent(str:string, options?:URIOptions):string {\n\treturn str && str.toString().replace((!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED), pctDecChars);\n};\n","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\n\nexport interface WSComponents extends URIComponents {\n\tresourceName?: string;\n\tsecure?: boolean;\n}\n\nfunction isSecure(wsComponents:WSComponents):boolean {\n\treturn typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === \"wss\";\n}\n\n//RFC 6455\nconst handler:URISchemeHandler = {\n\tscheme : \"ws\",\n\n\tdomainHost : true,\n\n\tparse : function (components:URIComponents, options:URIOptions):WSComponents {\n\t\tconst wsComponents = components as WSComponents;\n\n\t\t//indicate if the secure flag is set\n\t\twsComponents.secure = isSecure(wsComponents);\n\n\t\t//construct resouce name\n\t\twsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : '');\n\t\twsComponents.path = undefined;\n\t\twsComponents.query = undefined;\n\n\t\treturn wsComponents;\n\t},\n\n\tserialize : function (wsComponents:WSComponents, options:URIOptions):URIComponents {\n\t\t//normalize the default port\n\t\tif (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === \"\") {\n\t\t\twsComponents.port = undefined;\n\t\t}\n\n\t\t//ensure scheme matches secure flag\n\t\tif (typeof wsComponents.secure === 'boolean') {\n\t\t\twsComponents.scheme = (wsComponents.secure ? 'wss' : 'ws');\n\t\t\twsComponents.secure = undefined;\n\t\t}\n\n\t\t//reconstruct path from resource name\n\t\tif (wsComponents.resourceName) {\n\t\t\tconst [path, query] = wsComponents.resourceName.split('?');\n\t\t\twsComponents.path = (path && path !== '/' ? path : undefined);\n\t\t\twsComponents.query = query;\n\t\t\twsComponents.resourceName = undefined;\n\t\t}\n\n\t\t//forbid fragment component\n\t\twsComponents.fragment = undefined;\n\n\t\treturn wsComponents;\n\t}\n};\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport { pctEncChar, pctDecChars, unescapeComponent } from \"../uri\";\nimport punycode from \"punycode\";\nimport { merge, subexp, toUpperCase, toArray } from \"../util\";\n\nexport interface MailtoHeaders {\n\t[hfname:string]:string\n}\n\nexport interface MailtoComponents extends URIComponents {\n\tto:Array,\n\theaders?:MailtoHeaders,\n\tsubject?:string,\n\tbody?:string\n}\n\nconst O:MailtoHeaders = {};\nconst isIRI = true;\n\n//RFC 3986\nconst UNRESERVED$$ = \"[A-Za-z0-9\\\\-\\\\.\\\\_\\\\~\" + (isIRI ? \"\\\\xA0-\\\\u200D\\\\u2010-\\\\u2029\\\\u202F-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF\" : \"\") + \"]\";\nconst HEXDIG$$ = \"[0-9A-Fa-f]\"; //case-insensitive\nconst PCT_ENCODED$ = subexp(subexp(\"%[EFef]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%[89A-Fa-f]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%\" + HEXDIG$$ + HEXDIG$$)); //expanded\n\n//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; =\n//const ATEXT$$ = \"[A-Za-z0-9\\\\!\\\\#\\\\$\\\\%\\\\&\\\\'\\\\*\\\\+\\\\-\\\\/\\\\=\\\\?\\\\^\\\\_\\\\`\\\\{\\\\|\\\\}\\\\~]\";\n//const WSP$$ = \"[\\\\x20\\\\x09]\";\n//const OBS_QTEXT$$ = \"[\\\\x01-\\\\x08\\\\x0B\\\\x0C\\\\x0E-\\\\x1F\\\\x7F]\"; //(%d1-8 / %d11-12 / %d14-31 / %d127)\n//const QTEXT$$ = merge(\"[\\\\x21\\\\x23-\\\\x5B\\\\x5D-\\\\x7E]\", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext\n//const VCHAR$$ = \"[\\\\x21-\\\\x7E]\";\n//const WSP$$ = \"[\\\\x20\\\\x09]\";\n//const OBS_QP$ = subexp(\"\\\\\\\\\" + merge(\"[\\\\x00\\\\x0D\\\\x0A]\", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext\n//const FWS$ = subexp(subexp(WSP$$ + \"*\" + \"\\\\x0D\\\\x0A\") + \"?\" + WSP$$ + \"+\");\n//const QUOTED_PAIR$ = subexp(subexp(\"\\\\\\\\\" + subexp(VCHAR$$ + \"|\" + WSP$$)) + \"|\" + OBS_QP$);\n//const QUOTED_STRING$ = subexp('\\\\\"' + subexp(FWS$ + \"?\" + QCONTENT$) + \"*\" + FWS$ + \"?\" + '\\\\\"');\nconst ATEXT$$ = \"[A-Za-z0-9\\\\!\\\\$\\\\%\\\\'\\\\*\\\\+\\\\-\\\\^\\\\_\\\\`\\\\{\\\\|\\\\}\\\\~]\";\nconst QTEXT$$ = \"[\\\\!\\\\$\\\\%\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,\\\\-\\\\.0-9\\\\<\\\\>A-Z\\\\x5E-\\\\x7E]\";\nconst VCHAR$$ = merge(QTEXT$$, \"[\\\\\\\"\\\\\\\\]\");\nconst DOT_ATOM_TEXT$ = subexp(ATEXT$$ + \"+\" + subexp(\"\\\\.\" + ATEXT$$ + \"+\") + \"*\");\nconst QUOTED_PAIR$ = subexp(\"\\\\\\\\\" + VCHAR$$);\nconst QCONTENT$ = subexp(QTEXT$$ + \"|\" + QUOTED_PAIR$);\nconst QUOTED_STRING$ = subexp('\\\\\"' + QCONTENT$ + \"*\" + '\\\\\"');\n\n//RFC 6068\nconst DTEXT_NO_OBS$$ = \"[\\\\x21-\\\\x5A\\\\x5E-\\\\x7E]\"; //%d33-90 / %d94-126\nconst SOME_DELIMS$$ = \"[\\\\!\\\\$\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,\\\\;\\\\:\\\\@]\";\nconst QCHAR$ = subexp(UNRESERVED$$ + \"|\" + PCT_ENCODED$ + \"|\" + SOME_DELIMS$$);\nconst DOMAIN$ = subexp(DOT_ATOM_TEXT$ + \"|\" + \"\\\\[\" + DTEXT_NO_OBS$$ + \"*\" + \"\\\\]\");\nconst LOCAL_PART$ = subexp(DOT_ATOM_TEXT$ + \"|\" + QUOTED_STRING$);\nconst ADDR_SPEC$ = subexp(LOCAL_PART$ + \"\\\\@\" + DOMAIN$);\nconst TO$ = subexp(ADDR_SPEC$ + subexp(\"\\\\,\" + ADDR_SPEC$) + \"*\");\nconst HFNAME$ = subexp(QCHAR$ + \"*\");\nconst HFVALUE$ = HFNAME$;\nconst HFIELD$ = subexp(HFNAME$ + \"\\\\=\" + HFVALUE$);\nconst HFIELDS2$ = subexp(HFIELD$ + subexp(\"\\\\&\" + HFIELD$) + \"*\");\nconst HFIELDS$ = subexp(\"\\\\?\" + HFIELDS2$);\nconst MAILTO_URI = new RegExp(\"^mailto\\\\:\" + TO$ + \"?\" + HFIELDS$ + \"?$\");\n\nconst UNRESERVED = new RegExp(UNRESERVED$$, \"g\");\nconst PCT_ENCODED = new RegExp(PCT_ENCODED$, \"g\");\nconst NOT_LOCAL_PART = new RegExp(merge(\"[^]\", ATEXT$$, \"[\\\\.]\", '[\\\\\"]', VCHAR$$), \"g\");\nconst NOT_DOMAIN = new RegExp(merge(\"[^]\", ATEXT$$, \"[\\\\.]\", \"[\\\\[]\", DTEXT_NO_OBS$$, \"[\\\\]]\"), \"g\");\nconst NOT_HFNAME = new RegExp(merge(\"[^]\", UNRESERVED$$, SOME_DELIMS$$), \"g\");\nconst NOT_HFVALUE = NOT_HFNAME;\nconst TO = new RegExp(\"^\" + TO$ + \"$\");\nconst HFIELDS = new RegExp(\"^\" + HFIELDS2$ + \"$\");\n\nfunction decodeUnreserved(str:string):string {\n\tconst decStr = pctDecChars(str);\n\treturn (!decStr.match(UNRESERVED) ? str : decStr);\n}\n\nconst handler:URISchemeHandler = {\n\tscheme : \"mailto\",\n\n\tparse : function (components:URIComponents, options:URIOptions):MailtoComponents {\n\t\tconst mailtoComponents = components as MailtoComponents;\n\t\tconst to = mailtoComponents.to = (mailtoComponents.path ? mailtoComponents.path.split(\",\") : []);\n\t\tmailtoComponents.path = undefined;\n\n\t\tif (mailtoComponents.query) {\n\t\t\tlet unknownHeaders = false\n\t\t\tconst headers:MailtoHeaders = {};\n\t\t\tconst hfields = mailtoComponents.query.split(\"&\");\n\n\t\t\tfor (let x = 0, xl = hfields.length; x < xl; ++x) {\n\t\t\t\tconst hfield = hfields[x].split(\"=\");\n\n\t\t\t\tswitch (hfield[0]) {\n\t\t\t\t\tcase \"to\":\n\t\t\t\t\t\tconst toAddrs = hfield[1].split(\",\");\n\t\t\t\t\t\tfor (let x = 0, xl = toAddrs.length; x < xl; ++x) {\n\t\t\t\t\t\t\tto.push(toAddrs[x]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"subject\":\n\t\t\t\t\t\tmailtoComponents.subject = unescapeComponent(hfield[1], options);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"body\":\n\t\t\t\t\t\tmailtoComponents.body = unescapeComponent(hfield[1], options);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tunknownHeaders = true;\n\t\t\t\t\t\theaders[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (unknownHeaders) mailtoComponents.headers = headers;\n\t\t}\n\n\t\tmailtoComponents.query = undefined;\n\n\t\tfor (let x = 0, xl = to.length; x < xl; ++x) {\n\t\t\tconst addr = to[x].split(\"@\");\n\n\t\t\taddr[0] = unescapeComponent(addr[0]);\n\n\t\t\tif (!options.unicodeSupport) {\n\t\t\t\t//convert Unicode IDN -> ASCII IDN\n\t\t\t\ttry {\n\t\t\t\t\taddr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase());\n\t\t\t\t} catch (e) {\n\t\t\t\t\tmailtoComponents.error = mailtoComponents.error || \"Email address's domain name can not be converted to ASCII via punycode: \" + e;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\taddr[1] = unescapeComponent(addr[1], options).toLowerCase();\n\t\t\t}\n\n\t\t\tto[x] = addr.join(\"@\");\n\t\t}\n\n\t\treturn mailtoComponents;\n\t},\n\n\tserialize : function (mailtoComponents:MailtoComponents, options:URIOptions):URIComponents {\n\t\tconst components = mailtoComponents as URIComponents;\n\t\tconst to = toArray(mailtoComponents.to);\n\t\tif (to) {\n\t\t\tfor (let x = 0, xl = to.length; x < xl; ++x) {\n\t\t\t\tconst toAddr = String(to[x]);\n\t\t\t\tconst atIdx = toAddr.lastIndexOf(\"@\");\n\t\t\t\tconst localPart = (toAddr.slice(0, atIdx)).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar);\n\t\t\t\tlet domain = toAddr.slice(atIdx + 1);\n\n\t\t\t\t//convert IDN via punycode\n\t\t\t\ttry {\n\t\t\t\t\tdomain = (!options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain));\n\t\t\t\t} catch (e) {\n\t\t\t\t\tcomponents.error = components.error || \"Email address's domain name can not be converted to \" + (!options.iri ? \"ASCII\" : \"Unicode\") + \" via punycode: \" + e;\n\t\t\t\t}\n\n\t\t\t\tto[x] = localPart + \"@\" + domain;\n\t\t\t}\n\n\t\t\tcomponents.path = to.join(\",\");\n\t\t}\n\n\t\tconst headers = mailtoComponents.headers = mailtoComponents.headers || {};\n\n\t\tif (mailtoComponents.subject) headers[\"subject\"] = mailtoComponents.subject;\n\t\tif (mailtoComponents.body) headers[\"body\"] = mailtoComponents.body;\n\n\t\tconst fields = [];\n\t\tfor (const name in headers) {\n\t\t\tif (headers[name] !== O[name]) {\n\t\t\t\tfields.push(\n\t\t\t\t\tname.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) +\n\t\t\t\t\t\"=\" +\n\t\t\t\t\theaders[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (fields.length) {\n\t\t\tcomponents.query = fields.join(\"&\");\n\t\t}\n\n\t\treturn components;\n\t}\n}\n\nexport default handler;","import { URIRegExps } from \"./uri\";\nimport { buildExps } from \"./regexps-uri\";\n\nexport default buildExps(true);\n","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\n\nconst handler:URISchemeHandler = {\n\tscheme : \"http\",\n\n\tdomainHost : true,\n\n\tparse : function (components:URIComponents, options:URIOptions):URIComponents {\n\t\t//report missing host\n\t\tif (!components.host) {\n\t\t\tcomponents.error = components.error || \"HTTP URIs must have a host.\";\n\t\t}\n\n\t\treturn components;\n\t},\n\n\tserialize : function (components:URIComponents, options:URIOptions):URIComponents {\n\t\tconst secure = String(components.scheme).toLowerCase() === \"https\";\n\n\t\t//normalize the default port\n\t\tif (components.port === (secure ? 443 : 80) || components.port === \"\") {\n\t\t\tcomponents.port = undefined;\n\t\t}\n\t\t\n\t\t//normalize the empty path\n\t\tif (!components.path) {\n\t\t\tcomponents.path = \"/\";\n\t\t}\n\n\t\t//NOTE: We do not parse query strings for HTTP URIs\n\t\t//as WWW Form Url Encoded query strings are part of the HTML4+ spec,\n\t\t//and not the HTTP spec.\n\n\t\treturn components;\n\t}\n};\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport http from \"./http\";\n\nconst handler:URISchemeHandler = {\n\tscheme : \"https\",\n\tdomainHost : http.domainHost,\n\tparse : http.parse,\n\tserialize : http.serialize\n}\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport ws from \"./ws\";\n\nconst handler:URISchemeHandler = {\n\tscheme : \"wss\",\n\tdomainHost : ws.domainHost,\n\tparse : ws.parse,\n\tserialize : ws.serialize\n}\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport { pctEncChar, SCHEMES } from \"../uri\";\n\nexport interface URNComponents extends URIComponents {\n\tnid?:string;\n\tnss?:string;\n}\n\nexport interface URNOptions extends URIOptions {\n\tnid?:string;\n}\n\nconst NID$ = \"(?:[0-9A-Za-z][0-9A-Za-z\\\\-]{1,31})\";\nconst PCT_ENCODED$ = \"(?:\\\\%[0-9A-Fa-f]{2})\";\nconst TRANS$$ = \"[0-9A-Za-z\\\\(\\\\)\\\\+\\\\,\\\\-\\\\.\\\\:\\\\=\\\\@\\\\;\\\\$\\\\_\\\\!\\\\*\\\\'\\\\/\\\\?\\\\#]\";\nconst NSS$ = \"(?:(?:\" + PCT_ENCODED$ + \"|\" + TRANS$$ + \")+)\";\nconst URN_SCHEME = new RegExp(\"^urn\\\\:(\" + NID$ + \")$\");\nconst URN_PATH = new RegExp(\"^(\" + NID$ + \")\\\\:(\" + NSS$ + \")$\");\nconst URN_PARSE = /^([^\\:]+)\\:(.*)/;\nconst URN_EXCLUDED = /[\\x00-\\x20\\\\\\\"\\&\\<\\>\\[\\]\\^\\`\\{\\|\\}\\~\\x7F-\\xFF]/g;\n\n//RFC 2141\nconst handler:URISchemeHandler = {\n\tscheme : \"urn\",\n\n\tparse : function (components:URIComponents, options:URNOptions):URNComponents {\n\t\tconst matches = components.path && components.path.match(URN_PARSE);\n\t\tlet urnComponents = components as URNComponents;\n\n\t\tif (matches) {\n\t\t\tconst scheme = options.scheme || urnComponents.scheme || \"urn\";\n\t\t\tconst nid = matches[1].toLowerCase();\n\t\t\tconst nss = matches[2];\n\t\t\tconst urnScheme = `${scheme}:${options.nid || nid}`;\n\t\t\tconst schemeHandler = SCHEMES[urnScheme];\n\n\t\t\turnComponents.nid = nid;\n\t\t\turnComponents.nss = nss;\n\t\t\turnComponents.path = undefined;\n\n\t\t\tif (schemeHandler) {\n\t\t\t\turnComponents = schemeHandler.parse(urnComponents, options) as URNComponents;\n\t\t\t}\n\t\t} else {\n\t\t\turnComponents.error = urnComponents.error || \"URN can not be parsed.\";\n\t\t}\n\n\t\treturn urnComponents;\n\t},\n\n\tserialize : function (urnComponents:URNComponents, options:URNOptions):URIComponents {\n\t\tconst scheme = options.scheme || urnComponents.scheme || \"urn\";\n\t\tconst nid = urnComponents.nid;\n\t\tconst urnScheme = `${scheme}:${options.nid || nid}`;\n\t\tconst schemeHandler = SCHEMES[urnScheme];\n\n\t\tif (schemeHandler) {\n\t\t\turnComponents = schemeHandler.serialize(urnComponents, options) as URNComponents;\n\t\t}\n\n\t\tconst uriComponents = urnComponents as URIComponents;\n\t\tconst nss = urnComponents.nss;\n\t\turiComponents.path = `${nid || options.nid}:${nss}`;\n\n\t\treturn uriComponents;\n\t},\n};\n\nexport default handler;","import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport { URNComponents } from \"./urn\";\nimport { SCHEMES } from \"../uri\";\n\nexport interface UUIDComponents extends URNComponents {\n\tuuid?: string;\n}\n\nconst UUID = /^[0-9A-Fa-f]{8}(?:\\-[0-9A-Fa-f]{4}){3}\\-[0-9A-Fa-f]{12}$/;\nconst UUID_PARSE = /^[0-9A-Fa-f\\-]{36}/;\n\n//RFC 4122\nconst handler:URISchemeHandler = {\n\tscheme : \"urn:uuid\",\n\n\tparse : function (urnComponents:URNComponents, options:URIOptions):UUIDComponents {\n\t\tconst uuidComponents = urnComponents as UUIDComponents;\n\t\tuuidComponents.uuid = uuidComponents.nss;\n\t\tuuidComponents.nss = undefined;\n\n\t\tif (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) {\n\t\t\tuuidComponents.error = uuidComponents.error || \"UUID is not valid.\";\n\t\t}\n\n\t\treturn uuidComponents;\n\t},\n\n\tserialize : function (uuidComponents:UUIDComponents, options:URIOptions):URNComponents {\n\t\tconst urnComponents = uuidComponents as URNComponents;\n\t\t//normalize UUID\n\t\turnComponents.nss = (uuidComponents.uuid || \"\").toLowerCase();\n\t\treturn urnComponents;\n\t},\n};\n\nexport default handler;","import { SCHEMES } from \"./uri\";\n\nimport http from \"./schemes/http\";\nSCHEMES[http.scheme] = http;\n\nimport https from \"./schemes/https\";\nSCHEMES[https.scheme] = https;\n\nimport ws from \"./schemes/ws\";\nSCHEMES[ws.scheme] = ws;\n\nimport wss from \"./schemes/wss\";\nSCHEMES[wss.scheme] = wss;\n\nimport mailto from \"./schemes/mailto\";\nSCHEMES[mailto.scheme] = mailto;\n\nimport urn from \"./schemes/urn\";\nSCHEMES[urn.scheme] = urn;\n\nimport uuid from \"./schemes/urn-uuid\";\nSCHEMES[uuid.scheme] = uuid;\n\nexport * from \"./uri\";\n"]} \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/index.d.ts b/node_modules/uri-js/dist/esnext/index.d.ts new file mode 100755 index 0000000..f6be760 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/index.d.ts @@ -0,0 +1 @@ +export * from "./uri"; diff --git a/node_modules/uri-js/dist/esnext/index.js b/node_modules/uri-js/dist/esnext/index.js new file mode 100755 index 0000000..e3531b5 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/index.js @@ -0,0 +1,17 @@ +import { SCHEMES } from "./uri"; +import http from "./schemes/http"; +SCHEMES[http.scheme] = http; +import https from "./schemes/https"; +SCHEMES[https.scheme] = https; +import ws from "./schemes/ws"; +SCHEMES[ws.scheme] = ws; +import wss from "./schemes/wss"; +SCHEMES[wss.scheme] = wss; +import mailto from "./schemes/mailto"; +SCHEMES[mailto.scheme] = mailto; +import urn from "./schemes/urn"; +SCHEMES[urn.scheme] = urn; +import uuid from "./schemes/urn-uuid"; +SCHEMES[uuid.scheme] = uuid; +export * from "./uri"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/index.js.map b/node_modules/uri-js/dist/esnext/index.js.map new file mode 100755 index 0000000..0971f6e --- /dev/null +++ b/node_modules/uri-js/dist/esnext/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAEhC,OAAO,IAAI,MAAM,gBAAgB,CAAC;AAClC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;AAE5B,OAAO,KAAK,MAAM,iBAAiB,CAAC;AACpC,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC;AAE9B,OAAO,EAAE,MAAM,cAAc,CAAC;AAC9B,OAAO,CAAC,EAAE,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC;AAExB,OAAO,GAAG,MAAM,eAAe,CAAC;AAChC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,GAAG,CAAC;AAE1B,OAAO,MAAM,MAAM,kBAAkB,CAAC;AACtC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;AAEhC,OAAO,GAAG,MAAM,eAAe,CAAC;AAChC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,GAAG,CAAC;AAE1B,OAAO,IAAI,MAAM,oBAAoB,CAAC;AACtC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;AAE5B,cAAc,OAAO,CAAC"} \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/regexps-iri.d.ts b/node_modules/uri-js/dist/esnext/regexps-iri.d.ts new file mode 100755 index 0000000..c91cdac --- /dev/null +++ b/node_modules/uri-js/dist/esnext/regexps-iri.d.ts @@ -0,0 +1,3 @@ +import { URIRegExps } from "./uri"; +declare const _default: URIRegExps; +export default _default; diff --git a/node_modules/uri-js/dist/esnext/regexps-iri.js b/node_modules/uri-js/dist/esnext/regexps-iri.js new file mode 100755 index 0000000..34e7de9 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/regexps-iri.js @@ -0,0 +1,3 @@ +import { buildExps } from "./regexps-uri"; +export default buildExps(true); +//# sourceMappingURL=regexps-iri.js.map \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/regexps-iri.js.map b/node_modules/uri-js/dist/esnext/regexps-iri.js.map new file mode 100755 index 0000000..2269c58 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/regexps-iri.js.map @@ -0,0 +1 @@ +{"version":3,"file":"regexps-iri.js","sourceRoot":"","sources":["../../src/regexps-iri.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE1C,eAAe,SAAS,CAAC,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/regexps-uri.d.ts b/node_modules/uri-js/dist/esnext/regexps-uri.d.ts new file mode 100755 index 0000000..6096bda --- /dev/null +++ b/node_modules/uri-js/dist/esnext/regexps-uri.d.ts @@ -0,0 +1,4 @@ +import { URIRegExps } from "./uri"; +export declare function buildExps(isIRI: boolean): URIRegExps; +declare const _default: URIRegExps; +export default _default; diff --git a/node_modules/uri-js/dist/esnext/regexps-uri.js b/node_modules/uri-js/dist/esnext/regexps-uri.js new file mode 100755 index 0000000..1cc659f --- /dev/null +++ b/node_modules/uri-js/dist/esnext/regexps-uri.js @@ -0,0 +1,42 @@ +import { merge, subexp } from "./util"; +export function buildExps(isIRI) { + const ALPHA$$ = "[A-Za-z]", CR$ = "[\\x0D]", DIGIT$$ = "[0-9]", DQUOTE$$ = "[\\x22]", HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"), //case-insensitive + LF$$ = "[\\x0A]", SP$$ = "[\\x20]", PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)), //expanded + GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", //subset, excludes bidi control characters + IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", //subset + UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$), SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"), USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"), DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$), DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), //relaxed parsing rules + IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), H16$ = subexp(HEXDIG$$ + "{1,4}"), LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), // 6( h16 ":" ) ls32 + IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), // "::" 5( h16 ":" ) ls32 + IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), //[ h16 ] "::" 4( h16 ":" ) ls32 + IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), //[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), //[ *4( h16 ":" ) h16 ] "::" ls32 + IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), //[ *5( h16 ":" ) h16 ] "::" h16 + IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), //[ *6( h16 ":" ) h16 ] "::" + IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"), //RFC 6874 + IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$), //RFC 6874 + IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$), //RFC 6874, with relaxed parsing rules + IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"), IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"), //RFC 6874 + REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"), HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")" + "|" + REG_NAME$), PORT$ = subexp(DIGIT$$ + "*"), AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"), PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")), SEGMENT$ = subexp(PCHAR$ + "*"), SEGMENT_NZ$ = subexp(PCHAR$ + "+"), SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"), PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"), PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"), //simplified + PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), //simplified + PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), //simplified + PATH_EMPTY$ = "(?!" + PCHAR$ + ")", PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"), FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"), HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$), RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$), ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"), GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$", SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$"; + return { + NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"), + NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"), + NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"), + ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"), + UNRESERVED: new RegExp(UNRESERVED$$, "g"), + OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"), + PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"), + IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"), + IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules + }; +} +export default buildExps(false); +//# sourceMappingURL=regexps-uri.js.map \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/regexps-uri.js.map b/node_modules/uri-js/dist/esnext/regexps-uri.js.map new file mode 100755 index 0000000..cb028b8 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/regexps-uri.js.map @@ -0,0 +1 @@ +{"version":3,"file":"regexps-uri.js","sourceRoot":"","sources":["../../src/regexps-uri.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEvC,MAAM,oBAAoB,KAAa;IACtC,MACC,OAAO,GAAG,UAAU,EACpB,GAAG,GAAG,SAAS,EACf,OAAO,GAAG,OAAO,EACjB,QAAQ,GAAG,SAAS,EACpB,QAAQ,GAAG,KAAK,CAAC,OAAO,EAAE,UAAU,CAAC,EAAG,kBAAkB;IAC1D,IAAI,GAAG,SAAS,EAChB,IAAI,GAAG,SAAS,EAChB,YAAY,GAAG,MAAM,CAAC,MAAM,CAAC,SAAS,GAAG,QAAQ,GAAG,GAAG,GAAG,QAAQ,GAAG,QAAQ,GAAG,GAAG,GAAG,QAAQ,GAAG,QAAQ,CAAC,GAAG,GAAG,GAAG,MAAM,CAAC,aAAa,GAAG,QAAQ,GAAG,GAAG,GAAG,QAAQ,GAAG,QAAQ,CAAC,GAAG,GAAG,GAAG,MAAM,CAAC,GAAG,GAAG,QAAQ,GAAG,QAAQ,CAAC,CAAC,EAAG,UAAU;IACvO,YAAY,GAAG,yBAAyB,EACxC,YAAY,GAAG,qCAAqC,EACpD,UAAU,GAAG,KAAK,CAAC,YAAY,EAAE,YAAY,CAAC,EAC9C,SAAS,GAAG,KAAK,CAAC,CAAC,CAAC,6EAA6E,CAAC,CAAC,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AAE,GAAG,CAAC;QAC3C,WAAW,EAAG,IAAI,MAAM,CAAC,IAAI,GAAG,YAAY,GAAG,IAAI,CAAC;QACpD,WAAW,EAAG,IAAI,MAAM,CAAC,QAAQ,GAAG,YAAY,GAAG,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,cAAc,GAAG,QAAQ,GAAG,MAAM,CAAC,GAAG,GAAG,GAAG,OAAO,GAAG,GAAG,CAAC,GAAG,QAAQ,CAAC,CAAE,sCAAsC;KACrL,CAAC;AACH,CAAC;AAED,eAAe,SAAS,CAAC,KAAK,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/schemes/http.d.ts b/node_modules/uri-js/dist/esnext/schemes/http.d.ts new file mode 100755 index 0000000..fe5b2f3 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/http.d.ts @@ -0,0 +1,3 @@ +import { URISchemeHandler } from "../uri"; +declare const handler: URISchemeHandler; +export default handler; diff --git a/node_modules/uri-js/dist/esnext/schemes/http.js b/node_modules/uri-js/dist/esnext/schemes/http.js new file mode 100755 index 0000000..6abf0fe --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/http.js @@ -0,0 +1,28 @@ +const handler = { + scheme: "http", + domainHost: true, + parse: function (components, options) { + //report missing host + if (!components.host) { + components.error = components.error || "HTTP URIs must have a host."; + } + return components; + }, + serialize: function (components, options) { + const secure = String(components.scheme).toLowerCase() === "https"; + //normalize the default port + if (components.port === (secure ? 443 : 80) || components.port === "") { + components.port = undefined; + } + //normalize the empty path + if (!components.path) { + components.path = "/"; + } + //NOTE: We do not parse query strings for HTTP URIs + //as WWW Form Url Encoded query strings are part of the HTML4+ spec, + //and not the HTTP spec. + return components; + } +}; +export default handler; +//# sourceMappingURL=http.js.map \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/schemes/http.js.map b/node_modules/uri-js/dist/esnext/schemes/http.js.map new file mode 100755 index 0000000..8211897 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/http.js.map @@ -0,0 +1 @@ +{"version":3,"file":"http.js","sourceRoot":"","sources":["../../../src/schemes/http.ts"],"names":[],"mappings":"AAEA,MAAM,OAAO,GAAoB;IAChC,MAAM,EAAG,MAAM;IAEf,UAAU,EAAG,IAAI;IAEjB,KAAK,EAAG,UAAU,UAAwB,EAAE,OAAkB;QAC7D,qBAAqB;QACrB,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE;YACrB,UAAU,CAAC,KAAK,GAAG,UAAU,CAAC,KAAK,IAAI,6BAA6B,CAAC;SACrE;QAED,OAAO,UAAU,CAAC;IACnB,CAAC;IAED,SAAS,EAAG,UAAU,UAAwB,EAAE,OAAkB;QACjE,MAAM,MAAM,GAAG,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,KAAK,OAAO,CAAC;QAEnE,4BAA4B;QAC5B,IAAI,UAAU,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,UAAU,CAAC,IAAI,KAAK,EAAE,EAAE;YACtE,UAAU,CAAC,IAAI,GAAG,SAAS,CAAC;SAC5B;QAED,0BAA0B;QAC1B,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE;YACrB,UAAU,CAAC,IAAI,GAAG,GAAG,CAAC;SACtB;QAED,mDAAmD;QACnD,oEAAoE;QACpE,wBAAwB;QAExB,OAAO,UAAU,CAAC;IACnB,CAAC;CACD,CAAC;AAEF,eAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/schemes/https.d.ts b/node_modules/uri-js/dist/esnext/schemes/https.d.ts new file mode 100755 index 0000000..fe5b2f3 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/https.d.ts @@ -0,0 +1,3 @@ +import { URISchemeHandler } from "../uri"; +declare const handler: URISchemeHandler; +export default handler; diff --git a/node_modules/uri-js/dist/esnext/schemes/https.js b/node_modules/uri-js/dist/esnext/schemes/https.js new file mode 100755 index 0000000..ec4b6e7 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/https.js @@ -0,0 +1,9 @@ +import http from "./http"; +const handler = { + scheme: "https", + domainHost: http.domainHost, + parse: http.parse, + serialize: http.serialize +}; +export default handler; +//# sourceMappingURL=https.js.map \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/schemes/https.js.map b/node_modules/uri-js/dist/esnext/schemes/https.js.map new file mode 100755 index 0000000..385b8ef --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/https.js.map @@ -0,0 +1 @@ +{"version":3,"file":"https.js","sourceRoot":"","sources":["../../../src/schemes/https.ts"],"names":[],"mappings":"AACA,OAAO,IAAI,MAAM,QAAQ,CAAC;AAE1B,MAAM,OAAO,GAAoB;IAChC,MAAM,EAAG,OAAO;IAChB,UAAU,EAAG,IAAI,CAAC,UAAU;IAC5B,KAAK,EAAG,IAAI,CAAC,KAAK;IAClB,SAAS,EAAG,IAAI,CAAC,SAAS;CAC1B,CAAA;AAED,eAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/schemes/mailto.d.ts b/node_modules/uri-js/dist/esnext/schemes/mailto.d.ts new file mode 100755 index 0000000..e2aefc2 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/mailto.d.ts @@ -0,0 +1,12 @@ +import { URISchemeHandler, URIComponents } from "../uri"; +export interface MailtoHeaders { + [hfname: string]: string; +} +export interface MailtoComponents extends URIComponents { + to: Array; + headers?: MailtoHeaders; + subject?: string; + body?: string; +} +declare const handler: URISchemeHandler; +export default handler; diff --git a/node_modules/uri-js/dist/esnext/schemes/mailto.js b/node_modules/uri-js/dist/esnext/schemes/mailto.js new file mode 100755 index 0000000..2553713 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/mailto.js @@ -0,0 +1,148 @@ +import { pctEncChar, pctDecChars, unescapeComponent } from "../uri"; +import punycode from "punycode"; +import { merge, subexp, toUpperCase, toArray } from "../util"; +const O = {}; +const isIRI = true; +//RFC 3986 +const UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]"; +const HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive +const PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded +//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; = +//const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]"; +//const WSP$$ = "[\\x20\\x09]"; +//const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127) +//const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext +//const VCHAR$$ = "[\\x21-\\x7E]"; +//const WSP$$ = "[\\x20\\x09]"; +//const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext +//const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+"); +//const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$); +//const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"'); +const ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]"; +const QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]"; +const VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]"); +const DOT_ATOM_TEXT$ = subexp(ATEXT$$ + "+" + subexp("\\." + ATEXT$$ + "+") + "*"); +const QUOTED_PAIR$ = subexp("\\\\" + VCHAR$$); +const QCONTENT$ = subexp(QTEXT$$ + "|" + QUOTED_PAIR$); +const QUOTED_STRING$ = subexp('\\"' + QCONTENT$ + "*" + '\\"'); +//RFC 6068 +const DTEXT_NO_OBS$$ = "[\\x21-\\x5A\\x5E-\\x7E]"; //%d33-90 / %d94-126 +const SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"; +const QCHAR$ = subexp(UNRESERVED$$ + "|" + PCT_ENCODED$ + "|" + SOME_DELIMS$$); +const DOMAIN$ = subexp(DOT_ATOM_TEXT$ + "|" + "\\[" + DTEXT_NO_OBS$$ + "*" + "\\]"); +const LOCAL_PART$ = subexp(DOT_ATOM_TEXT$ + "|" + QUOTED_STRING$); +const ADDR_SPEC$ = subexp(LOCAL_PART$ + "\\@" + DOMAIN$); +const TO$ = subexp(ADDR_SPEC$ + subexp("\\," + ADDR_SPEC$) + "*"); +const HFNAME$ = subexp(QCHAR$ + "*"); +const HFVALUE$ = HFNAME$; +const HFIELD$ = subexp(HFNAME$ + "\\=" + HFVALUE$); +const HFIELDS2$ = subexp(HFIELD$ + subexp("\\&" + HFIELD$) + "*"); +const HFIELDS$ = subexp("\\?" + HFIELDS2$); +const MAILTO_URI = new RegExp("^mailto\\:" + TO$ + "?" + HFIELDS$ + "?$"); +const UNRESERVED = new RegExp(UNRESERVED$$, "g"); +const PCT_ENCODED = new RegExp(PCT_ENCODED$, "g"); +const NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g"); +const NOT_DOMAIN = new RegExp(merge("[^]", ATEXT$$, "[\\.]", "[\\[]", DTEXT_NO_OBS$$, "[\\]]"), "g"); +const NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g"); +const NOT_HFVALUE = NOT_HFNAME; +const TO = new RegExp("^" + TO$ + "$"); +const HFIELDS = new RegExp("^" + HFIELDS2$ + "$"); +function decodeUnreserved(str) { + const decStr = pctDecChars(str); + return (!decStr.match(UNRESERVED) ? str : decStr); +} +const handler = { + scheme: "mailto", + parse: function (components, options) { + const mailtoComponents = components; + const to = mailtoComponents.to = (mailtoComponents.path ? mailtoComponents.path.split(",") : []); + mailtoComponents.path = undefined; + if (mailtoComponents.query) { + let unknownHeaders = false; + const headers = {}; + const hfields = mailtoComponents.query.split("&"); + for (let x = 0, xl = hfields.length; x < xl; ++x) { + const hfield = hfields[x].split("="); + switch (hfield[0]) { + case "to": + const toAddrs = hfield[1].split(","); + for (let x = 0, xl = toAddrs.length; x < xl; ++x) { + to.push(toAddrs[x]); + } + break; + case "subject": + mailtoComponents.subject = unescapeComponent(hfield[1], options); + break; + case "body": + mailtoComponents.body = unescapeComponent(hfield[1], options); + break; + default: + unknownHeaders = true; + headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options); + break; + } + } + if (unknownHeaders) + mailtoComponents.headers = headers; + } + mailtoComponents.query = undefined; + for (let x = 0, xl = to.length; x < xl; ++x) { + const addr = to[x].split("@"); + addr[0] = unescapeComponent(addr[0]); + if (!options.unicodeSupport) { + //convert Unicode IDN -> ASCII IDN + try { + addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase()); + } + catch (e) { + mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e; + } + } + else { + addr[1] = unescapeComponent(addr[1], options).toLowerCase(); + } + to[x] = addr.join("@"); + } + return mailtoComponents; + }, + serialize: function (mailtoComponents, options) { + const components = mailtoComponents; + const to = toArray(mailtoComponents.to); + if (to) { + for (let x = 0, xl = to.length; x < xl; ++x) { + const toAddr = String(to[x]); + const atIdx = toAddr.lastIndexOf("@"); + const localPart = (toAddr.slice(0, atIdx)).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar); + let domain = toAddr.slice(atIdx + 1); + //convert IDN via punycode + try { + domain = (!options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain)); + } + catch (e) { + components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + to[x] = localPart + "@" + domain; + } + components.path = to.join(","); + } + const headers = mailtoComponents.headers = mailtoComponents.headers || {}; + if (mailtoComponents.subject) + headers["subject"] = mailtoComponents.subject; + if (mailtoComponents.body) + headers["body"] = mailtoComponents.body; + const fields = []; + for (const name in headers) { + if (headers[name] !== O[name]) { + fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + + "=" + + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)); + } + } + if (fields.length) { + components.query = fields.join("&"); + } + return components; + } +}; +export default handler; +//# sourceMappingURL=mailto.js.map \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/schemes/mailto.js.map b/node_modules/uri-js/dist/esnext/schemes/mailto.js.map new file mode 100755 index 0000000..82dba9a --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/mailto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mailto.js","sourceRoot":"","sources":["../../../src/schemes/mailto.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,QAAQ,CAAC;AACpE,OAAO,QAAQ,MAAM,UAAU,CAAC;AAChC,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,WAAW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C;QAE1E,IAAI,gBAAgB,CAAC,OAAO;YAAE,OAAO,CAAC,SAAS,CAAC,GAAG,gBAAgB,CAAC,OAAO,CAAC;QAC5E,IAAI,gBAAgB,CAAC,IAAI;YAAE,OAAO,CAAC,MAAM,CAAC,GAAG,gBAAgB,CAAC,IAAI,CAAC;QAEnE,MAAM,MAAM,GAAG,EAAE,CAAC;QAClB,KAAK,MAAM,IAAI,IAAI,OAAO,EAAE;YAC3B,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,EAAE;gBAC9B,MAAM,CAAC,IAAI,CACV,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,gBAAgB,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,UAAU,CAAC;oBAC7G,GAAG;oBACH,OAAO,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,gBAAgB,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,UAAU,CAAC,CACvH,CAAC;aACF;SACD;QACD,IAAI,MAAM,CAAC,MAAM,EAAE;YAClB,UAAU,CAAC,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;SACpC;QAED,OAAO,UAAU,CAAC;IACnB,CAAC;CACD,CAAA;AAED,eAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/schemes/urn-uuid.d.ts b/node_modules/uri-js/dist/esnext/schemes/urn-uuid.d.ts new file mode 100755 index 0000000..e75f2e7 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/urn-uuid.d.ts @@ -0,0 +1,7 @@ +import { URISchemeHandler, URIOptions } from "../uri"; +import { URNComponents } from "./urn"; +export interface UUIDComponents extends URNComponents { + uuid?: string; +} +declare const handler: URISchemeHandler; +export default handler; diff --git a/node_modules/uri-js/dist/esnext/schemes/urn-uuid.js b/node_modules/uri-js/dist/esnext/schemes/urn-uuid.js new file mode 100755 index 0000000..d1fce49 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/urn-uuid.js @@ -0,0 +1,23 @@ +const UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/; +const UUID_PARSE = /^[0-9A-Fa-f\-]{36}/; +//RFC 4122 +const handler = { + scheme: "urn:uuid", + parse: function (urnComponents, options) { + const uuidComponents = urnComponents; + uuidComponents.uuid = uuidComponents.nss; + uuidComponents.nss = undefined; + if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) { + uuidComponents.error = uuidComponents.error || "UUID is not valid."; + } + return uuidComponents; + }, + serialize: function (uuidComponents, options) { + const urnComponents = uuidComponents; + //normalize UUID + urnComponents.nss = (uuidComponents.uuid || "").toLowerCase(); + return urnComponents; + }, +}; +export default handler; +//# sourceMappingURL=urn-uuid.js.map \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/schemes/urn-uuid.js.map b/node_modules/uri-js/dist/esnext/schemes/urn-uuid.js.map new file mode 100755 index 0000000..3b7a8b3 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/urn-uuid.js.map @@ -0,0 +1 @@ +{"version":3,"file":"urn-uuid.js","sourceRoot":"","sources":["../../../src/schemes/urn-uuid.ts"],"names":[],"mappings":"AAQA,MAAM,IAAI,GAAG,0DAA0D,CAAC;AACxE,MAAM,UAAU,GAAG,oBAAoB,CAAC;AAExC,UAAU;AACV,MAAM,OAAO,GAA+D;IAC3E,MAAM,EAAG,UAAU;IAEnB,KAAK,EAAG,UAAU,aAA2B,EAAE,OAAkB;QAChE,MAAM,cAAc,GAAG,aAA+B,CAAC;QACvD,cAAc,CAAC,IAAI,GAAG,cAAc,CAAC,GAAG,CAAC;QACzC,cAAc,CAAC,GAAG,GAAG,SAAS,CAAC;QAE/B,IAAI,CAAC,OAAO,CAAC,QAAQ,IAAI,CAAC,CAAC,cAAc,CAAC,IAAI,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE;YACpF,cAAc,CAAC,KAAK,GAAG,cAAc,CAAC,KAAK,IAAI,oBAAoB,CAAC;SACpE;QAED,OAAO,cAAc,CAAC;IACvB,CAAC;IAED,SAAS,EAAG,UAAU,cAA6B,EAAE,OAAkB;QACtE,MAAM,aAAa,GAAG,cAA+B,CAAC;QACtD,gBAAgB;QAChB,aAAa,CAAC,GAAG,GAAG,CAAC,cAAc,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;QAC9D,OAAO,aAAa,CAAC;IACtB,CAAC;CACD,CAAC;AAEF,eAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/schemes/urn.d.ts b/node_modules/uri-js/dist/esnext/schemes/urn.d.ts new file mode 100755 index 0000000..7e0c2fb --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/urn.d.ts @@ -0,0 +1,10 @@ +import { URISchemeHandler, URIComponents, URIOptions } from "../uri"; +export interface URNComponents extends URIComponents { + nid?: string; + nss?: string; +} +export interface URNOptions extends URIOptions { + nid?: string; +} +declare const handler: URISchemeHandler; +export default handler; diff --git a/node_modules/uri-js/dist/esnext/schemes/urn.js b/node_modules/uri-js/dist/esnext/schemes/urn.js new file mode 100755 index 0000000..5d3f10a --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/urn.js @@ -0,0 +1,49 @@ +import { SCHEMES } from "../uri"; +const NID$ = "(?:[0-9A-Za-z][0-9A-Za-z\\-]{1,31})"; +const PCT_ENCODED$ = "(?:\\%[0-9A-Fa-f]{2})"; +const TRANS$$ = "[0-9A-Za-z\\(\\)\\+\\,\\-\\.\\:\\=\\@\\;\\$\\_\\!\\*\\'\\/\\?\\#]"; +const NSS$ = "(?:(?:" + PCT_ENCODED$ + "|" + TRANS$$ + ")+)"; +const URN_SCHEME = new RegExp("^urn\\:(" + NID$ + ")$"); +const URN_PATH = new RegExp("^(" + NID$ + ")\\:(" + NSS$ + ")$"); +const URN_PARSE = /^([^\:]+)\:(.*)/; +const URN_EXCLUDED = /[\x00-\x20\\\"\&\<\>\[\]\^\`\{\|\}\~\x7F-\xFF]/g; +//RFC 2141 +const handler = { + scheme: "urn", + parse: function (components, options) { + const matches = components.path && components.path.match(URN_PARSE); + let urnComponents = components; + if (matches) { + const scheme = options.scheme || urnComponents.scheme || "urn"; + const nid = matches[1].toLowerCase(); + const nss = matches[2]; + const urnScheme = `${scheme}:${options.nid || nid}`; + const schemeHandler = SCHEMES[urnScheme]; + urnComponents.nid = nid; + urnComponents.nss = nss; + urnComponents.path = undefined; + if (schemeHandler) { + urnComponents = schemeHandler.parse(urnComponents, options); + } + } + else { + urnComponents.error = urnComponents.error || "URN can not be parsed."; + } + return urnComponents; + }, + serialize: function (urnComponents, options) { + const scheme = options.scheme || urnComponents.scheme || "urn"; + const nid = urnComponents.nid; + const urnScheme = `${scheme}:${options.nid || nid}`; + const schemeHandler = SCHEMES[urnScheme]; + if (schemeHandler) { + urnComponents = schemeHandler.serialize(urnComponents, options); + } + const uriComponents = urnComponents; + const nss = urnComponents.nss; + uriComponents.path = `${nid || options.nid}:${nss}`; + return uriComponents; + }, +}; +export default handler; +//# sourceMappingURL=urn.js.map \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/schemes/urn.js.map b/node_modules/uri-js/dist/esnext/schemes/urn.js.map new file mode 100755 index 0000000..ea43b0b --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/urn.js.map @@ -0,0 +1 @@ +{"version":3,"file":"urn.js","sourceRoot":"","sources":["../../../src/schemes/urn.ts"],"names":[],"mappings":"AACA,OAAO,EAAc,OAAO,EAAE,MAAM,QAAQ,CAAC;AAW7C,MAAM,IAAI,GAAG,qCAAqC,CAAC;AACnD,MAAM,YAAY,GAAG,uBAAuB,CAAC;AAC7C,MAAM,OAAO,GA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;SACD;aAAM;YACN,aAAa,CAAC,KAAK,GAAG,aAAa,CAAC,KAAK,IAAI,wBAAwB,CAAC;SACtE;QAED,OAAO,aAAa,CAAC;IACtB,CAAC;IAED,SAAS,EAAG,UAAU,aAA2B,EAAE,OAAkB;QACpE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,aAAa,CAAC,MAAM,IAAI,KAAK,CAAC;QAC/D,MAAM,GAAG,GAAG,aAAa,CAAC,GAAG,CAAC;QAC9B,MAAM,SAAS,GAAG,GAAG,MAAM,IAAI,OAAO,CAAC,GAAG,IAAI,GAAG,EAAE,CAAC;QACpD,MAAM,aAAa,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;QAEzC,IAAI,aAAa,EAAE;YAClB,aAAa,GAAG,aAAa,CAAC,SAAS,CAAC,aAAa,EAAE,OAAO,CAAkB,CAAC;SACjF;QAED,MAAM,aAAa,GAAG,aAA8B,CAAC;QACrD,MAAM,GAAG,GAAG,aAAa,CAAC,GAAG,CAAC;QAC9B,aAAa,CAAC,IAAI,GAAG,GAAG,GAAG,IAAI,OAAO,CAAC,GAAG,IAAI,GAAG,EAAE,CAAC;QAEpD,OAAO,aAAa,CAAC;IACtB,CAAC;CACD,CAAC;AAEF,eAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/schemes/ws.d.ts b/node_modules/uri-js/dist/esnext/schemes/ws.d.ts new file mode 100755 index 0000000..47f4835 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/ws.d.ts @@ -0,0 +1,7 @@ +import { URISchemeHandler, URIComponents } from "../uri"; +export interface WSComponents extends URIComponents { + resourceName?: string; + secure?: boolean; +} +declare const handler: URISchemeHandler; +export default handler; diff --git a/node_modules/uri-js/dist/esnext/schemes/ws.js b/node_modules/uri-js/dist/esnext/schemes/ws.js new file mode 100755 index 0000000..9277f03 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/ws.js @@ -0,0 +1,41 @@ +function isSecure(wsComponents) { + return typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss"; +} +//RFC 6455 +const handler = { + scheme: "ws", + domainHost: true, + parse: function (components, options) { + const wsComponents = components; + //indicate if the secure flag is set + wsComponents.secure = isSecure(wsComponents); + //construct resouce name + wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : ''); + wsComponents.path = undefined; + wsComponents.query = undefined; + return wsComponents; + }, + serialize: function (wsComponents, options) { + //normalize the default port + if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") { + wsComponents.port = undefined; + } + //ensure scheme matches secure flag + if (typeof wsComponents.secure === 'boolean') { + wsComponents.scheme = (wsComponents.secure ? 'wss' : 'ws'); + wsComponents.secure = undefined; + } + //reconstruct path from resource name + if (wsComponents.resourceName) { + const [path, query] = wsComponents.resourceName.split('?'); + wsComponents.path = (path && path !== '/' ? path : undefined); + wsComponents.query = query; + wsComponents.resourceName = undefined; + } + //forbid fragment component + wsComponents.fragment = undefined; + return wsComponents; + } +}; +export default handler; +//# sourceMappingURL=ws.js.map \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/schemes/ws.js.map b/node_modules/uri-js/dist/esnext/schemes/ws.js.map new file mode 100755 index 0000000..186818c --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/ws.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ws.js","sourceRoot":"","sources":["../../../src/schemes/ws.ts"],"names":[],"mappings":"AAOA,kBAAkB,YAAyB;IAC1C,OAAO,OAAO,YAAY,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,KAAK,KAAK,CAAC;AAC7H,CAAC;AAED,UAAU;AACV,MAAM,OAAO,GAAoB;IAChC,MAAM,EAAG,IAAI;IAEb,UAAU,EAAG,IAA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,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;YAC9D,YAAY,CAAC,KAAK,GAAG,KAAK,CAAC;YAC3B,YAAY,CAAC,YAAY,GAAG,SAAS,CAAC;SACtC;QAED,2BAA2B;QAC3B,YAAY,CAAC,QAAQ,GAAG,SAAS,CAAC;QAElC,OAAO,YAAY,CAAC;IACrB,CAAC;CACD,CAAC;AAEF,eAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/schemes/wss.d.ts b/node_modules/uri-js/dist/esnext/schemes/wss.d.ts new file mode 100755 index 0000000..fe5b2f3 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/wss.d.ts @@ -0,0 +1,3 @@ +import { URISchemeHandler } from "../uri"; +declare const handler: URISchemeHandler; +export default handler; diff --git a/node_modules/uri-js/dist/esnext/schemes/wss.js b/node_modules/uri-js/dist/esnext/schemes/wss.js new file mode 100755 index 0000000..d1e22cc --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/wss.js @@ -0,0 +1,9 @@ +import ws from "./ws"; +const handler = { + scheme: "wss", + domainHost: ws.domainHost, + parse: ws.parse, + serialize: ws.serialize +}; +export default handler; +//# sourceMappingURL=wss.js.map \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/schemes/wss.js.map b/node_modules/uri-js/dist/esnext/schemes/wss.js.map new file mode 100755 index 0000000..e19006d --- /dev/null +++ b/node_modules/uri-js/dist/esnext/schemes/wss.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wss.js","sourceRoot":"","sources":["../../../src/schemes/wss.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,MAAM,CAAC;AAEtB,MAAM,OAAO,GAAoB;IAChC,MAAM,EAAG,KAAK;IACd,UAAU,EAAG,EAAE,CAAC,UAAU;IAC1B,KAAK,EAAG,EAAE,CAAC,KAAK;IAChB,SAAS,EAAG,EAAE,CAAC,SAAS;CACxB,CAAA;AAED,eAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/uri.d.ts b/node_modules/uri-js/dist/esnext/uri.d.ts new file mode 100755 index 0000000..da51e23 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/uri.d.ts @@ -0,0 +1,59 @@ +export interface URIComponents { + scheme?: string; + userinfo?: string; + host?: string; + port?: number | string; + path?: string; + query?: string; + fragment?: string; + reference?: string; + error?: string; +} +export interface URIOptions { + scheme?: string; + reference?: string; + tolerant?: boolean; + absolutePath?: boolean; + iri?: boolean; + unicodeSupport?: boolean; + domainHost?: boolean; +} +export interface URISchemeHandler { + scheme: string; + parse(components: ParentComponents, options: Options): Components; + serialize(components: Components, options: Options): ParentComponents; + unicodeSupport?: boolean; + domainHost?: boolean; + absolutePath?: boolean; +} +export interface URIRegExps { + NOT_SCHEME: RegExp; + NOT_USERINFO: RegExp; + NOT_HOST: RegExp; + NOT_PATH: RegExp; + NOT_PATH_NOSCHEME: RegExp; + NOT_QUERY: RegExp; + NOT_FRAGMENT: RegExp; + ESCAPE: RegExp; + UNRESERVED: RegExp; + OTHER_CHARS: RegExp; + PCT_ENCODED: RegExp; + IPV4ADDRESS: RegExp; + IPV6ADDRESS: RegExp; +} +export declare const SCHEMES: { + [scheme: string]: URISchemeHandler; +}; +export declare function pctEncChar(chr: string): string; +export declare function pctDecChars(str: string): string; +export declare function parse(uriString: string, options?: URIOptions): URIComponents; +export declare function removeDotSegments(input: string): string; +export declare function serialize(components: URIComponents, options?: URIOptions): string; +export declare function resolveComponents(base: URIComponents, relative: URIComponents, options?: URIOptions, skipNormalization?: boolean): URIComponents; +export declare function resolve(baseURI: string, relativeURI: string, options?: URIOptions): string; +export declare function normalize(uri: string, options?: URIOptions): string; +export declare function normalize(uri: URIComponents, options?: URIOptions): URIComponents; +export declare function equal(uriA: string, uriB: string, options?: URIOptions): boolean; +export declare function equal(uriA: URIComponents, uriB: URIComponents, options?: URIOptions): boolean; +export declare function escapeComponent(str: string, options?: URIOptions): string; +export declare function unescapeComponent(str: string, options?: URIOptions): string; diff --git a/node_modules/uri-js/dist/esnext/uri.js b/node_modules/uri-js/dist/esnext/uri.js new file mode 100755 index 0000000..659ce26 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/uri.js @@ -0,0 +1,480 @@ +/** + * URI.js + * + * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript. + * @author Gary Court + * @see http://github.com/garycourt/uri-js + */ +/** + * Copyright 2011 Gary Court. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of Gary Court. + */ +import URI_PROTOCOL from "./regexps-uri"; +import IRI_PROTOCOL from "./regexps-iri"; +import punycode from "punycode"; +import { toUpperCase, typeOf, assign } from "./util"; +export const SCHEMES = {}; +export function pctEncChar(chr) { + const c = chr.charCodeAt(0); + let e; + if (c < 16) + e = "%0" + c.toString(16).toUpperCase(); + else if (c < 128) + e = "%" + c.toString(16).toUpperCase(); + else if (c < 2048) + e = "%" + ((c >> 6) | 192).toString(16).toUpperCase() + "%" + ((c & 63) | 128).toString(16).toUpperCase(); + else + e = "%" + ((c >> 12) | 224).toString(16).toUpperCase() + "%" + (((c >> 6) & 63) | 128).toString(16).toUpperCase() + "%" + ((c & 63) | 128).toString(16).toUpperCase(); + return e; +} +export function pctDecChars(str) { + let newStr = ""; + let i = 0; + const il = str.length; + while (i < il) { + const c = parseInt(str.substr(i + 1, 2), 16); + if (c < 128) { + newStr += String.fromCharCode(c); + i += 3; + } + else if (c >= 194 && c < 224) { + if ((il - i) >= 6) { + const c2 = parseInt(str.substr(i + 4, 2), 16); + newStr += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); + } + else { + newStr += str.substr(i, 6); + } + i += 6; + } + else if (c >= 224) { + if ((il - i) >= 9) { + const c2 = parseInt(str.substr(i + 4, 2), 16); + const c3 = parseInt(str.substr(i + 7, 2), 16); + newStr += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); + } + else { + newStr += str.substr(i, 9); + } + i += 9; + } + else { + newStr += str.substr(i, 3); + i += 3; + } + } + return newStr; +} +function _normalizeComponentEncoding(components, protocol) { + function decodeUnreserved(str) { + const decStr = pctDecChars(str); + return (!decStr.match(protocol.UNRESERVED) ? str : decStr); + } + if (components.scheme) + components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, ""); + if (components.userinfo !== undefined) + components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.host !== undefined) + components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.path !== undefined) + components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace((components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME), pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.query !== undefined) + components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.fragment !== undefined) + components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + return components; +} +; +function _stripLeadingZeros(str) { + return str.replace(/^0*(.*)/, "$1") || "0"; +} +function _normalizeIPv4(host, protocol) { + const matches = host.match(protocol.IPV4ADDRESS) || []; + const [, address] = matches; + if (address) { + return address.split(".").map(_stripLeadingZeros).join("."); + } + else { + return host; + } +} +function _normalizeIPv6(host, protocol) { + const matches = host.match(protocol.IPV6ADDRESS) || []; + const [, address, zone] = matches; + if (address) { + const [last, first] = address.toLowerCase().split('::').reverse(); + const firstFields = first ? first.split(":").map(_stripLeadingZeros) : []; + const lastFields = last.split(":").map(_stripLeadingZeros); + const isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]); + const fieldCount = isLastFieldIPv4Address ? 7 : 8; + const lastFieldsStart = lastFields.length - fieldCount; + const fields = Array(fieldCount); + for (let x = 0; x < fieldCount; ++x) { + fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || ''; + } + if (isLastFieldIPv4Address) { + fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol); + } + const allZeroFields = fields.reduce((acc, field, index) => { + if (!field || field === "0") { + const lastLongest = acc[acc.length - 1]; + if (lastLongest && lastLongest.index + lastLongest.length === index) { + lastLongest.length++; + } + else { + acc.push({ index, length: 1 }); + } + } + return acc; + }, []); + const longestZeroFields = allZeroFields.sort((a, b) => b.length - a.length)[0]; + let newHost; + if (longestZeroFields && longestZeroFields.length > 1) { + const newFirst = fields.slice(0, longestZeroFields.index); + const newLast = fields.slice(longestZeroFields.index + longestZeroFields.length); + newHost = newFirst.join(":") + "::" + newLast.join(":"); + } + else { + newHost = fields.join(":"); + } + if (zone) { + newHost += "%" + zone; + } + return newHost; + } + else { + return host; + } +} +const URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i; +const NO_MATCH_IS_UNDEFINED = ("").match(/(){0}/)[1] === undefined; +export function parse(uriString, options = {}) { + const components = {}; + const protocol = (options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL); + if (options.reference === "suffix") + uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString; + const matches = uriString.match(URI_PARSE); + if (matches) { + if (NO_MATCH_IS_UNDEFINED) { + //store each component + components.scheme = matches[1]; + components.userinfo = matches[3]; + components.host = matches[4]; + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = matches[7]; + components.fragment = matches[8]; + //fix port number + if (isNaN(components.port)) { + components.port = matches[5]; + } + } + else { //IE FIX for improper RegExp matching + //store each component + components.scheme = matches[1] || undefined; + components.userinfo = (uriString.indexOf("@") !== -1 ? matches[3] : undefined); + components.host = (uriString.indexOf("//") !== -1 ? matches[4] : undefined); + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = (uriString.indexOf("?") !== -1 ? matches[7] : undefined); + components.fragment = (uriString.indexOf("#") !== -1 ? matches[8] : undefined); + //fix port number + if (isNaN(components.port)) { + components.port = (uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined); + } + } + if (components.host) { + //normalize IP hosts + components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol); + } + //determine reference type + if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) { + components.reference = "same-document"; + } + else if (components.scheme === undefined) { + components.reference = "relative"; + } + else if (components.fragment === undefined) { + components.reference = "absolute"; + } + else { + components.reference = "uri"; + } + //check for reference errors + if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) { + components.error = components.error || "URI is not a " + options.reference + " reference."; + } + //find scheme handler + const schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //check if scheme can't handle IRIs + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + //if host component is a domain name + if (components.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost))) { + //convert Unicode IDN -> ASCII IDN + try { + components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()); + } + catch (e) { + components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e; + } + } + //convert IRI -> URI + _normalizeComponentEncoding(components, URI_PROTOCOL); + } + else { + //normalize encodings + _normalizeComponentEncoding(components, protocol); + } + //perform scheme specific parsing + if (schemeHandler && schemeHandler.parse) { + schemeHandler.parse(components, options); + } + } + else { + components.error = components.error || "URI can not be parsed."; + } + return components; +} +; +function _recomposeAuthority(components, options) { + const protocol = (options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL); + const uriTokens = []; + if (components.userinfo !== undefined) { + uriTokens.push(components.userinfo); + uriTokens.push("@"); + } + if (components.host !== undefined) { + //normalize IP hosts, add brackets and escape zone separator for IPv6 + uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, (_, $1, $2) => "[" + $1 + ($2 ? "%25" + $2 : "") + "]")); + } + if (typeof components.port === "number" || typeof components.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(components.port)); + } + return uriTokens.length ? uriTokens.join("") : undefined; +} +; +const RDS1 = /^\.\.?\//; +const RDS2 = /^\/\.(\/|$)/; +const RDS3 = /^\/\.\.(\/|$)/; +const RDS4 = /^\.\.?$/; +const RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/; +export function removeDotSegments(input) { + const output = []; + while (input.length) { + if (input.match(RDS1)) { + input = input.replace(RDS1, ""); + } + else if (input.match(RDS2)) { + input = input.replace(RDS2, "/"); + } + else if (input.match(RDS3)) { + input = input.replace(RDS3, "/"); + output.pop(); + } + else if (input === "." || input === "..") { + input = ""; + } + else { + const im = input.match(RDS5); + if (im) { + const s = im[0]; + input = input.slice(s.length); + output.push(s); + } + else { + throw new Error("Unexpected dot segment condition"); + } + } + } + return output.join(""); +} +; +export function serialize(components, options = {}) { + const protocol = (options.iri ? IRI_PROTOCOL : URI_PROTOCOL); + const uriTokens = []; + //find scheme handler + const schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //perform scheme specific serialization + if (schemeHandler && schemeHandler.serialize) + schemeHandler.serialize(components, options); + if (components.host) { + //if host component is an IPv6 address + if (protocol.IPV6ADDRESS.test(components.host)) { + //TODO: normalize IPv6 address as per RFC 5952 + } + //if host component is a domain name + else if (options.domainHost || (schemeHandler && schemeHandler.domainHost)) { + //convert IDN via punycode + try { + components.host = (!options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host)); + } + catch (e) { + components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + } + } + //normalize encoding + _normalizeComponentEncoding(components, protocol); + if (options.reference !== "suffix" && components.scheme) { + uriTokens.push(components.scheme); + uriTokens.push(":"); + } + const authority = _recomposeAuthority(components, options); + if (authority !== undefined) { + if (options.reference !== "suffix") { + uriTokens.push("//"); + } + uriTokens.push(authority); + if (components.path && components.path.charAt(0) !== "/") { + uriTokens.push("/"); + } + } + if (components.path !== undefined) { + let s = components.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { + s = removeDotSegments(s); + } + if (authority === undefined) { + s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//" + } + uriTokens.push(s); + } + if (components.query !== undefined) { + uriTokens.push("?"); + uriTokens.push(components.query); + } + if (components.fragment !== undefined) { + uriTokens.push("#"); + uriTokens.push(components.fragment); + } + return uriTokens.join(""); //merge tokens into a string +} +; +export function resolveComponents(base, relative, options = {}, skipNormalization) { + const target = {}; + if (!skipNormalization) { + base = parse(serialize(base, options), options); //normalize base components + relative = parse(serialize(relative, options), options); //normalize relative components + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } + else { + if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } + else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== undefined) { + target.query = relative.query; + } + else { + target.query = base.query; + } + } + else { + if (relative.path.charAt(0) === "/") { + target.path = removeDotSegments(relative.path); + } + else { + if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) { + target.path = "/" + relative.path; + } + else if (!base.path) { + target.path = relative.path; + } + else { + target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + } + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + //target.authority = base.authority; + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; +} +; +export function resolve(baseURI, relativeURI, options) { + const schemelessOptions = assign({ scheme: 'null' }, options); + return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions); +} +; +export function normalize(uri, options) { + if (typeof uri === "string") { + uri = serialize(parse(uri, options), options); + } + else if (typeOf(uri) === "object") { + uri = parse(serialize(uri, options), options); + } + return uri; +} +; +export function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = serialize(parse(uriA, options), options); + } + else if (typeOf(uriA) === "object") { + uriA = serialize(uriA, options); + } + if (typeof uriB === "string") { + uriB = serialize(parse(uriB, options), options); + } + else if (typeOf(uriB) === "object") { + uriB = serialize(uriB, options); + } + return uriA === uriB; +} +; +export function escapeComponent(str, options) { + return str && str.toString().replace((!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE), pctEncChar); +} +; +export function unescapeComponent(str, options) { + return str && str.toString().replace((!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED), pctDecChars); +} +; +//# sourceMappingURL=uri.js.map \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/uri.js.map b/node_modules/uri-js/dist/esnext/uri.js.map new file mode 100755 index 0000000..2e72ab1 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/uri.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uri.js","sourceRoot":"","sources":["../../src/uri.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,QAAQ,MAAM,UAAU,CAAC;AAChC,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAiDrD,MAAM,CAAC,MAAM,OAAO,GAAsC,EAAE,CAAC;AAE7D,MAAM,qBAAqB,GAAU;IACpC,MAAM,CAAC,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAC5B,IAAI,CAAQ,CAAC;IAEb,IAAI,CAAC,GAAG,EAAE;QAAE,CAAC,GAAG,IAAI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,GAAG,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC,WAAW,CAAC,CAAC,CAAC,YAAY,CAAC,WAAW,CAAC,EAAE,WAAW,CAAC,CAAC;AACrI,CAAC;AAAA,CAAC"} \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/util.d.ts b/node_modules/uri-js/dist/esnext/util.d.ts new file mode 100755 index 0000000..7c12857 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/util.d.ts @@ -0,0 +1,6 @@ +export declare function merge(...sets: Array): string; +export declare function subexp(str: string): string; +export declare function typeOf(o: any): string; +export declare function toUpperCase(str: string): string; +export declare function toArray(obj: any): Array; +export declare function assign(target: object, source: any): any; diff --git a/node_modules/uri-js/dist/esnext/util.js b/node_modules/uri-js/dist/esnext/util.js new file mode 100755 index 0000000..072711e --- /dev/null +++ b/node_modules/uri-js/dist/esnext/util.js @@ -0,0 +1,36 @@ +export function merge(...sets) { + if (sets.length > 1) { + sets[0] = sets[0].slice(0, -1); + const xl = sets.length - 1; + for (let x = 1; x < xl; ++x) { + sets[x] = sets[x].slice(1, -1); + } + sets[xl] = sets[xl].slice(1); + return sets.join(''); + } + else { + return sets[0]; + } +} +export function subexp(str) { + return "(?:" + str + ")"; +} +export function typeOf(o) { + return o === undefined ? "undefined" : (o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase()); +} +export function toUpperCase(str) { + return str.toUpperCase(); +} +export function toArray(obj) { + return obj !== undefined && obj !== null ? (obj instanceof Array ? obj : (typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj))) : []; +} +export function assign(target, source) { + const obj = target; + if (source) { + for (const key in source) { + obj[key] = source[key]; + } + } + return obj; +} +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/node_modules/uri-js/dist/esnext/util.js.map b/node_modules/uri-js/dist/esnext/util.js.map new file mode 100755 index 0000000..05d9df0 --- /dev/null +++ b/node_modules/uri-js/dist/esnext/util.js.map @@ -0,0 +1 @@ +{"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/util.ts"],"names":[],"mappings":"AAAA,MAAM,gBAAgB,GAAG,IAAkB;IAC1C,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE;QACpB,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QAC/B,MAAM,EAAE,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;QAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,EAAE,CAAC,EAAE;YAC5B,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;SAC/B;QACD,IAAI,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QAC7B,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;KACrB;SAAM;QACN,OAAO,IAAI,CAAC,CAAC,CAAC,CAAC;KACf;AACF,CAAC;AAED,MAAM,iBAAiB,GAAU;IAChC,OAAO,KAAK,GAAG,GAAG,GAAG,GAAG,CAAC;AAC1B,CAAC;AAED,MAAM,iBAAiB,CAAK;IAC3B,OAAO,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC;AACpJ,CAAC;AAED,MAAM,sBAAsB,GAAU;IACrC,OAAO,GAAG,CAAC,WAAW,EAAE,CAAC;AAC1B,CAAC;AAED,MAAM,kBAAkB,GAAO;IAC9B,OAAO,GAAG,KAAK,SAAS,IAAI,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,GAAG,CAAC,MAAM,KAAK,QAAQ,IAAI,GAAG,CAAC,KAAK,IAAI,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACvM,CAAC;AAGD,MAAM,iBAAiB,MAAc,EAAE,MAAW;IACjD,MAAM,GAAG,GAAG,MAAa,CAAC;IAC1B,IAAI,MAAM,EAAE;QACX,KAAK,MAAM,GAAG,IAAI,MAAM,EAAE;YACzB,GAAG,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;SACvB;KACD;IACD,OAAO,GAAG,CAAC;AACZ,CAAC"} \ No newline at end of file diff --git a/node_modules/uri-js/package.json b/node_modules/uri-js/package.json new file mode 100755 index 0000000..de95d91 --- /dev/null +++ b/node_modules/uri-js/package.json @@ -0,0 +1,77 @@ +{ + "name": "uri-js", + "version": "4.4.1", + "description": "An RFC 3986/3987 compliant, scheme extendable URI/IRI parsing/validating/resolving library for JavaScript.", + "main": "dist/es5/uri.all.js", + "types": "dist/es5/uri.all.d.ts", + "directories": { + "test": "tests" + }, + "files": [ + "dist", + "package.json", + "yarn.lock", + "README.md", + "CHANGELOG", + "LICENSE" + ], + "scripts": { + "build:esnext": "tsc", + "build:es5": "rollup -c && cp dist/esnext/uri.d.ts dist/es5/uri.all.d.ts && npm run build:es5:fix-sourcemap", + "build:es5:fix-sourcemap": "sorcery -i dist/es5/uri.all.js", + "build:es5:min": "uglifyjs dist/es5/uri.all.js --support-ie8 --output dist/es5/uri.all.min.js --in-source-map dist/es5/uri.all.js.map --source-map uri.all.min.js.map --comments --compress --mangle --pure-funcs merge subexp && mv uri.all.min.js.map dist/es5/ && cp dist/es5/uri.all.d.ts dist/es5/uri.all.min.d.ts", + "build": "npm run build:esnext && npm run build:es5 && npm run build:es5:min", + "clean": "rm -rf dist", + "test": "mocha -u mocha-qunit-ui dist/es5/uri.all.js tests/tests.js" + }, + "repository": { + "type": "git", + "url": "http://github.com/garycourt/uri-js" + }, + "keywords": [ + "URI", + "IRI", + "IDN", + "URN", + "UUID", + "HTTP", + "HTTPS", + "WS", + "WSS", + "MAILTO", + "RFC3986", + "RFC3987", + "RFC5891", + "RFC2616", + "RFC2818", + "RFC2141", + "RFC4122", + "RFC4291", + "RFC5952", + "RFC6068", + "RFC6455", + "RFC6874" + ], + "author": "Gary Court ", + "license": "BSD-2-Clause", + "bugs": { + "url": "https://github.com/garycourt/uri-js/issues" + }, + "homepage": "https://github.com/garycourt/uri-js", + "devDependencies": { + "babel-cli": "^6.26.0", + "babel-plugin-external-helpers": "^6.22.0", + "babel-preset-latest": "^6.24.1", + "mocha": "^8.2.1", + "mocha-qunit-ui": "^0.1.3", + "rollup": "^0.41.6", + "rollup-plugin-babel": "^2.7.1", + "rollup-plugin-node-resolve": "^2.0.0", + "sorcery": "^0.10.0", + "typescript": "^2.8.1", + "uglify-js": "^2.8.14" + }, + "dependencies": { + "punycode": "^2.1.0" + } +} diff --git a/node_modules/uri-js/yarn.lock b/node_modules/uri-js/yarn.lock new file mode 100755 index 0000000..3c42ded --- /dev/null +++ b/node_modules/uri-js/yarn.lock @@ -0,0 +1,2558 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +"@ungap/promise-all-settled@1.1.2": + version "1.1.2" + resolved "https://registry.yarnpkg.com/@ungap/promise-all-settled/-/promise-all-settled-1.1.2.tgz#aa58042711d6e3275dd37dc597e5d31e8c290a44" + integrity sha512-sL/cEvJWAnClXw0wHk85/2L0G6Sj8UB0Ctc1TEMbKSsmpRosqhwj9gWgFRZSrBr2f9tiXISwNhCPmlfqUqyb9Q== + +align-text@^0.1.1, align-text@^0.1.3: + version "0.1.4" + resolved "https://registry.yarnpkg.com/align-text/-/align-text-0.1.4.tgz#0cd90a561093f35d0a99256c22b7069433fad117" + dependencies: + kind-of "^3.0.2" + longest "^1.0.1" + repeat-string "^1.5.2" + +ansi-colors@4.1.1: + version "4.1.1" + resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-4.1.1.tgz#cbb9ae256bf750af1eab344f229aa27fe94ba348" + integrity sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA== + +ansi-regex@^2.0.0: + version "2.1.1" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df" + integrity sha1-w7M6te42DYbg5ijwRorn7yfWVN8= + +ansi-regex@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-3.0.0.tgz#ed0317c322064f79466c02966bddb605ab37d998" + integrity sha1-7QMXwyIGT3lGbAKWa922Bas32Zg= + +ansi-regex@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-4.1.0.tgz#8b9f8f08cf1acb843756a839ca8c7e3168c51997" + integrity sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg== + +ansi-styles@^2.2.1: + version "2.2.1" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe" + integrity sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4= + +ansi-styles@^3.2.0: + version "3.2.1" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" + integrity sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA== + dependencies: + color-convert "^1.9.0" + +ansi-styles@^4.1.0: + version "4.3.0" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.3.0.tgz#edd803628ae71c04c85ae7a0906edad34b648937" + integrity sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg== + dependencies: + color-convert "^2.0.1" + +anymatch@^1.3.0: + version "1.3.2" + resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-1.3.2.tgz#553dcb8f91e3c889845dfdba34c77721b90b9d7a" + integrity sha512-0XNayC8lTHQ2OI8aljNCN3sSx6hsr/1+rlcDAotXJR7C1oZZHCNsfpbKwMjRA3Uqb5tF1Rae2oloTr4xpq+WjA== + dependencies: + micromatch "^2.1.5" + normalize-path "^2.0.0" + +anymatch@~3.1.1: + version "3.1.1" + resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.1.tgz#c55ecf02185e2469259399310c173ce31233b142" + integrity sha512-mM8522psRCqzV+6LhomX5wgp25YVibjh8Wj23I5RPkPppSVSjyKD2A2mBJmWGa+KN7f2D6LNh9jkBCeyLktzjg== + dependencies: + normalize-path "^3.0.0" + picomatch "^2.0.4" + +argparse@^1.0.7: + version "1.0.10" + resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" + integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg== + dependencies: + sprintf-js "~1.0.2" + +arr-diff@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-2.0.0.tgz#8f3b827f955a8bd669697e4a4256ac3ceae356cf" + integrity sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8= + dependencies: + arr-flatten "^1.0.1" + +arr-diff@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-4.0.0.tgz#d6461074febfec71e7e15235761a329a5dc7c520" + integrity sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA= + +arr-flatten@^1.0.1, arr-flatten@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/arr-flatten/-/arr-flatten-1.1.0.tgz#36048bbff4e7b47e136644316c99669ea5ae91f1" + integrity sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg== + +arr-union@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/arr-union/-/arr-union-3.1.0.tgz#e39b09aea9def866a8f206e288af63919bae39c4" + integrity sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ= + +array-unique@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.2.1.tgz#a1d97ccafcbc2625cc70fadceb36a50c58b01a53" + integrity sha1-odl8yvy8JiXMcPrc6zalDFiwGlM= + +array-unique@^0.3.2: + version "0.3.2" + resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.3.2.tgz#a894b75d4bc4f6cd679ef3244a9fd8f46ae2d428" + integrity sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg= + +assign-symbols@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/assign-symbols/-/assign-symbols-1.0.0.tgz#59667f41fadd4f20ccbc2bb96b8d4f7f78ec0367" + integrity sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c= + +async-each@^1.0.0: + version "1.0.3" + resolved "https://registry.yarnpkg.com/async-each/-/async-each-1.0.3.tgz#b727dbf87d7651602f06f4d4ac387f47d91b0cbf" + integrity sha512-z/WhQ5FPySLdvREByI2vZiTWwCnF0moMJ1hK9YQwDTHKh6I7/uSckMetoRGb5UBZPC1z0jlw+n/XCgjeH7y1AQ== + +atob@^2.1.2: + version "2.1.2" + resolved "https://registry.yarnpkg.com/atob/-/atob-2.1.2.tgz#6d9517eb9e030d2436666651e86bd9f6f13533c9" + integrity sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg== + +babel-cli@^6.26.0: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-cli/-/babel-cli-6.26.0.tgz#502ab54874d7db88ad00b887a06383ce03d002f1" + integrity sha1-UCq1SHTX24itALiHoGODzgPQAvE= + dependencies: + babel-core "^6.26.0" + babel-polyfill "^6.26.0" + babel-register "^6.26.0" + babel-runtime "^6.26.0" + commander "^2.11.0" + convert-source-map "^1.5.0" + fs-readdir-recursive "^1.0.0" + glob "^7.1.2" + lodash "^4.17.4" + output-file-sync "^1.1.2" + path-is-absolute "^1.0.1" + slash "^1.0.0" + source-map "^0.5.6" + v8flags "^2.1.1" + optionalDependencies: + chokidar "^1.6.1" + +babel-code-frame@^6.26.0: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-code-frame/-/babel-code-frame-6.26.0.tgz#63fd43f7dc1e3bb7ce35947db8fe369a3f58c74b" + integrity sha1-Y/1D99weO7fONZR9uP42mj9Yx0s= + dependencies: + chalk "^1.1.3" + esutils "^2.0.2" + js-tokens "^3.0.2" + +babel-core@6: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-core/-/babel-core-6.26.0.tgz#af32f78b31a6fcef119c87b0fd8d9753f03a0bb8" + dependencies: + babel-code-frame "^6.26.0" + babel-generator "^6.26.0" + babel-helpers "^6.24.1" + babel-messages "^6.23.0" + babel-register "^6.26.0" + babel-runtime "^6.26.0" + babel-template "^6.26.0" + babel-traverse "^6.26.0" + babel-types "^6.26.0" + babylon "^6.18.0" + convert-source-map "^1.5.0" + debug "^2.6.8" + json5 "^0.5.1" + lodash "^4.17.4" + minimatch "^3.0.4" + path-is-absolute "^1.0.1" + private "^0.1.7" + slash "^1.0.0" + source-map "^0.5.6" + +babel-core@^6.26.0: + version "6.26.3" + resolved "https://registry.yarnpkg.com/babel-core/-/babel-core-6.26.3.tgz#b2e2f09e342d0f0c88e2f02e067794125e75c207" + integrity sha512-6jyFLuDmeidKmUEb3NM+/yawG0M2bDZ9Z1qbZP59cyHLz8kYGKYwpJP0UwUKKUiTRNvxfLesJnTedqczP7cTDA== + dependencies: + babel-code-frame "^6.26.0" + babel-generator "^6.26.0" + babel-helpers "^6.24.1" + babel-messages "^6.23.0" + babel-register "^6.26.0" + babel-runtime "^6.26.0" + babel-template "^6.26.0" + babel-traverse "^6.26.0" + babel-types "^6.26.0" + babylon "^6.18.0" + convert-source-map "^1.5.1" + debug "^2.6.9" + json5 "^0.5.1" + lodash "^4.17.4" + minimatch "^3.0.4" + path-is-absolute "^1.0.1" + private "^0.1.8" + slash "^1.0.0" + source-map "^0.5.7" + +babel-generator@^6.26.0: + version "6.26.1" + resolved "https://registry.yarnpkg.com/babel-generator/-/babel-generator-6.26.1.tgz#1844408d3b8f0d35a404ea7ac180f087a601bd90" + integrity sha512-HyfwY6ApZj7BYTcJURpM5tznulaBvyio7/0d4zFOeMPUmfxkCjHocCuoLa2SAGzBI8AREcH3eP3758F672DppA== + dependencies: + babel-messages "^6.23.0" + babel-runtime "^6.26.0" + babel-types "^6.26.0" + detect-indent "^4.0.0" + jsesc "^1.3.0" + lodash "^4.17.4" + source-map "^0.5.7" + trim-right "^1.0.1" + +babel-helper-builder-binary-assignment-operator-visitor@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-helper-builder-binary-assignment-operator-visitor/-/babel-helper-builder-binary-assignment-operator-visitor-6.24.1.tgz#cce4517ada356f4220bcae8a02c2b346f9a56664" + dependencies: + babel-helper-explode-assignable-expression "^6.24.1" + babel-runtime "^6.22.0" + babel-types "^6.24.1" + +babel-helper-call-delegate@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-helper-call-delegate/-/babel-helper-call-delegate-6.24.1.tgz#ece6aacddc76e41c3461f88bfc575bd0daa2df8d" + dependencies: + babel-helper-hoist-variables "^6.24.1" + babel-runtime "^6.22.0" + babel-traverse "^6.24.1" + babel-types "^6.24.1" + +babel-helper-define-map@^6.24.1: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-helper-define-map/-/babel-helper-define-map-6.26.0.tgz#a5f56dab41a25f97ecb498c7ebaca9819f95be5f" + dependencies: + babel-helper-function-name "^6.24.1" + babel-runtime "^6.26.0" + babel-types "^6.26.0" + lodash "^4.17.4" + +babel-helper-explode-assignable-expression@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-helper-explode-assignable-expression/-/babel-helper-explode-assignable-expression-6.24.1.tgz#f25b82cf7dc10433c55f70592d5746400ac22caa" + dependencies: + babel-runtime "^6.22.0" + babel-traverse "^6.24.1" + babel-types "^6.24.1" + +babel-helper-function-name@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-helper-function-name/-/babel-helper-function-name-6.24.1.tgz#d3475b8c03ed98242a25b48351ab18399d3580a9" + dependencies: + babel-helper-get-function-arity "^6.24.1" + babel-runtime "^6.22.0" + babel-template "^6.24.1" + babel-traverse "^6.24.1" + babel-types "^6.24.1" + +babel-helper-get-function-arity@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-helper-get-function-arity/-/babel-helper-get-function-arity-6.24.1.tgz#8f7782aa93407c41d3aa50908f89b031b1b6853d" + dependencies: + babel-runtime "^6.22.0" + babel-types "^6.24.1" + +babel-helper-hoist-variables@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-helper-hoist-variables/-/babel-helper-hoist-variables-6.24.1.tgz#1ecb27689c9d25513eadbc9914a73f5408be7a76" + dependencies: + babel-runtime "^6.22.0" + babel-types "^6.24.1" + +babel-helper-optimise-call-expression@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-helper-optimise-call-expression/-/babel-helper-optimise-call-expression-6.24.1.tgz#f7a13427ba9f73f8f4fa993c54a97882d1244257" + dependencies: + babel-runtime "^6.22.0" + babel-types "^6.24.1" + +babel-helper-regex@^6.24.1: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-helper-regex/-/babel-helper-regex-6.26.0.tgz#325c59f902f82f24b74faceed0363954f6495e72" + dependencies: + babel-runtime "^6.26.0" + babel-types "^6.26.0" + lodash "^4.17.4" + +babel-helper-remap-async-to-generator@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-helper-remap-async-to-generator/-/babel-helper-remap-async-to-generator-6.24.1.tgz#5ec581827ad723fecdd381f1c928390676e4551b" + dependencies: + babel-helper-function-name "^6.24.1" + babel-runtime "^6.22.0" + babel-template "^6.24.1" + babel-traverse "^6.24.1" + babel-types "^6.24.1" + +babel-helper-replace-supers@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-helper-replace-supers/-/babel-helper-replace-supers-6.24.1.tgz#bf6dbfe43938d17369a213ca8a8bf74b6a90ab1a" + dependencies: + babel-helper-optimise-call-expression "^6.24.1" + babel-messages "^6.23.0" + babel-runtime "^6.22.0" + babel-template "^6.24.1" + babel-traverse "^6.24.1" + babel-types "^6.24.1" + +babel-helpers@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-helpers/-/babel-helpers-6.24.1.tgz#3471de9caec388e5c850e597e58a26ddf37602b2" + integrity sha1-NHHenK7DiOXIUOWX5Yom3fN2ArI= + dependencies: + babel-runtime "^6.22.0" + babel-template "^6.24.1" + +babel-messages@^6.23.0: + version "6.23.0" + resolved "https://registry.yarnpkg.com/babel-messages/-/babel-messages-6.23.0.tgz#f3cdf4703858035b2a2951c6ec5edf6c62f2630e" + integrity sha1-8830cDhYA1sqKVHG7F7fbGLyYw4= + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-check-es2015-constants@^6.22.0: + version "6.22.0" + resolved "https://registry.yarnpkg.com/babel-plugin-check-es2015-constants/-/babel-plugin-check-es2015-constants-6.22.0.tgz#35157b101426fd2ffd3da3f75c7d1e91835bbf8a" + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-external-helpers@^6.22.0: + version "6.22.0" + resolved "https://registry.yarnpkg.com/babel-plugin-external-helpers/-/babel-plugin-external-helpers-6.22.0.tgz#2285f48b02bd5dede85175caf8c62e86adccefa1" + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-syntax-async-functions@^6.8.0: + version "6.13.0" + resolved "https://registry.yarnpkg.com/babel-plugin-syntax-async-functions/-/babel-plugin-syntax-async-functions-6.13.0.tgz#cad9cad1191b5ad634bf30ae0872391e0647be95" + +babel-plugin-syntax-exponentiation-operator@^6.8.0: + version "6.13.0" + resolved "https://registry.yarnpkg.com/babel-plugin-syntax-exponentiation-operator/-/babel-plugin-syntax-exponentiation-operator-6.13.0.tgz#9ee7e8337290da95288201a6a57f4170317830de" + +babel-plugin-syntax-trailing-function-commas@^6.22.0: + version "6.22.0" + resolved "https://registry.yarnpkg.com/babel-plugin-syntax-trailing-function-commas/-/babel-plugin-syntax-trailing-function-commas-6.22.0.tgz#ba0360937f8d06e40180a43fe0d5616fff532cf3" + +babel-plugin-transform-async-to-generator@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-async-to-generator/-/babel-plugin-transform-async-to-generator-6.24.1.tgz#6536e378aff6cb1d5517ac0e40eb3e9fc8d08761" + dependencies: + babel-helper-remap-async-to-generator "^6.24.1" + babel-plugin-syntax-async-functions "^6.8.0" + babel-runtime "^6.22.0" + +babel-plugin-transform-es2015-arrow-functions@^6.22.0: + version "6.22.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-arrow-functions/-/babel-plugin-transform-es2015-arrow-functions-6.22.0.tgz#452692cb711d5f79dc7f85e440ce41b9f244d221" + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-transform-es2015-block-scoped-functions@^6.22.0: + version "6.22.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-block-scoped-functions/-/babel-plugin-transform-es2015-block-scoped-functions-6.22.0.tgz#bbc51b49f964d70cb8d8e0b94e820246ce3a6141" + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-transform-es2015-block-scoping@^6.24.1: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-block-scoping/-/babel-plugin-transform-es2015-block-scoping-6.26.0.tgz#d70f5299c1308d05c12f463813b0a09e73b1895f" + dependencies: + babel-runtime "^6.26.0" + babel-template "^6.26.0" + babel-traverse "^6.26.0" + babel-types "^6.26.0" + lodash "^4.17.4" + +babel-plugin-transform-es2015-classes@^6.24.1, babel-plugin-transform-es2015-classes@^6.9.0: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-classes/-/babel-plugin-transform-es2015-classes-6.24.1.tgz#5a4c58a50c9c9461e564b4b2a3bfabc97a2584db" + dependencies: + babel-helper-define-map "^6.24.1" + babel-helper-function-name "^6.24.1" + babel-helper-optimise-call-expression "^6.24.1" + babel-helper-replace-supers "^6.24.1" + babel-messages "^6.23.0" + babel-runtime "^6.22.0" + babel-template "^6.24.1" + babel-traverse "^6.24.1" + babel-types "^6.24.1" + +babel-plugin-transform-es2015-computed-properties@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-computed-properties/-/babel-plugin-transform-es2015-computed-properties-6.24.1.tgz#6fe2a8d16895d5634f4cd999b6d3480a308159b3" + dependencies: + babel-runtime "^6.22.0" + babel-template "^6.24.1" + +babel-plugin-transform-es2015-destructuring@^6.22.0: + version "6.23.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-destructuring/-/babel-plugin-transform-es2015-destructuring-6.23.0.tgz#997bb1f1ab967f682d2b0876fe358d60e765c56d" + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-transform-es2015-duplicate-keys@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-duplicate-keys/-/babel-plugin-transform-es2015-duplicate-keys-6.24.1.tgz#73eb3d310ca969e3ef9ec91c53741a6f1576423e" + dependencies: + babel-runtime "^6.22.0" + babel-types "^6.24.1" + +babel-plugin-transform-es2015-for-of@^6.22.0: + version "6.23.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-for-of/-/babel-plugin-transform-es2015-for-of-6.23.0.tgz#f47c95b2b613df1d3ecc2fdb7573623c75248691" + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-transform-es2015-function-name@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-function-name/-/babel-plugin-transform-es2015-function-name-6.24.1.tgz#834c89853bc36b1af0f3a4c5dbaa94fd8eacaa8b" + dependencies: + babel-helper-function-name "^6.24.1" + babel-runtime "^6.22.0" + babel-types "^6.24.1" + +babel-plugin-transform-es2015-literals@^6.22.0: + version "6.22.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-literals/-/babel-plugin-transform-es2015-literals-6.22.0.tgz#4f54a02d6cd66cf915280019a31d31925377ca2e" + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-transform-es2015-modules-amd@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-modules-amd/-/babel-plugin-transform-es2015-modules-amd-6.24.1.tgz#3b3e54017239842d6d19c3011c4bd2f00a00d154" + dependencies: + babel-plugin-transform-es2015-modules-commonjs "^6.24.1" + babel-runtime "^6.22.0" + babel-template "^6.24.1" + +babel-plugin-transform-es2015-modules-commonjs@^6.24.1: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-modules-commonjs/-/babel-plugin-transform-es2015-modules-commonjs-6.26.0.tgz#0d8394029b7dc6abe1a97ef181e00758dd2e5d8a" + dependencies: + babel-plugin-transform-strict-mode "^6.24.1" + babel-runtime "^6.26.0" + babel-template "^6.26.0" + babel-types "^6.26.0" + +babel-plugin-transform-es2015-modules-systemjs@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-modules-systemjs/-/babel-plugin-transform-es2015-modules-systemjs-6.24.1.tgz#ff89a142b9119a906195f5f106ecf305d9407d23" + dependencies: + babel-helper-hoist-variables "^6.24.1" + babel-runtime "^6.22.0" + babel-template "^6.24.1" + +babel-plugin-transform-es2015-modules-umd@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-modules-umd/-/babel-plugin-transform-es2015-modules-umd-6.24.1.tgz#ac997e6285cd18ed6176adb607d602344ad38468" + dependencies: + babel-plugin-transform-es2015-modules-amd "^6.24.1" + babel-runtime "^6.22.0" + babel-template "^6.24.1" + +babel-plugin-transform-es2015-object-super@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-object-super/-/babel-plugin-transform-es2015-object-super-6.24.1.tgz#24cef69ae21cb83a7f8603dad021f572eb278f8d" + dependencies: + babel-helper-replace-supers "^6.24.1" + babel-runtime "^6.22.0" + +babel-plugin-transform-es2015-parameters@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-parameters/-/babel-plugin-transform-es2015-parameters-6.24.1.tgz#57ac351ab49caf14a97cd13b09f66fdf0a625f2b" + dependencies: + babel-helper-call-delegate "^6.24.1" + babel-helper-get-function-arity "^6.24.1" + babel-runtime "^6.22.0" + babel-template "^6.24.1" + babel-traverse "^6.24.1" + babel-types "^6.24.1" + +babel-plugin-transform-es2015-shorthand-properties@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-shorthand-properties/-/babel-plugin-transform-es2015-shorthand-properties-6.24.1.tgz#24f875d6721c87661bbd99a4622e51f14de38aa0" + dependencies: + babel-runtime "^6.22.0" + babel-types "^6.24.1" + +babel-plugin-transform-es2015-spread@^6.22.0: + version "6.22.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-spread/-/babel-plugin-transform-es2015-spread-6.22.0.tgz#d6d68a99f89aedc4536c81a542e8dd9f1746f8d1" + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-transform-es2015-sticky-regex@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-sticky-regex/-/babel-plugin-transform-es2015-sticky-regex-6.24.1.tgz#00c1cdb1aca71112cdf0cf6126c2ed6b457ccdbc" + dependencies: + babel-helper-regex "^6.24.1" + babel-runtime "^6.22.0" + babel-types "^6.24.1" + +babel-plugin-transform-es2015-template-literals@^6.22.0: + version "6.22.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-template-literals/-/babel-plugin-transform-es2015-template-literals-6.22.0.tgz#a84b3450f7e9f8f1f6839d6d687da84bb1236d8d" + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-transform-es2015-typeof-symbol@^6.22.0: + version "6.23.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-typeof-symbol/-/babel-plugin-transform-es2015-typeof-symbol-6.23.0.tgz#dec09f1cddff94b52ac73d505c84df59dcceb372" + dependencies: + babel-runtime "^6.22.0" + +babel-plugin-transform-es2015-unicode-regex@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-unicode-regex/-/babel-plugin-transform-es2015-unicode-regex-6.24.1.tgz#d38b12f42ea7323f729387f18a7c5ae1faeb35e9" + dependencies: + babel-helper-regex "^6.24.1" + babel-runtime "^6.22.0" + regexpu-core "^2.0.0" + +babel-plugin-transform-exponentiation-operator@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-exponentiation-operator/-/babel-plugin-transform-exponentiation-operator-6.24.1.tgz#2ab0c9c7f3098fa48907772bb813fe41e8de3a0e" + dependencies: + babel-helper-builder-binary-assignment-operator-visitor "^6.24.1" + babel-plugin-syntax-exponentiation-operator "^6.8.0" + babel-runtime "^6.22.0" + +babel-plugin-transform-regenerator@^6.24.1: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-regenerator/-/babel-plugin-transform-regenerator-6.26.0.tgz#e0703696fbde27f0a3efcacf8b4dca2f7b3a8f2f" + dependencies: + regenerator-transform "^0.10.0" + +babel-plugin-transform-strict-mode@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-strict-mode/-/babel-plugin-transform-strict-mode-6.24.1.tgz#d5faf7aa578a65bbe591cf5edae04a0c67020758" + dependencies: + babel-runtime "^6.22.0" + babel-types "^6.24.1" + +babel-polyfill@^6.26.0: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-polyfill/-/babel-polyfill-6.26.0.tgz#379937abc67d7895970adc621f284cd966cf2153" + integrity sha1-N5k3q8Z9eJWXCtxiHyhM2WbPIVM= + dependencies: + babel-runtime "^6.26.0" + core-js "^2.5.0" + regenerator-runtime "^0.10.5" + +babel-preset-es2015@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-preset-es2015/-/babel-preset-es2015-6.24.1.tgz#d44050d6bc2c9feea702aaf38d727a0210538939" + dependencies: + babel-plugin-check-es2015-constants "^6.22.0" + babel-plugin-transform-es2015-arrow-functions "^6.22.0" + babel-plugin-transform-es2015-block-scoped-functions "^6.22.0" + babel-plugin-transform-es2015-block-scoping "^6.24.1" + babel-plugin-transform-es2015-classes "^6.24.1" + babel-plugin-transform-es2015-computed-properties "^6.24.1" + babel-plugin-transform-es2015-destructuring "^6.22.0" + babel-plugin-transform-es2015-duplicate-keys "^6.24.1" + babel-plugin-transform-es2015-for-of "^6.22.0" + babel-plugin-transform-es2015-function-name "^6.24.1" + babel-plugin-transform-es2015-literals "^6.22.0" + babel-plugin-transform-es2015-modules-amd "^6.24.1" + babel-plugin-transform-es2015-modules-commonjs "^6.24.1" + babel-plugin-transform-es2015-modules-systemjs "^6.24.1" + babel-plugin-transform-es2015-modules-umd "^6.24.1" + babel-plugin-transform-es2015-object-super "^6.24.1" + babel-plugin-transform-es2015-parameters "^6.24.1" + babel-plugin-transform-es2015-shorthand-properties "^6.24.1" + babel-plugin-transform-es2015-spread "^6.22.0" + babel-plugin-transform-es2015-sticky-regex "^6.24.1" + babel-plugin-transform-es2015-template-literals "^6.22.0" + babel-plugin-transform-es2015-typeof-symbol "^6.22.0" + babel-plugin-transform-es2015-unicode-regex "^6.24.1" + babel-plugin-transform-regenerator "^6.24.1" + +babel-preset-es2016@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-preset-es2016/-/babel-preset-es2016-6.24.1.tgz#f900bf93e2ebc0d276df9b8ab59724ebfd959f8b" + dependencies: + babel-plugin-transform-exponentiation-operator "^6.24.1" + +babel-preset-es2017@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-preset-es2017/-/babel-preset-es2017-6.24.1.tgz#597beadfb9f7f208bcfd8a12e9b2b29b8b2f14d1" + dependencies: + babel-plugin-syntax-trailing-function-commas "^6.22.0" + babel-plugin-transform-async-to-generator "^6.24.1" + +babel-preset-latest@^6.24.1: + version "6.24.1" + resolved "https://registry.yarnpkg.com/babel-preset-latest/-/babel-preset-latest-6.24.1.tgz#677de069154a7485c2d25c577c02f624b85b85e8" + dependencies: + babel-preset-es2015 "^6.24.1" + babel-preset-es2016 "^6.24.1" + babel-preset-es2017 "^6.24.1" + +babel-register@^6.26.0: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-register/-/babel-register-6.26.0.tgz#6ed021173e2fcb486d7acb45c6009a856f647071" + integrity sha1-btAhFz4vy0htestFxgCahW9kcHE= + dependencies: + babel-core "^6.26.0" + babel-runtime "^6.26.0" + core-js "^2.5.0" + home-or-tmp "^2.0.0" + lodash "^4.17.4" + mkdirp "^0.5.1" + source-map-support "^0.4.15" + +babel-runtime@^6.18.0, babel-runtime@^6.22.0, babel-runtime@^6.26.0: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-runtime/-/babel-runtime-6.26.0.tgz#965c7058668e82b55d7bfe04ff2337bc8b5647fe" + integrity sha1-llxwWGaOgrVde/4E/yM3vItWR/4= + dependencies: + core-js "^2.4.0" + regenerator-runtime "^0.11.0" + +babel-template@^6.24.1, babel-template@^6.26.0: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-template/-/babel-template-6.26.0.tgz#de03e2d16396b069f46dd9fff8521fb1a0e35e02" + integrity sha1-3gPi0WOWsGn0bdn/+FIfsaDjXgI= + dependencies: + babel-runtime "^6.26.0" + babel-traverse "^6.26.0" + babel-types "^6.26.0" + babylon "^6.18.0" + lodash "^4.17.4" + +babel-traverse@^6.24.1, babel-traverse@^6.26.0: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-traverse/-/babel-traverse-6.26.0.tgz#46a9cbd7edcc62c8e5c064e2d2d8d0f4035766ee" + dependencies: + babel-code-frame "^6.26.0" + babel-messages "^6.23.0" + babel-runtime "^6.26.0" + babel-types "^6.26.0" + babylon "^6.18.0" + debug "^2.6.8" + globals "^9.18.0" + invariant "^2.2.2" + lodash "^4.17.4" + +babel-types@^6.19.0, babel-types@^6.24.1, babel-types@^6.26.0: + version "6.26.0" + resolved "https://registry.yarnpkg.com/babel-types/-/babel-types-6.26.0.tgz#a3b073f94ab49eb6fa55cd65227a334380632497" + dependencies: + babel-runtime "^6.26.0" + esutils "^2.0.2" + lodash "^4.17.4" + to-fast-properties "^1.0.3" + +babylon@^6.18.0: + version "6.18.0" + resolved "https://registry.yarnpkg.com/babylon/-/babylon-6.18.0.tgz#af2f3b88fa6f5c1e4c634d1a0f8eac4f55b395e3" + integrity sha512-q/UEjfGJ2Cm3oKV71DJz9d25TPnq5rhBVL2Q4fA5wcC3jcrdn7+SssEybFIxwAvvP+YCsCYNKughoF33GxgycQ== + +balanced-match@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" + integrity sha1-ibTRmasr7kneFk6gK4nORi1xt2c= + +base@^0.11.1: + version "0.11.2" + resolved "https://registry.yarnpkg.com/base/-/base-0.11.2.tgz#7bde5ced145b6d551a90db87f83c558b4eb48a8f" + integrity sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg== + dependencies: + cache-base "^1.0.1" + class-utils "^0.3.5" + component-emitter "^1.2.1" + define-property "^1.0.0" + isobject "^3.0.1" + mixin-deep "^1.2.0" + pascalcase "^0.1.1" + +binary-extensions@^1.0.0: + version "1.13.1" + resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-1.13.1.tgz#598afe54755b2868a5330d2aff9d4ebb53209b65" + integrity sha512-Un7MIEDdUC5gNpcGDV97op1Ywk748MpHcFTHoYs6qnj1Z3j7I53VG3nwZhKzoBZmbdRNnb6WRdFlwl7tSDuZGw== + +binary-extensions@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-2.1.0.tgz#30fa40c9e7fe07dbc895678cd287024dea241dd9" + integrity sha512-1Yj8h9Q+QDF5FzhMs/c9+6UntbD5MkRfRwac8DoEm9ZfUBZ7tZ55YcGVAzEe4bXsdQHEk+s9S5wsOKVdZrw0tQ== + +bindings@^1.5.0: + version "1.5.0" + resolved "https://registry.yarnpkg.com/bindings/-/bindings-1.5.0.tgz#10353c9e945334bc0511a6d90b38fbc7c9c504df" + integrity sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ== + dependencies: + file-uri-to-path "1.0.0" + +brace-expansion@^1.1.7: + version "1.1.11" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" + integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA== + dependencies: + balanced-match "^1.0.0" + concat-map "0.0.1" + +braces@^1.8.2: + version "1.8.5" + resolved "https://registry.yarnpkg.com/braces/-/braces-1.8.5.tgz#ba77962e12dff969d6b76711e914b737857bf6a7" + integrity sha1-uneWLhLf+WnWt2cR6RS3N4V79qc= + dependencies: + expand-range "^1.8.1" + preserve "^0.2.0" + repeat-element "^1.1.2" + +braces@^2.3.1: + version "2.3.2" + resolved "https://registry.yarnpkg.com/braces/-/braces-2.3.2.tgz#5979fd3f14cd531565e5fa2df1abfff1dfaee729" + integrity sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w== + dependencies: + arr-flatten "^1.1.0" + array-unique "^0.3.2" + extend-shallow "^2.0.1" + fill-range "^4.0.0" + isobject "^3.0.1" + repeat-element "^1.1.2" + snapdragon "^0.8.1" + snapdragon-node "^2.0.1" + split-string "^3.0.2" + to-regex "^3.0.1" + +braces@~3.0.2: + version "3.0.2" + resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.2.tgz#3454e1a462ee8d599e236df336cd9ea4f8afe107" + integrity sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A== + dependencies: + fill-range "^7.0.1" + +browser-resolve@^1.11.0: + version "1.11.2" + resolved "https://registry.yarnpkg.com/browser-resolve/-/browser-resolve-1.11.2.tgz#8ff09b0a2c421718a1051c260b32e48f442938ce" + dependencies: + resolve "1.1.7" + +browser-stdout@1.3.1: + version "1.3.1" + resolved "https://registry.yarnpkg.com/browser-stdout/-/browser-stdout-1.3.1.tgz#baa559ee14ced73452229bad7326467c61fabd60" + integrity sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw== + +buffer-crc32@^0.2.5: + version "0.2.13" + resolved "https://registry.yarnpkg.com/buffer-crc32/-/buffer-crc32-0.2.13.tgz#0d333e3f00eac50aa1454abd30ef8c2a5d9a7242" + +builtin-modules@^1.1.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/builtin-modules/-/builtin-modules-1.1.1.tgz#270f076c5a72c02f5b65a47df94c5fe3a278892f" + +cache-base@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/cache-base/-/cache-base-1.0.1.tgz#0a7f46416831c8b662ee36fe4e7c59d76f666ab2" + integrity sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ== + dependencies: + collection-visit "^1.0.0" + component-emitter "^1.2.1" + get-value "^2.0.6" + has-value "^1.0.0" + isobject "^3.0.1" + set-value "^2.0.0" + to-object-path "^0.3.0" + union-value "^1.0.0" + unset-value "^1.0.0" + +camelcase@^1.0.2: + version "1.2.1" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-1.2.1.tgz#9bb5304d2e0b56698b2c758b08a3eaa9daa58a39" + +camelcase@^5.0.0: + version "5.3.1" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-5.3.1.tgz#e3c9b31569e106811df242f715725a1f4c494320" + integrity sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg== + +camelcase@^6.0.0: + version "6.2.0" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-6.2.0.tgz#924af881c9d525ac9d87f40d964e5cea982a1809" + integrity sha512-c7wVvbw3f37nuobQNtgsgG9POC9qMbNuMQmTCqZv23b6MIz0fcYpBiOlv9gEN/hdLdnZTDQhg6e9Dq5M1vKvfg== + +center-align@^0.1.1: + version "0.1.3" + resolved "https://registry.yarnpkg.com/center-align/-/center-align-0.1.3.tgz#aa0d32629b6ee972200411cbd4461c907bc2b7ad" + dependencies: + align-text "^0.1.3" + lazy-cache "^1.0.3" + +chalk@^1.1.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98" + integrity sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg= + dependencies: + ansi-styles "^2.2.1" + escape-string-regexp "^1.0.2" + has-ansi "^2.0.0" + strip-ansi "^3.0.0" + supports-color "^2.0.0" + +chalk@^4.0.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.0.tgz#4e14870a618d9e2edd97dd8345fd9d9dc315646a" + integrity sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A== + dependencies: + ansi-styles "^4.1.0" + supports-color "^7.1.0" + +chokidar@3.4.3: + version "3.4.3" + resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-3.4.3.tgz#c1df38231448e45ca4ac588e6c79573ba6a57d5b" + integrity sha512-DtM3g7juCXQxFVSNPNByEC2+NImtBuxQQvWlHunpJIS5Ocr0lG306cC7FCi7cEA0fzmybPUIl4txBIobk1gGOQ== + dependencies: + anymatch "~3.1.1" + braces "~3.0.2" + glob-parent "~5.1.0" + is-binary-path "~2.1.0" + is-glob "~4.0.1" + normalize-path "~3.0.0" + readdirp "~3.5.0" + optionalDependencies: + fsevents "~2.1.2" + +chokidar@^1.6.1: + version "1.7.0" + resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-1.7.0.tgz#798e689778151c8076b4b360e5edd28cda2bb468" + integrity sha1-eY5ol3gVHIB2tLNg5e3SjNortGg= + dependencies: + anymatch "^1.3.0" + async-each "^1.0.0" + glob-parent "^2.0.0" + inherits "^2.0.1" + is-binary-path "^1.0.0" + is-glob "^2.0.0" + path-is-absolute "^1.0.0" + readdirp "^2.0.0" + optionalDependencies: + fsevents "^1.0.0" + +class-utils@^0.3.5: + version "0.3.6" + resolved "https://registry.yarnpkg.com/class-utils/-/class-utils-0.3.6.tgz#f93369ae8b9a7ce02fd41faad0ca83033190c463" + integrity sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg== + dependencies: + arr-union "^3.1.0" + define-property "^0.2.5" + isobject "^3.0.0" + static-extend "^0.1.1" + +cliui@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/cliui/-/cliui-2.1.0.tgz#4b475760ff80264c762c3a1719032e91c7fea0d1" + dependencies: + center-align "^0.1.1" + right-align "^0.1.1" + wordwrap "0.0.2" + +cliui@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/cliui/-/cliui-5.0.0.tgz#deefcfdb2e800784aa34f46fa08e06851c7bbbc5" + integrity sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA== + dependencies: + string-width "^3.1.0" + strip-ansi "^5.2.0" + wrap-ansi "^5.1.0" + +collection-visit@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/collection-visit/-/collection-visit-1.0.0.tgz#4bc0373c164bc3291b4d368c829cf1a80a59dca0" + integrity sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA= + dependencies: + map-visit "^1.0.0" + object-visit "^1.0.0" + +color-convert@^1.9.0: + version "1.9.3" + resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8" + integrity sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg== + dependencies: + color-name "1.1.3" + +color-convert@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-2.0.1.tgz#72d3a68d598c9bdb3af2ad1e84f21d896abd4de3" + integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ== + dependencies: + color-name "~1.1.4" + +color-name@1.1.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25" + integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU= + +color-name@~1.1.4: + version "1.1.4" + resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" + integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== + +commander@^2.11.0: + version "2.20.3" + resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" + integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== + +component-emitter@^1.2.1: + version "1.3.0" + resolved "https://registry.yarnpkg.com/component-emitter/-/component-emitter-1.3.0.tgz#16e4070fba8ae29b679f2215853ee181ab2eabc0" + integrity sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg== + +concat-map@0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" + integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s= + +convert-source-map@^1.5.0, convert-source-map@^1.5.1: + version "1.7.0" + resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.7.0.tgz#17a2cb882d7f77d3490585e2ce6c524424a3a442" + integrity sha512-4FJkXzKXEDB1snCFZlLP4gpC3JILicCpGbzG9f9G7tGqGCzETQ2hWPrcinA9oU4wtf2biUaEH5065UnMeR33oA== + dependencies: + safe-buffer "~5.1.1" + +copy-descriptor@^0.1.0: + version "0.1.1" + resolved "https://registry.yarnpkg.com/copy-descriptor/-/copy-descriptor-0.1.1.tgz#676f6eb3c39997c2ee1ac3a924fd6124748f578d" + integrity sha1-Z29us8OZl8LuGsOpJP1hJHSPV40= + +core-js@^2.4.0, core-js@^2.5.0: + version "2.6.12" + resolved "https://registry.yarnpkg.com/core-js/-/core-js-2.6.12.tgz#d9333dfa7b065e347cc5682219d6f690859cc2ec" + integrity sha512-Kb2wC0fvsWfQrgk8HU5lW6U/Lcs8+9aaYcy4ZFc6DDlo4nZ7n70dEgE5rtR0oG6ufKDUnrwfWL1mXR5ljDatrQ== + +core-util-is@~1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" + integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac= + +debug@4.2.0: + version "4.2.0" + resolved "https://registry.yarnpkg.com/debug/-/debug-4.2.0.tgz#7f150f93920e94c58f5574c2fd01a3110effe7f1" + integrity sha512-IX2ncY78vDTjZMFUdmsvIRFY2Cf4FnD0wRs+nQwJU8Lu99/tPFdb0VybiiMTPe3I6rQmwsqQqRBvxU+bZ/I8sg== + dependencies: + ms "2.1.2" + +debug@^2.2.0, debug@^2.3.3, debug@^2.6.8, debug@^2.6.9: + version "2.6.9" + resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" + integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA== + dependencies: + ms "2.0.0" + +decamelize@^1.0.0, decamelize@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" + +decamelize@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-4.0.0.tgz#aa472d7bf660eb15f3494efd531cab7f2a709837" + integrity sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ== + +decode-uri-component@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/decode-uri-component/-/decode-uri-component-0.2.0.tgz#eb3913333458775cb84cd1a1fae062106bb87545" + integrity sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU= + +define-property@^0.2.5: + version "0.2.5" + resolved "https://registry.yarnpkg.com/define-property/-/define-property-0.2.5.tgz#c35b1ef918ec3c990f9a5bc57be04aacec5c8116" + integrity sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY= + dependencies: + is-descriptor "^0.1.0" + +define-property@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/define-property/-/define-property-1.0.0.tgz#769ebaaf3f4a63aad3af9e8d304c9bbe79bfb0e6" + integrity sha1-dp66rz9KY6rTr56NMEybvnm/sOY= + dependencies: + is-descriptor "^1.0.0" + +define-property@^2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/define-property/-/define-property-2.0.2.tgz#d459689e8d654ba77e02a817f8710d702cb16e9d" + integrity sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ== + dependencies: + is-descriptor "^1.0.2" + isobject "^3.0.1" + +detect-indent@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/detect-indent/-/detect-indent-4.0.0.tgz#f76d064352cdf43a1cb6ce619c4ee3a9475de208" + integrity sha1-920GQ1LN9Docts5hnE7jqUdd4gg= + dependencies: + repeating "^2.0.0" + +diff@4.0.2: + version "4.0.2" + resolved "https://registry.yarnpkg.com/diff/-/diff-4.0.2.tgz#60f3aecb89d5fae520c11aa19efc2bb982aade7d" + integrity sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A== + +emoji-regex@^7.0.1: + version "7.0.3" + resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-7.0.3.tgz#933a04052860c85e83c122479c4748a8e4c72156" + integrity sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA== + +es6-promise@^3.1.2: + version "3.3.1" + resolved "https://registry.yarnpkg.com/es6-promise/-/es6-promise-3.3.1.tgz#a08cdde84ccdbf34d027a1451bc91d4bcd28a613" + +escape-string-regexp@4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34" + integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA== + +escape-string-regexp@^1.0.2: + version "1.0.5" + resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" + integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= + +esprima@^4.0.0: + version "4.0.1" + resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.1.tgz#13b04cdb3e6c5d19df91ab6987a8695619b0aa71" + integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A== + +estree-walker@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/estree-walker/-/estree-walker-0.2.1.tgz#bdafe8095383d8414d5dc2ecf4c9173b6db9412e" + +esutils@^2.0.2: + version "2.0.3" + resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64" + integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g== + +expand-brackets@^0.1.4: + version "0.1.5" + resolved "https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-0.1.5.tgz#df07284e342a807cd733ac5af72411e581d1177b" + integrity sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s= + dependencies: + is-posix-bracket "^0.1.0" + +expand-brackets@^2.1.4: + version "2.1.4" + resolved "https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-2.1.4.tgz#b77735e315ce30f6b6eff0f83b04151a22449622" + integrity sha1-t3c14xXOMPa27/D4OwQVGiJEliI= + dependencies: + debug "^2.3.3" + define-property "^0.2.5" + extend-shallow "^2.0.1" + posix-character-classes "^0.1.0" + regex-not "^1.0.0" + snapdragon "^0.8.1" + to-regex "^3.0.1" + +expand-range@^1.8.1: + version "1.8.2" + resolved "https://registry.yarnpkg.com/expand-range/-/expand-range-1.8.2.tgz#a299effd335fe2721ebae8e257ec79644fc85337" + integrity sha1-opnv/TNf4nIeuujiV+x5ZE/IUzc= + dependencies: + fill-range "^2.1.0" + +extend-shallow@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-2.0.1.tgz#51af7d614ad9a9f610ea1bafbb989d6b1c56890f" + integrity sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8= + dependencies: + is-extendable "^0.1.0" + +extend-shallow@^3.0.0, extend-shallow@^3.0.2: + version "3.0.2" + resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-3.0.2.tgz#26a71aaf073b39fb2127172746131c2704028db8" + integrity sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg= + dependencies: + assign-symbols "^1.0.0" + is-extendable "^1.0.1" + +extglob@^0.3.1: + version "0.3.2" + resolved "https://registry.yarnpkg.com/extglob/-/extglob-0.3.2.tgz#2e18ff3d2f49ab2765cec9023f011daa8d8349a1" + integrity sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE= + dependencies: + is-extglob "^1.0.0" + +extglob@^2.0.4: + version "2.0.4" + resolved "https://registry.yarnpkg.com/extglob/-/extglob-2.0.4.tgz#ad00fe4dc612a9232e8718711dc5cb5ab0285543" + integrity sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw== + dependencies: + array-unique "^0.3.2" + define-property "^1.0.0" + expand-brackets "^2.1.4" + extend-shallow "^2.0.1" + fragment-cache "^0.2.1" + regex-not "^1.0.0" + snapdragon "^0.8.1" + to-regex "^3.0.1" + +file-uri-to-path@1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz#553a7b8446ff6f684359c445f1e37a05dacc33dd" + integrity sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw== + +filename-regex@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/filename-regex/-/filename-regex-2.0.1.tgz#c1c4b9bee3e09725ddb106b75c1e301fe2f18b26" + integrity sha1-wcS5vuPglyXdsQa3XB4wH+LxiyY= + +fill-range@^2.1.0: + version "2.2.4" + resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-2.2.4.tgz#eb1e773abb056dcd8df2bfdf6af59b8b3a936565" + integrity sha512-cnrcCbj01+j2gTG921VZPnHbjmdAf8oQV/iGeV2kZxGSyfYjjTyY79ErsK1WJWMpw6DaApEX72binqJE+/d+5Q== + dependencies: + is-number "^2.1.0" + isobject "^2.0.0" + randomatic "^3.0.0" + repeat-element "^1.1.2" + repeat-string "^1.5.2" + +fill-range@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-4.0.0.tgz#d544811d428f98eb06a63dc402d2403c328c38f7" + integrity sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc= + dependencies: + extend-shallow "^2.0.1" + is-number "^3.0.0" + repeat-string "^1.6.1" + to-regex-range "^2.1.0" + +fill-range@^7.0.1: + version "7.0.1" + resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.0.1.tgz#1919a6a7c75fe38b2c7c77e5198535da9acdda40" + integrity sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ== + dependencies: + to-regex-range "^5.0.1" + +find-up@5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/find-up/-/find-up-5.0.0.tgz#4c92819ecb7083561e4f4a240a86be5198f536fc" + integrity sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng== + dependencies: + locate-path "^6.0.0" + path-exists "^4.0.0" + +find-up@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/find-up/-/find-up-3.0.0.tgz#49169f1d7993430646da61ecc5ae355c21c97b73" + integrity sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg== + dependencies: + locate-path "^3.0.0" + +flat@^5.0.2: + version "5.0.2" + resolved "https://registry.yarnpkg.com/flat/-/flat-5.0.2.tgz#8ca6fe332069ffa9d324c327198c598259ceb241" + integrity sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ== + +for-in@^1.0.1, for-in@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/for-in/-/for-in-1.0.2.tgz#81068d295a8142ec0ac726c6e2200c30fb6d5e80" + integrity sha1-gQaNKVqBQuwKxybG4iAMMPttXoA= + +for-own@^0.1.4: + version "0.1.5" + resolved "https://registry.yarnpkg.com/for-own/-/for-own-0.1.5.tgz#5265c681a4f294dabbf17c9509b6763aa84510ce" + integrity sha1-UmXGgaTylNq78XyVCbZ2OqhFEM4= + dependencies: + for-in "^1.0.1" + +fragment-cache@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/fragment-cache/-/fragment-cache-0.2.1.tgz#4290fad27f13e89be7f33799c6bc5a0abfff0d19" + integrity sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk= + dependencies: + map-cache "^0.2.2" + +fs-readdir-recursive@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/fs-readdir-recursive/-/fs-readdir-recursive-1.1.0.tgz#e32fc030a2ccee44a6b5371308da54be0b397d27" + integrity sha512-GNanXlVr2pf02+sPN40XN8HG+ePaNcvM0q5mZBd668Obwb0yD5GiUbZOFgwn8kGMY6I3mdyDJzieUy3PTYyTRA== + +fs.realpath@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" + integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8= + +fsevents@^1.0.0: + version "1.2.13" + resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-1.2.13.tgz#f325cb0455592428bcf11b383370ef70e3bfcc38" + integrity sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw== + dependencies: + bindings "^1.5.0" + nan "^2.12.1" + +fsevents@~2.1.2: + version "2.1.3" + resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.1.3.tgz#fb738703ae8d2f9fe900c33836ddebee8b97f23e" + integrity sha512-Auw9a4AxqWpa9GUfj370BMPzzyncfBABW8Mab7BGWBYDj4Isgq+cDKtx0i6u9jcX9pQDnswsaaOTgTmA5pEjuQ== + +get-caller-file@^2.0.1: + version "2.0.5" + resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e" + integrity sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg== + +get-value@^2.0.3, get-value@^2.0.6: + version "2.0.6" + resolved "https://registry.yarnpkg.com/get-value/-/get-value-2.0.6.tgz#dc15ca1c672387ca76bd37ac0a395ba2042a2c28" + integrity sha1-3BXKHGcjh8p2vTesCjlbogQqLCg= + +glob-base@^0.3.0: + version "0.3.0" + resolved "https://registry.yarnpkg.com/glob-base/-/glob-base-0.3.0.tgz#dbb164f6221b1c0b1ccf82aea328b497df0ea3c4" + integrity sha1-27Fk9iIbHAscz4Kuoyi0l98Oo8Q= + dependencies: + glob-parent "^2.0.0" + is-glob "^2.0.0" + +glob-parent@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-2.0.0.tgz#81383d72db054fcccf5336daa902f182f6edbb28" + integrity sha1-gTg9ctsFT8zPUzbaqQLxgvbtuyg= + dependencies: + is-glob "^2.0.0" + +glob-parent@~5.1.0: + version "5.1.1" + resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.1.tgz#b6c1ef417c4e5663ea498f1c45afac6916bbc229" + integrity sha512-FnI+VGOpnlGHWZxthPGR+QhR78fuiK0sNLkHQv+bL9fQi57lNNdquIbna/WrfROrolq8GK5Ek6BiMwqL/voRYQ== + dependencies: + is-glob "^4.0.1" + +glob@7.1.6, glob@^7.1.2, glob@^7.1.3: + version "7.1.6" + resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.6.tgz#141f33b81a7c2492e125594307480c46679278a6" + integrity sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA== + dependencies: + fs.realpath "^1.0.0" + inflight "^1.0.4" + inherits "2" + minimatch "^3.0.4" + once "^1.3.0" + path-is-absolute "^1.0.0" + +globals@^9.18.0: + version "9.18.0" + resolved "https://registry.yarnpkg.com/globals/-/globals-9.18.0.tgz#aa3896b3e69b487f17e31ed2143d69a8e30c2d8a" + integrity sha512-S0nG3CLEQiY/ILxqtztTWH/3iRRdyBLw6KMDxnKMchrtbj2OFmehVh0WUCfW3DUrIgx/qFrJPICrq4Z4sTR9UQ== + +graceful-fs@^4.1.11, graceful-fs@^4.1.4: + version "4.2.4" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.4.tgz#2256bde14d3632958c465ebc96dc467ca07a29fb" + integrity sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw== + +graceful-fs@^4.1.3: + version "4.2.3" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.3.tgz#4a12ff1b60376ef09862c2093edd908328be8423" + +growl@1.10.5: + version "1.10.5" + resolved "https://registry.yarnpkg.com/growl/-/growl-1.10.5.tgz#f2735dc2283674fa67478b10181059355c369e5e" + integrity sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA== + +has-ansi@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/has-ansi/-/has-ansi-2.0.0.tgz#34f5049ce1ecdf2b0649af3ef24e45ed35416d91" + integrity sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE= + dependencies: + ansi-regex "^2.0.0" + +has-flag@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b" + integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ== + +has-value@^0.3.1: + version "0.3.1" + resolved "https://registry.yarnpkg.com/has-value/-/has-value-0.3.1.tgz#7b1f58bada62ca827ec0a2078025654845995e1f" + integrity sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8= + dependencies: + get-value "^2.0.3" + has-values "^0.1.4" + isobject "^2.0.0" + +has-value@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/has-value/-/has-value-1.0.0.tgz#18b281da585b1c5c51def24c930ed29a0be6b177" + integrity sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc= + dependencies: + get-value "^2.0.6" + has-values "^1.0.0" + isobject "^3.0.0" + +has-values@^0.1.4: + version "0.1.4" + resolved "https://registry.yarnpkg.com/has-values/-/has-values-0.1.4.tgz#6d61de95d91dfca9b9a02089ad384bff8f62b771" + integrity sha1-bWHeldkd/Km5oCCJrThL/49it3E= + +has-values@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/has-values/-/has-values-1.0.0.tgz#95b0b63fec2146619a6fe57fe75628d5a39efe4f" + integrity sha1-lbC2P+whRmGab+V/51Yo1aOe/k8= + dependencies: + is-number "^3.0.0" + kind-of "^4.0.0" + +he@1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/he/-/he-1.2.0.tgz#84ae65fa7eafb165fddb61566ae14baf05664f0f" + integrity sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw== + +home-or-tmp@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/home-or-tmp/-/home-or-tmp-2.0.0.tgz#e36c3f2d2cae7d746a857e38d18d5f32a7882db8" + integrity sha1-42w/LSyufXRqhX440Y1fMqeILbg= + dependencies: + os-homedir "^1.0.0" + os-tmpdir "^1.0.1" + +inflight@^1.0.4: + version "1.0.6" + resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" + integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk= + dependencies: + once "^1.3.0" + wrappy "1" + +inherits@2, inherits@^2.0.1, inherits@~2.0.3: + version "2.0.4" + resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" + integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== + +invariant@^2.2.2: + version "2.2.4" + resolved "https://registry.yarnpkg.com/invariant/-/invariant-2.2.4.tgz#610f3c92c9359ce1db616e538008d23ff35158e6" + integrity sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA== + dependencies: + loose-envify "^1.0.0" + +is-accessor-descriptor@^0.1.6: + version "0.1.6" + resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz#a9e12cb3ae8d876727eeef3843f8a0897b5c98d6" + integrity sha1-qeEss66Nh2cn7u84Q/igiXtcmNY= + dependencies: + kind-of "^3.0.2" + +is-accessor-descriptor@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz#169c2f6d3df1f992618072365c9b0ea1f6878656" + integrity sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ== + dependencies: + kind-of "^6.0.0" + +is-binary-path@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-1.0.1.tgz#75f16642b480f187a711c814161fd3a4a7655898" + integrity sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg= + dependencies: + binary-extensions "^1.0.0" + +is-binary-path@~2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-2.1.0.tgz#ea1f7f3b80f064236e83470f86c09c254fb45b09" + integrity sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw== + dependencies: + binary-extensions "^2.0.0" + +is-buffer@^1.1.5: + version "1.1.6" + resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be" + integrity sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w== + +is-data-descriptor@^0.1.4: + version "0.1.4" + resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz#0b5ee648388e2c860282e793f1856fec3f301b56" + integrity sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y= + dependencies: + kind-of "^3.0.2" + +is-data-descriptor@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz#d84876321d0e7add03990406abbbbd36ba9268c7" + integrity sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ== + dependencies: + kind-of "^6.0.0" + +is-descriptor@^0.1.0: + version "0.1.6" + resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-0.1.6.tgz#366d8240dde487ca51823b1ab9f07a10a78251ca" + integrity sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg== + dependencies: + is-accessor-descriptor "^0.1.6" + is-data-descriptor "^0.1.4" + kind-of "^5.0.0" + +is-descriptor@^1.0.0, is-descriptor@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-1.0.2.tgz#3b159746a66604b04f8c81524ba365c5f14d86ec" + integrity sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg== + dependencies: + is-accessor-descriptor "^1.0.0" + is-data-descriptor "^1.0.0" + kind-of "^6.0.2" + +is-dotfile@^1.0.0: + version "1.0.3" + resolved "https://registry.yarnpkg.com/is-dotfile/-/is-dotfile-1.0.3.tgz#a6a2f32ffd2dfb04f5ca25ecd0f6b83cf798a1e1" + integrity sha1-pqLzL/0t+wT1yiXs0Pa4PPeYoeE= + +is-equal-shallow@^0.1.3: + version "0.1.3" + resolved "https://registry.yarnpkg.com/is-equal-shallow/-/is-equal-shallow-0.1.3.tgz#2238098fc221de0bcfa5d9eac4c45d638aa1c534" + integrity sha1-IjgJj8Ih3gvPpdnqxMRdY4qhxTQ= + dependencies: + is-primitive "^2.0.0" + +is-extendable@^0.1.0, is-extendable@^0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-0.1.1.tgz#62b110e289a471418e3ec36a617d472e301dfc89" + integrity sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik= + +is-extendable@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-1.0.1.tgz#a7470f9e426733d81bd81e1155264e3a3507cab4" + integrity sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA== + dependencies: + is-plain-object "^2.0.4" + +is-extglob@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-1.0.0.tgz#ac468177c4943405a092fc8f29760c6ffc6206c0" + integrity sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA= + +is-extglob@^2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" + integrity sha1-qIwCU1eR8C7TfHahueqXc8gz+MI= + +is-finite@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/is-finite/-/is-finite-1.1.0.tgz#904135c77fb42c0641d6aa1bcdbc4daa8da082f3" + integrity sha512-cdyMtqX/BOqqNBBiKlIVkytNHm49MtMlYyn1zxzvJKWmFMlGzm+ry5BBfYyeY9YmNKbRSo/o7OX9w9ale0wg3w== + +is-fullwidth-code-point@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f" + integrity sha1-o7MKXE8ZkYMWeqq5O+764937ZU8= + +is-glob@^2.0.0, is-glob@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-2.0.1.tgz#d096f926a3ded5600f3fdfd91198cb0888c2d863" + integrity sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM= + dependencies: + is-extglob "^1.0.0" + +is-glob@^4.0.1, is-glob@~4.0.1: + version "4.0.1" + resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.1.tgz#7567dbe9f2f5e2467bc77ab83c4a29482407a5dc" + integrity sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg== + dependencies: + is-extglob "^2.1.1" + +is-number@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/is-number/-/is-number-2.1.0.tgz#01fcbbb393463a548f2f466cce16dece49db908f" + integrity sha1-Afy7s5NGOlSPL0ZszhbezknbkI8= + dependencies: + kind-of "^3.0.2" + +is-number@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/is-number/-/is-number-3.0.0.tgz#24fd6201a4782cf50561c810276afc7d12d71195" + integrity sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU= + dependencies: + kind-of "^3.0.2" + +is-number@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/is-number/-/is-number-4.0.0.tgz#0026e37f5454d73e356dfe6564699867c6a7f0ff" + integrity sha512-rSklcAIlf1OmFdyAqbnWTLVelsQ58uvZ66S/ZyawjWqIviTWCjg2PzVGw8WUA+nNuPTqb4wgA+NszrJ+08LlgQ== + +is-number@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" + integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== + +is-plain-obj@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/is-plain-obj/-/is-plain-obj-2.1.0.tgz#45e42e37fccf1f40da8e5f76ee21515840c09287" + integrity sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA== + +is-plain-object@^2.0.3, is-plain-object@^2.0.4: + version "2.0.4" + resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677" + integrity sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og== + dependencies: + isobject "^3.0.1" + +is-posix-bracket@^0.1.0: + version "0.1.1" + resolved "https://registry.yarnpkg.com/is-posix-bracket/-/is-posix-bracket-0.1.1.tgz#3334dc79774368e92f016e6fbc0a88f5cd6e6bc4" + integrity sha1-MzTceXdDaOkvAW5vvAqI9c1ua8Q= + +is-primitive@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/is-primitive/-/is-primitive-2.0.0.tgz#207bab91638499c07b2adf240a41a87210034575" + integrity sha1-IHurkWOEmcB7Kt8kCkGochADRXU= + +is-windows@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/is-windows/-/is-windows-1.0.2.tgz#d1850eb9791ecd18e6182ce12a30f396634bb19d" + integrity sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA== + +isarray@1.0.0, isarray@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" + integrity sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE= + +isexe@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" + integrity sha1-6PvzdNxVb/iUehDcsFctYz8s+hA= + +isobject@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/isobject/-/isobject-2.1.0.tgz#f065561096a3f1da2ef46272f815c840d87e0c89" + integrity sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk= + dependencies: + isarray "1.0.0" + +isobject@^3.0.0, isobject@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df" + integrity sha1-TkMekrEalzFjaqH5yNHMvP2reN8= + +"js-tokens@^3.0.0 || ^4.0.0": + version "4.0.0" + resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" + integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== + +js-tokens@^3.0.2: + version "3.0.2" + resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-3.0.2.tgz#9866df395102130e38f7f996bceb65443209c25b" + integrity sha1-mGbfOVECEw449/mWvOtlRDIJwls= + +js-yaml@3.14.0: + version "3.14.0" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.14.0.tgz#a7a34170f26a21bb162424d8adacb4113a69e482" + integrity sha512-/4IbIeHcD9VMHFqDR/gQ7EdZdLimOvW2DdcxFjdyyZ9NsbS+ccrXqVWDtab/lRl5AlUqmpBx8EhPaWR+OtY17A== + dependencies: + argparse "^1.0.7" + esprima "^4.0.0" + +jsesc@^1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-1.3.0.tgz#46c3fec8c1892b12b0833db9bc7622176dbab34b" + integrity sha1-RsP+yMGJKxKwgz25vHYiF226s0s= + +jsesc@~0.5.0: + version "0.5.0" + resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-0.5.0.tgz#e7dee66e35d6fc16f710fe91d5cf69f70f08911d" + +json5@^0.5.1: + version "0.5.1" + resolved "https://registry.yarnpkg.com/json5/-/json5-0.5.1.tgz#1eade7acc012034ad84e2396767ead9fa5495821" + integrity sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE= + +kind-of@^3.0.2, kind-of@^3.0.3, kind-of@^3.2.0: + version "3.2.2" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.2.2.tgz#31ea21a734bab9bbb0f32466d893aea51e4a3c64" + integrity sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ= + dependencies: + is-buffer "^1.1.5" + +kind-of@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-4.0.0.tgz#20813df3d712928b207378691a45066fae72dd57" + integrity sha1-IIE989cSkosgc3hpGkUGb65y3Vc= + dependencies: + is-buffer "^1.1.5" + +kind-of@^5.0.0: + version "5.1.0" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-5.1.0.tgz#729c91e2d857b7a419a1f9aa65685c4c33f5845d" + integrity sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw== + +kind-of@^6.0.0, kind-of@^6.0.2: + version "6.0.3" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd" + integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw== + +lazy-cache@^1.0.3: + version "1.0.4" + resolved "https://registry.yarnpkg.com/lazy-cache/-/lazy-cache-1.0.4.tgz#a1d78fc3a50474cb80845d3b3b6e1da49a446e8e" + +locate-path@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-3.0.0.tgz#dbec3b3ab759758071b58fe59fc41871af21400e" + integrity sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A== + dependencies: + p-locate "^3.0.0" + path-exists "^3.0.0" + +locate-path@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-6.0.0.tgz#55321eb309febbc59c4801d931a72452a681d286" + integrity sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw== + dependencies: + p-locate "^5.0.0" + +lodash@^4.17.4: + version "4.17.20" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.20.tgz#b44a9b6297bcb698f1c51a3545a2b3b368d59c52" + integrity sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA== + +log-symbols@4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-4.0.0.tgz#69b3cc46d20f448eccdb75ea1fa733d9e821c920" + integrity sha512-FN8JBzLx6CzeMrB0tg6pqlGU1wCrXW+ZXGH481kfsBqer0hToTIiHdjH4Mq8xJUbvATujKCvaREGWpGUionraA== + dependencies: + chalk "^4.0.0" + +longest@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/longest/-/longest-1.0.1.tgz#30a0b2da38f73770e8294a0d22e6625ed77d0097" + +loose-envify@^1.0.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.4.0.tgz#71ee51fa7be4caec1a63839f7e682d8132d30caf" + integrity sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q== + dependencies: + js-tokens "^3.0.0 || ^4.0.0" + +map-cache@^0.2.2: + version "0.2.2" + resolved "https://registry.yarnpkg.com/map-cache/-/map-cache-0.2.2.tgz#c32abd0bd6525d9b051645bb4f26ac5dc98a0dbf" + integrity sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8= + +map-visit@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/map-visit/-/map-visit-1.0.0.tgz#ecdca8f13144e660f1b5bd41f12f3479d98dfb8f" + integrity sha1-7Nyo8TFE5mDxtb1B8S80edmN+48= + dependencies: + object-visit "^1.0.0" + +math-random@^1.0.1: + version "1.0.4" + resolved "https://registry.yarnpkg.com/math-random/-/math-random-1.0.4.tgz#5dd6943c938548267016d4e34f057583080c514c" + integrity sha512-rUxjysqif/BZQH2yhd5Aaq7vXMSx9NdEsQcyA07uEzIvxgI7zIr33gGsh+RU0/XjmQpCW7RsVof1vlkvQVCK5A== + +micromatch@^2.1.5: + version "2.3.11" + resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-2.3.11.tgz#86677c97d1720b363431d04d0d15293bd38c1565" + integrity sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU= + dependencies: + arr-diff "^2.0.0" + array-unique "^0.2.1" + braces "^1.8.2" + expand-brackets "^0.1.4" + extglob "^0.3.1" + filename-regex "^2.0.0" + is-extglob "^1.0.0" + is-glob "^2.0.1" + kind-of "^3.0.2" + normalize-path "^2.0.1" + object.omit "^2.0.0" + parse-glob "^3.0.4" + regex-cache "^0.4.2" + +micromatch@^3.1.10: + version "3.1.10" + resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-3.1.10.tgz#70859bc95c9840952f359a068a3fc49f9ecfac23" + integrity sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg== + dependencies: + arr-diff "^4.0.0" + array-unique "^0.3.2" + braces "^2.3.1" + define-property "^2.0.2" + extend-shallow "^3.0.2" + extglob "^2.0.4" + fragment-cache "^0.2.1" + kind-of "^6.0.2" + nanomatch "^1.2.9" + object.pick "^1.3.0" + regex-not "^1.0.0" + snapdragon "^0.8.1" + to-regex "^3.0.2" + +minimatch@3.0.4, minimatch@^3.0.2, minimatch@^3.0.4: + version "3.0.4" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" + dependencies: + brace-expansion "^1.1.7" + +minimist@^1.2.0, minimist@^1.2.5: + version "1.2.5" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.5.tgz#67d66014b66a6a8aaa0c083c5fd58df4e4e97602" + integrity sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw== + +mixin-deep@^1.2.0: + version "1.3.2" + resolved "https://registry.yarnpkg.com/mixin-deep/-/mixin-deep-1.3.2.tgz#1120b43dc359a785dce65b55b82e257ccf479566" + integrity sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA== + dependencies: + for-in "^1.0.2" + is-extendable "^1.0.1" + +mkdirp@^0.5.1: + version "0.5.5" + resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.5.tgz#d91cefd62d1436ca0f41620e251288d420099def" + integrity sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ== + dependencies: + minimist "^1.2.5" + +mocha-qunit-ui@^0.1.3: + version "0.1.3" + resolved "https://registry.yarnpkg.com/mocha-qunit-ui/-/mocha-qunit-ui-0.1.3.tgz#e3e1ff1dac33222b10cef681efd7f82664141ea9" + +mocha@^8.2.1: + version "8.2.1" + resolved "https://registry.yarnpkg.com/mocha/-/mocha-8.2.1.tgz#f2fa68817ed0e53343d989df65ccd358bc3a4b39" + integrity sha512-cuLBVfyFfFqbNR0uUKbDGXKGk+UDFe6aR4os78XIrMQpZl/nv7JYHcvP5MFIAb374b2zFXsdgEGwmzMtP0Xg8w== + dependencies: + "@ungap/promise-all-settled" "1.1.2" + ansi-colors "4.1.1" + browser-stdout "1.3.1" + chokidar "3.4.3" + debug "4.2.0" + diff "4.0.2" + escape-string-regexp "4.0.0" + find-up "5.0.0" + glob "7.1.6" + growl "1.10.5" + he "1.2.0" + js-yaml "3.14.0" + log-symbols "4.0.0" + minimatch "3.0.4" + ms "2.1.2" + nanoid "3.1.12" + serialize-javascript "5.0.1" + strip-json-comments "3.1.1" + supports-color "7.2.0" + which "2.0.2" + wide-align "1.1.3" + workerpool "6.0.2" + yargs "13.3.2" + yargs-parser "13.1.2" + yargs-unparser "2.0.0" + +ms@2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" + integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g= + +ms@2.1.2: + version "2.1.2" + resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" + integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== + +nan@^2.12.1: + version "2.14.2" + resolved "https://registry.yarnpkg.com/nan/-/nan-2.14.2.tgz#f5376400695168f4cc694ac9393d0c9585eeea19" + integrity sha512-M2ufzIiINKCuDfBSAUr1vWQ+vuVcA9kqx8JJUsbQi6yf1uGRyb7HfpdfUr5qLXf3B/t8dPvcjhKMmlfnP47EzQ== + +nanoid@3.1.12: + version "3.1.12" + resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.1.12.tgz#6f7736c62e8d39421601e4a0c77623a97ea69654" + integrity sha512-1qstj9z5+x491jfiC4Nelk+f8XBad7LN20PmyWINJEMRSf3wcAjAWysw1qaA8z6NSKe2sjq1hRSDpBH5paCb6A== + +nanomatch@^1.2.9: + version "1.2.13" + resolved "https://registry.yarnpkg.com/nanomatch/-/nanomatch-1.2.13.tgz#b87a8aa4fc0de8fe6be88895b38983ff265bd119" + integrity sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA== + dependencies: + arr-diff "^4.0.0" + array-unique "^0.3.2" + define-property "^2.0.2" + extend-shallow "^3.0.2" + fragment-cache "^0.2.1" + is-windows "^1.0.2" + kind-of "^6.0.2" + object.pick "^1.3.0" + regex-not "^1.0.0" + snapdragon "^0.8.1" + to-regex "^3.0.1" + +normalize-path@^2.0.0, normalize-path@^2.0.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-2.1.1.tgz#1ab28b556e198363a8c1a6f7e6fa20137fe6aed9" + integrity sha1-GrKLVW4Zg2Oowab35vogE3/mrtk= + dependencies: + remove-trailing-separator "^1.0.1" + +normalize-path@^3.0.0, normalize-path@~3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" + integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== + +object-assign@^4.1.0: + version "4.1.1" + resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" + integrity sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM= + +object-copy@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/object-copy/-/object-copy-0.1.0.tgz#7e7d858b781bd7c991a41ba975ed3812754e998c" + integrity sha1-fn2Fi3gb18mRpBupde04EnVOmYw= + dependencies: + copy-descriptor "^0.1.0" + define-property "^0.2.5" + kind-of "^3.0.3" + +object-visit@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/object-visit/-/object-visit-1.0.1.tgz#f79c4493af0c5377b59fe39d395e41042dd045bb" + integrity sha1-95xEk68MU3e1n+OdOV5BBC3QRbs= + dependencies: + isobject "^3.0.0" + +object.omit@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/object.omit/-/object.omit-2.0.1.tgz#1a9c744829f39dbb858c76ca3579ae2a54ebd1fa" + integrity sha1-Gpx0SCnznbuFjHbKNXmuKlTr0fo= + dependencies: + for-own "^0.1.4" + is-extendable "^0.1.1" + +object.pick@^1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/object.pick/-/object.pick-1.3.0.tgz#87a10ac4c1694bd2e1cbf53591a66141fb5dd747" + integrity sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c= + dependencies: + isobject "^3.0.1" + +once@^1.3.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" + integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E= + dependencies: + wrappy "1" + +os-homedir@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/os-homedir/-/os-homedir-1.0.2.tgz#ffbc4988336e0e833de0c168c7ef152121aa7fb3" + integrity sha1-/7xJiDNuDoM94MFox+8VISGqf7M= + +os-tmpdir@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274" + integrity sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ= + +output-file-sync@^1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/output-file-sync/-/output-file-sync-1.1.2.tgz#d0a33eefe61a205facb90092e826598d5245ce76" + integrity sha1-0KM+7+YaIF+suQCS6CZZjVJFznY= + dependencies: + graceful-fs "^4.1.4" + mkdirp "^0.5.1" + object-assign "^4.1.0" + +p-limit@^2.0.0: + version "2.3.0" + resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.3.0.tgz#3dd33c647a214fdfffd835933eb086da0dc21db1" + integrity sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w== + dependencies: + p-try "^2.0.0" + +p-limit@^3.0.2: + version "3.1.0" + resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-3.1.0.tgz#e1daccbe78d0d1388ca18c64fea38e3e57e3706b" + integrity sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ== + dependencies: + yocto-queue "^0.1.0" + +p-locate@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-3.0.0.tgz#322d69a05c0264b25997d9f40cd8a891ab0064a4" + integrity sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ== + dependencies: + p-limit "^2.0.0" + +p-locate@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-5.0.0.tgz#83c8315c6785005e3bd021839411c9e110e6d834" + integrity sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw== + dependencies: + p-limit "^3.0.2" + +p-try@^2.0.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6" + integrity sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ== + +parse-glob@^3.0.4: + version "3.0.4" + resolved "https://registry.yarnpkg.com/parse-glob/-/parse-glob-3.0.4.tgz#b2c376cfb11f35513badd173ef0bb6e3a388391c" + integrity sha1-ssN2z7EfNVE7rdFz7wu246OIORw= + dependencies: + glob-base "^0.3.0" + is-dotfile "^1.0.0" + is-extglob "^1.0.0" + is-glob "^2.0.0" + +pascalcase@^0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/pascalcase/-/pascalcase-0.1.1.tgz#b363e55e8006ca6fe21784d2db22bd15d7917f14" + integrity sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ= + +path-exists@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-3.0.0.tgz#ce0ebeaa5f78cb18925ea7d810d7b59b010fd515" + integrity sha1-zg6+ql94yxiSXqfYENe1mwEP1RU= + +path-exists@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-4.0.0.tgz#513bdbe2d3b95d7762e8c1137efa195c6c61b5b3" + integrity sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w== + +path-is-absolute@^1.0.0, path-is-absolute@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" + integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18= + +path-parse@^1.0.5: + version "1.0.5" + resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.5.tgz#3c1adf871ea9cd6c9431b6ea2bd74a0ff055c4c1" + +picomatch@^2.0.4, picomatch@^2.2.1: + version "2.2.2" + resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.2.2.tgz#21f333e9b6b8eaff02468f5146ea406d345f4dad" + integrity sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg== + +posix-character-classes@^0.1.0: + version "0.1.1" + resolved "https://registry.yarnpkg.com/posix-character-classes/-/posix-character-classes-0.1.1.tgz#01eac0fe3b5af71a2a6c02feabb8c1fef7e00eab" + integrity sha1-AerA/jta9xoqbAL+q7jB/vfgDqs= + +preserve@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b" + integrity sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks= + +private@^0.1.6, private@^0.1.7, private@^0.1.8: + version "0.1.8" + resolved "https://registry.yarnpkg.com/private/-/private-0.1.8.tgz#2381edb3689f7a53d653190060fcf822d2f368ff" + +process-nextick-args@~2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz#7820d9b16120cc55ca9ae7792680ae7dba6d7fe2" + integrity sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag== + +punycode@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.1.0.tgz#5f863edc89b96db09074bad7947bf09056ca4e7d" + +randomatic@^3.0.0: + version "3.1.1" + resolved "https://registry.yarnpkg.com/randomatic/-/randomatic-3.1.1.tgz#b776efc59375984e36c537b2f51a1f0aff0da1ed" + integrity sha512-TuDE5KxZ0J461RVjrJZCJc+J+zCkTb1MbH9AQUq68sMhOMcy9jLcb3BrZKgp9q9Ncltdg4QVqWrH02W2EFFVYw== + dependencies: + is-number "^4.0.0" + kind-of "^6.0.0" + math-random "^1.0.1" + +randombytes@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/randombytes/-/randombytes-2.1.0.tgz#df6f84372f0270dc65cdf6291349ab7a473d4f2a" + integrity sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ== + dependencies: + safe-buffer "^5.1.0" + +readable-stream@^2.0.2: + version "2.3.7" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.7.tgz#1eca1cf711aef814c04f62252a36a62f6cb23b57" + integrity sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw== + dependencies: + core-util-is "~1.0.0" + inherits "~2.0.3" + isarray "~1.0.0" + process-nextick-args "~2.0.0" + safe-buffer "~5.1.1" + string_decoder "~1.1.1" + util-deprecate "~1.0.1" + +readdirp@^2.0.0: + version "2.2.1" + resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-2.2.1.tgz#0e87622a3325aa33e892285caf8b4e846529a525" + integrity sha512-1JU/8q+VgFZyxwrJ+SVIOsh+KywWGpds3NTqikiKpDMZWScmAYyKIgqkO+ARvNWJfXeXR1zxz7aHF4u4CyH6vQ== + dependencies: + graceful-fs "^4.1.11" + micromatch "^3.1.10" + readable-stream "^2.0.2" + +readdirp@~3.5.0: + version "3.5.0" + resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-3.5.0.tgz#9ba74c019b15d365278d2e91bb8c48d7b4d42c9e" + integrity sha512-cMhu7c/8rdhkHXWsY+osBhfSy0JikwpHK/5+imo+LpeasTF8ouErHrlYkwT0++njiyuDvc7OFY5T3ukvZ8qmFQ== + dependencies: + picomatch "^2.2.1" + +regenerate@^1.2.1: + version "1.3.3" + resolved "https://registry.yarnpkg.com/regenerate/-/regenerate-1.3.3.tgz#0c336d3980553d755c39b586ae3b20aa49c82b7f" + +regenerator-runtime@^0.10.5: + version "0.10.5" + resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.10.5.tgz#336c3efc1220adcedda2c9fab67b5a7955a33658" + integrity sha1-M2w+/BIgrc7dosn6tntaeVWjNlg= + +regenerator-runtime@^0.11.0: + version "0.11.1" + resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz#be05ad7f9bf7d22e056f9726cee5017fbf19e2e9" + integrity sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg== + +regenerator-transform@^0.10.0: + version "0.10.1" + resolved "https://registry.yarnpkg.com/regenerator-transform/-/regenerator-transform-0.10.1.tgz#1e4996837231da8b7f3cf4114d71b5691a0680dd" + dependencies: + babel-runtime "^6.18.0" + babel-types "^6.19.0" + private "^0.1.6" + +regex-cache@^0.4.2: + version "0.4.4" + resolved "https://registry.yarnpkg.com/regex-cache/-/regex-cache-0.4.4.tgz#75bdc58a2a1496cec48a12835bc54c8d562336dd" + integrity sha512-nVIZwtCjkC9YgvWkpM55B5rBhBYRZhAaJbgcFYXXsHnbZ9UZI9nnVWYZpBlCqv9ho2eZryPnWrZGsOdPwVWXWQ== + dependencies: + is-equal-shallow "^0.1.3" + +regex-not@^1.0.0, regex-not@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/regex-not/-/regex-not-1.0.2.tgz#1f4ece27e00b0b65e0247a6810e6a85d83a5752c" + integrity sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A== + dependencies: + extend-shallow "^3.0.2" + safe-regex "^1.1.0" + +regexpu-core@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/regexpu-core/-/regexpu-core-2.0.0.tgz#49d038837b8dcf8bfa5b9a42139938e6ea2ae240" + dependencies: + regenerate "^1.2.1" + regjsgen "^0.2.0" + regjsparser "^0.1.4" + +regjsgen@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/regjsgen/-/regjsgen-0.2.0.tgz#6c016adeac554f75823fe37ac05b92d5a4edb1f7" + +regjsparser@^0.1.4: + version "0.1.5" + resolved "https://registry.yarnpkg.com/regjsparser/-/regjsparser-0.1.5.tgz#7ee8f84dc6fa792d3fd0ae228d24bd949ead205c" + dependencies: + jsesc "~0.5.0" + +remove-trailing-separator@^1.0.1: + version "1.1.0" + resolved "https://registry.yarnpkg.com/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz#c24bce2a283adad5bc3f58e0d48249b92379d8ef" + integrity sha1-wkvOKig62tW8P1jg1IJJuSN52O8= + +repeat-element@^1.1.2: + version "1.1.3" + resolved "https://registry.yarnpkg.com/repeat-element/-/repeat-element-1.1.3.tgz#782e0d825c0c5a3bb39731f84efee6b742e6b1ce" + integrity sha512-ahGq0ZnV5m5XtZLMb+vP76kcAM5nkLqk0lpqAuojSKGgQtn4eRi4ZZGm2olo2zKFH+sMsWaqOCW1dqAnOru72g== + +repeat-string@^1.5.2, repeat-string@^1.6.1: + version "1.6.1" + resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" + integrity sha1-jcrkcOHIirwtYA//Sndihtp15jc= + +repeating@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/repeating/-/repeating-2.0.1.tgz#5214c53a926d3552707527fbab415dbc08d06dda" + integrity sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo= + dependencies: + is-finite "^1.0.0" + +require-directory@^2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" + integrity sha1-jGStX9MNqxyXbiNE/+f3kqam30I= + +require-main-filename@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-2.0.0.tgz#d0b329ecc7cc0f61649f62215be69af54aa8989b" + integrity sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg== + +resolve-url@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/resolve-url/-/resolve-url-0.2.1.tgz#2c637fe77c893afd2a663fe21aa9080068e2052a" + integrity sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo= + +resolve@1.1.7: + version "1.1.7" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.1.7.tgz#203114d82ad2c5ed9e8e0411b3932875e889e97b" + +resolve@^1.1.6: + version "1.6.0" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.6.0.tgz#0fbd21278b27b4004481c395349e7aba60a9ff5c" + dependencies: + path-parse "^1.0.5" + +ret@~0.1.10: + version "0.1.15" + resolved "https://registry.yarnpkg.com/ret/-/ret-0.1.15.tgz#b8a4825d5bdb1fc3f6f53c2bc33f81388681c7bc" + integrity sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg== + +right-align@^0.1.1: + version "0.1.3" + resolved "https://registry.yarnpkg.com/right-align/-/right-align-0.1.3.tgz#61339b722fe6a3515689210d24e14c96148613ef" + dependencies: + align-text "^0.1.1" + +rimraf@^2.5.2: + version "2.7.1" + resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.7.1.tgz#35797f13a7fdadc566142c29d4f07ccad483e3ec" + dependencies: + glob "^7.1.3" + +rollup-plugin-babel@^2.7.1: + version "2.7.1" + resolved "https://registry.yarnpkg.com/rollup-plugin-babel/-/rollup-plugin-babel-2.7.1.tgz#16528197b0f938a1536f44683c7a93d573182f57" + dependencies: + babel-core "6" + babel-plugin-transform-es2015-classes "^6.9.0" + object-assign "^4.1.0" + rollup-pluginutils "^1.5.0" + +rollup-plugin-node-resolve@^2.0.0: + version "2.1.1" + resolved "https://registry.yarnpkg.com/rollup-plugin-node-resolve/-/rollup-plugin-node-resolve-2.1.1.tgz#cbb783b0d15b02794d58915350b2f0d902b8ddc8" + dependencies: + browser-resolve "^1.11.0" + builtin-modules "^1.1.0" + resolve "^1.1.6" + +rollup-pluginutils@^1.5.0: + version "1.5.2" + resolved "https://registry.yarnpkg.com/rollup-pluginutils/-/rollup-pluginutils-1.5.2.tgz#1e156e778f94b7255bfa1b3d0178be8f5c552408" + dependencies: + estree-walker "^0.2.1" + minimatch "^3.0.2" + +rollup@^0.41.6: + version "0.41.6" + resolved "https://registry.yarnpkg.com/rollup/-/rollup-0.41.6.tgz#e0d05497877a398c104d816d2733a718a7a94e2a" + dependencies: + source-map-support "^0.4.0" + +safe-buffer@^5.1.0: + version "5.2.1" + resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" + integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== + +safe-buffer@~5.1.0, safe-buffer@~5.1.1: + version "5.1.2" + resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" + integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g== + +safe-regex@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/safe-regex/-/safe-regex-1.1.0.tgz#40a3669f3b077d1e943d44629e157dd48023bf2e" + integrity sha1-QKNmnzsHfR6UPURinhV91IAjvy4= + dependencies: + ret "~0.1.10" + +sander@^0.5.0: + version "0.5.1" + resolved "https://registry.yarnpkg.com/sander/-/sander-0.5.1.tgz#741e245e231f07cafb6fdf0f133adfa216a502ad" + dependencies: + es6-promise "^3.1.2" + graceful-fs "^4.1.3" + mkdirp "^0.5.1" + rimraf "^2.5.2" + +serialize-javascript@5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-5.0.1.tgz#7886ec848049a462467a97d3d918ebb2aaf934f4" + integrity sha512-SaaNal9imEO737H2c05Og0/8LUXG7EnsZyMa8MzkmuHoELfT6txuj0cMqRj6zfPKnmQ1yasR4PCJc8x+M4JSPA== + dependencies: + randombytes "^2.1.0" + +set-blocking@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7" + +set-value@^2.0.0, set-value@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/set-value/-/set-value-2.0.1.tgz#a18d40530e6f07de4228c7defe4227af8cad005b" + integrity sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw== + dependencies: + extend-shallow "^2.0.1" + is-extendable "^0.1.1" + is-plain-object "^2.0.3" + split-string "^3.0.1" + +slash@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/slash/-/slash-1.0.0.tgz#c41f2f6c39fc16d1cd17ad4b5d896114ae470d55" + integrity sha1-xB8vbDn8FtHNF61LXYlhFK5HDVU= + +snapdragon-node@^2.0.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/snapdragon-node/-/snapdragon-node-2.1.1.tgz#6c175f86ff14bdb0724563e8f3c1b021a286853b" + integrity sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw== + dependencies: + define-property "^1.0.0" + isobject "^3.0.0" + snapdragon-util "^3.0.1" + +snapdragon-util@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/snapdragon-util/-/snapdragon-util-3.0.1.tgz#f956479486f2acd79700693f6f7b805e45ab56e2" + integrity sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ== + dependencies: + kind-of "^3.2.0" + +snapdragon@^0.8.1: + version "0.8.2" + resolved "https://registry.yarnpkg.com/snapdragon/-/snapdragon-0.8.2.tgz#64922e7c565b0e14204ba1aa7d6964278d25182d" + integrity sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg== + dependencies: + base "^0.11.1" + debug "^2.2.0" + define-property "^0.2.5" + extend-shallow "^2.0.1" + map-cache "^0.2.2" + source-map "^0.5.6" + source-map-resolve "^0.5.0" + use "^3.1.0" + +sorcery@^0.10.0: + version "0.10.0" + resolved "https://registry.yarnpkg.com/sorcery/-/sorcery-0.10.0.tgz#8ae90ad7d7cb05fc59f1ab0c637845d5c15a52b7" + dependencies: + buffer-crc32 "^0.2.5" + minimist "^1.2.0" + sander "^0.5.0" + sourcemap-codec "^1.3.0" + +source-map-resolve@^0.5.0: + version "0.5.3" + resolved "https://registry.yarnpkg.com/source-map-resolve/-/source-map-resolve-0.5.3.tgz#190866bece7553e1f8f267a2ee82c606b5509a1a" + integrity sha512-Htz+RnsXWk5+P2slx5Jh3Q66vhQj1Cllm0zvnaY98+NFx+Dv2CF/f5O/t8x+KaNdrdIAsruNzoh/KpialbqAnw== + dependencies: + atob "^2.1.2" + decode-uri-component "^0.2.0" + resolve-url "^0.2.1" + source-map-url "^0.4.0" + urix "^0.1.0" + +source-map-support@^0.4.0, source-map-support@^0.4.15: + version "0.4.18" + resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.4.18.tgz#0286a6de8be42641338594e97ccea75f0a2c585f" + dependencies: + source-map "^0.5.6" + +source-map-url@^0.4.0: + version "0.4.0" + resolved "https://registry.yarnpkg.com/source-map-url/-/source-map-url-0.4.0.tgz#3e935d7ddd73631b97659956d55128e87b5084a3" + integrity sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM= + +source-map@^0.5.6, source-map@^0.5.7, source-map@~0.5.1: + version "0.5.7" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc" + integrity sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w= + +sourcemap-codec@^1.3.0: + version "1.4.1" + resolved "https://registry.yarnpkg.com/sourcemap-codec/-/sourcemap-codec-1.4.1.tgz#c8fd92d91889e902a07aee392bdd2c5863958ba2" + +split-string@^3.0.1, split-string@^3.0.2: + version "3.1.0" + resolved "https://registry.yarnpkg.com/split-string/-/split-string-3.1.0.tgz#7cb09dda3a86585705c64b39a6466038682e8fe2" + integrity sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw== + dependencies: + extend-shallow "^3.0.0" + +sprintf-js@~1.0.2: + version "1.0.3" + resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" + integrity sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw= + +static-extend@^0.1.1: + version "0.1.2" + resolved "https://registry.yarnpkg.com/static-extend/-/static-extend-0.1.2.tgz#60809c39cbff55337226fd5e0b520f341f1fb5c6" + integrity sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY= + dependencies: + define-property "^0.2.5" + object-copy "^0.1.0" + +"string-width@^1.0.2 || 2": + version "2.1.1" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-2.1.1.tgz#ab93f27a8dc13d28cac815c462143a6d9012ae9e" + integrity sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw== + dependencies: + is-fullwidth-code-point "^2.0.0" + strip-ansi "^4.0.0" + +string-width@^3.0.0, string-width@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-3.1.0.tgz#22767be21b62af1081574306f69ac51b62203961" + integrity sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w== + dependencies: + emoji-regex "^7.0.1" + is-fullwidth-code-point "^2.0.0" + strip-ansi "^5.1.0" + +string_decoder@~1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.1.1.tgz#9cf1611ba62685d7030ae9e4ba34149c3af03fc8" + integrity sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg== + dependencies: + safe-buffer "~5.1.0" + +strip-ansi@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" + integrity sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8= + dependencies: + ansi-regex "^2.0.0" + +strip-ansi@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-4.0.0.tgz#a8479022eb1ac368a871389b635262c505ee368f" + integrity sha1-qEeQIusaw2iocTibY1JixQXuNo8= + dependencies: + ansi-regex "^3.0.0" + +strip-ansi@^5.0.0, strip-ansi@^5.1.0, strip-ansi@^5.2.0: + version "5.2.0" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-5.2.0.tgz#8c9a536feb6afc962bdfa5b104a5091c1ad9c0ae" + integrity sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA== + dependencies: + ansi-regex "^4.1.0" + +strip-json-comments@3.1.1: + version "3.1.1" + resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006" + integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== + +supports-color@7.2.0, supports-color@^7.1.0: + version "7.2.0" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-7.2.0.tgz#1b7dcdcb32b8138801b3e478ba6a51caa89648da" + integrity sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw== + dependencies: + has-flag "^4.0.0" + +supports-color@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7" + integrity sha1-U10EXOa2Nj+kARcIRimZXp3zJMc= + +to-fast-properties@^1.0.3: + version "1.0.3" + resolved "https://registry.yarnpkg.com/to-fast-properties/-/to-fast-properties-1.0.3.tgz#b83571fa4d8c25b82e231b06e3a3055de4ca1a47" + integrity sha1-uDVx+k2MJbguIxsG46MFXeTKGkc= + +to-object-path@^0.3.0: + version "0.3.0" + resolved "https://registry.yarnpkg.com/to-object-path/-/to-object-path-0.3.0.tgz#297588b7b0e7e0ac08e04e672f85c1f4999e17af" + integrity sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68= + dependencies: + kind-of "^3.0.2" + +to-regex-range@^2.1.0: + version "2.1.1" + resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-2.1.1.tgz#7c80c17b9dfebe599e27367e0d4dd5590141db38" + integrity sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg= + dependencies: + is-number "^3.0.0" + repeat-string "^1.6.1" + +to-regex-range@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" + integrity sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ== + dependencies: + is-number "^7.0.0" + +to-regex@^3.0.1, to-regex@^3.0.2: + version "3.0.2" + resolved "https://registry.yarnpkg.com/to-regex/-/to-regex-3.0.2.tgz#13cfdd9b336552f30b51f33a8ae1b42a7a7599ce" + integrity sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw== + dependencies: + define-property "^2.0.2" + extend-shallow "^3.0.2" + regex-not "^1.0.2" + safe-regex "^1.1.0" + +trim-right@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/trim-right/-/trim-right-1.0.1.tgz#cb2e1203067e0c8de1f614094b9fe45704ea6003" + integrity sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM= + +typescript@^2.8.1: + version "2.8.1" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-2.8.1.tgz#6160e4f8f195d5ba81d4876f9c0cc1fbc0820624" + +uglify-js@^2.8.14: + version "2.8.29" + resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-2.8.29.tgz#29c5733148057bb4e1f75df35b7a9cb72e6a59dd" + dependencies: + source-map "~0.5.1" + yargs "~3.10.0" + optionalDependencies: + uglify-to-browserify "~1.0.0" + +uglify-to-browserify@~1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz#6e0924d6bda6b5afe349e39a6d632850a0f882b7" + +union-value@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/union-value/-/union-value-1.0.1.tgz#0b6fe7b835aecda61c6ea4d4f02c14221e109847" + integrity sha512-tJfXmxMeWYnczCVs7XAEvIV7ieppALdyepWMkHkwciRpZraG/xwT+s2JN8+pr1+8jCRf80FFzvr+MpQeeoF4Xg== + dependencies: + arr-union "^3.1.0" + get-value "^2.0.6" + is-extendable "^0.1.1" + set-value "^2.0.1" + +unset-value@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/unset-value/-/unset-value-1.0.0.tgz#8376873f7d2335179ffb1e6fc3a8ed0dfc8ab559" + integrity sha1-g3aHP30jNRef+x5vw6jtDfyKtVk= + dependencies: + has-value "^0.3.1" + isobject "^3.0.0" + +urix@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/urix/-/urix-0.1.0.tgz#da937f7a62e21fec1fd18d49b35c2935067a6c72" + integrity sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI= + +use@^3.1.0: + version "3.1.1" + resolved "https://registry.yarnpkg.com/use/-/use-3.1.1.tgz#d50c8cac79a19fbc20f2911f56eb973f4e10070f" + integrity sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ== + +user-home@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/user-home/-/user-home-1.1.1.tgz#2b5be23a32b63a7c9deb8d0f28d485724a3df190" + integrity sha1-K1viOjK2Onyd640PKNSFcko98ZA= + +util-deprecate@~1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" + integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8= + +v8flags@^2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/v8flags/-/v8flags-2.1.1.tgz#aab1a1fa30d45f88dd321148875ac02c0b55e5b4" + integrity sha1-qrGh+jDUX4jdMhFIh1rALAtV5bQ= + dependencies: + user-home "^1.1.1" + +which-module@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/which-module/-/which-module-2.0.0.tgz#d9ef07dce77b9902b8a3a8fa4b31c3e3f7e6e87a" + integrity sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho= + +which@2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1" + integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA== + dependencies: + isexe "^2.0.0" + +wide-align@1.1.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/wide-align/-/wide-align-1.1.3.tgz#ae074e6bdc0c14a431e804e624549c633b000457" + integrity sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA== + dependencies: + string-width "^1.0.2 || 2" + +window-size@0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/window-size/-/window-size-0.1.0.tgz#5438cd2ea93b202efa3a19fe8887aee7c94f9c9d" + +wordwrap@0.0.2: + version "0.0.2" + resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.2.tgz#b79669bb42ecb409f83d583cad52ca17eaa1643f" + +workerpool@6.0.2: + version "6.0.2" + resolved "https://registry.yarnpkg.com/workerpool/-/workerpool-6.0.2.tgz#e241b43d8d033f1beb52c7851069456039d1d438" + integrity sha512-DSNyvOpFKrNusaaUwk+ej6cBj1bmhLcBfj80elGk+ZIo5JSkq+unB1dLKEOcNfJDZgjGICfhQ0Q5TbP0PvF4+Q== + +wrap-ansi@^5.1.0: + version "5.1.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-5.1.0.tgz#1fd1f67235d5b6d0fee781056001bfb694c03b09" + integrity sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q== + dependencies: + ansi-styles "^3.2.0" + string-width "^3.0.0" + strip-ansi "^5.0.0" + +wrappy@1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" + integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8= + +y18n@^4.0.0: + version "4.0.1" + resolved "https://registry.yarnpkg.com/y18n/-/y18n-4.0.1.tgz#8db2b83c31c5d75099bb890b23f3094891e247d4" + integrity sha512-wNcy4NvjMYL8gogWWYAO7ZFWFfHcbdbE57tZO8e4cbpj8tfUcwrwqSl3ad8HxpYWCdXcJUCeKKZS62Av1affwQ== + +yargs-parser@13.1.2, yargs-parser@^13.1.2: + version "13.1.2" + resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-13.1.2.tgz#130f09702ebaeef2650d54ce6e3e5706f7a4fb38" + integrity sha512-3lbsNRf/j+A4QuSZfDRA7HRSfWrzO0YjqTJd5kjAq37Zep1CEgaYmrH9Q3GwPiB9cHyd1Y1UwggGhJGoxipbzg== + dependencies: + camelcase "^5.0.0" + decamelize "^1.2.0" + +yargs-unparser@2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/yargs-unparser/-/yargs-unparser-2.0.0.tgz#f131f9226911ae5d9ad38c432fe809366c2325eb" + integrity sha512-7pRTIA9Qc1caZ0bZ6RYRGbHJthJWuakf+WmHK0rVeLkNrrGhfoabBNdue6kdINI6r4if7ocq9aD/n7xwKOdzOA== + dependencies: + camelcase "^6.0.0" + decamelize "^4.0.0" + flat "^5.0.2" + is-plain-obj "^2.1.0" + +yargs@13.3.2: + version "13.3.2" + resolved "https://registry.yarnpkg.com/yargs/-/yargs-13.3.2.tgz#ad7ffefec1aa59565ac915f82dccb38a9c31a2dd" + integrity sha512-AX3Zw5iPruN5ie6xGRIDgqkT+ZhnRlZMLMHAs8tg7nRruy2Nb+i5o9bwghAogtM08q1dpr2LVoS8KSTMYpWXUw== + dependencies: + cliui "^5.0.0" + find-up "^3.0.0" + get-caller-file "^2.0.1" + require-directory "^2.1.1" + require-main-filename "^2.0.0" + set-blocking "^2.0.0" + string-width "^3.0.0" + which-module "^2.0.0" + y18n "^4.0.0" + yargs-parser "^13.1.2" + +yargs@~3.10.0: + version "3.10.0" + resolved "https://registry.yarnpkg.com/yargs/-/yargs-3.10.0.tgz#f7ee7bd857dd7c1d2d38c0e74efbd681d1431fd1" + dependencies: + camelcase "^1.0.2" + cliui "^2.1.0" + decamelize "^1.0.0" + window-size "0.1.0" + +yocto-queue@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/yocto-queue/-/yocto-queue-0.1.0.tgz#0294eb3dee05028d31ee1a5fa2c556a6aaf10a1b" + integrity sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q== diff --git a/node_modules/watchpack/LICENSE b/node_modules/watchpack/LICENSE new file mode 100644 index 0000000..8c11fc7 --- /dev/null +++ b/node_modules/watchpack/LICENSE @@ -0,0 +1,20 @@ +Copyright JS Foundation and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/watchpack/README.md b/node_modules/watchpack/README.md new file mode 100644 index 0000000..a005f50 --- /dev/null +++ b/node_modules/watchpack/README.md @@ -0,0 +1,133 @@ +# watchpack + +Wrapper library for directory and file watching. + +[![Test](https://github.com/webpack/watchpack/actions/workflows/test.yml/badge.svg)](https://github.com/webpack/watchpack/actions/workflows/test.yml) +[![Codecov](https://codecov.io/gh/webpack/watchpack/graph/badge.svg?token=8xk2OrrxWm)](https://codecov.io/gh/webpack/watchpack) +[![Downloads](https://img.shields.io/npm/dm/watchpack.svg)](https://www.npmjs.com/package/watchpack) + +## Concept + +watchpack high level API doesn't map directly to watchers. Instead a three level architecture ensures that for each directory only a single watcher exists. + +- The high level API requests `DirectoryWatchers` from a `WatcherManager`, which ensures that only a single `DirectoryWatcher` per directory is created. +- A user-faced `Watcher` can be obtained from a `DirectoryWatcher` and provides a filtered view on the `DirectoryWatcher`. +- Reference-counting is used on the `DirectoryWatcher` and `Watcher` to decide when to close them. +- The real watchers are created by the `DirectoryWatcher`. +- Files are never watched directly. This should keep the watcher count low. +- Watching can be started in the past. This way watching can start after file reading. +- Symlinks are not followed, instead the symlink is watched. + +## API + +```javascript +var Watchpack = require("watchpack"); + +var wp = new Watchpack({ + // options: + aggregateTimeout: 1000, + // fire "aggregated" event when after a change for 1000ms no additional change occurred + // aggregated defaults to undefined, which doesn't fire an "aggregated" event + + poll: true, + // poll: true - use polling with the default interval + // poll: 10000 - use polling with an interval of 10s + // poll defaults to undefined, which prefer native watching methods + // Note: enable polling when watching on a network path + // When WATCHPACK_POLLING environment variable is set it will override this option + + followSymlinks: true, + // true: follows symlinks and watches symlinks and real files + // (This makes sense when symlinks has not been resolved yet, comes with a performance hit) + // false (default): watches only specified item they may be real files or symlinks + // (This makes sense when symlinks has already been resolved) + + ignored: "**/.git" + // ignored: "string" - a glob pattern for files or folders that should not be watched + // ignored: ["string", "string"] - multiple glob patterns that should be ignored + // ignored: /regexp/ - a regular expression for files or folders that should not be watched + // ignored: (entry) => boolean - an arbitrary function which must return truthy to ignore an entry + // For all cases expect the arbitrary function the path will have path separator normalized to '/'. + // All subdirectories are ignored too +}); + +// Watchpack.prototype.watch({ +// files: Iterable, +// directories: Iterable, +// missing: Iterable, +// startTime?: number +// }) +wp.watch({ + files: listOfFiles, + directories: listOfDirectories, + missing: listOfNotExistingItems, + startTime: Date.now() - 10000 +}); +// starts watching these files and directories +// calling this again will override the files and directories +// files: can be files or directories, for files: content and existence changes are tracked +// for directories: only existence and timestamp changes are tracked +// directories: only directories, directory content (and content of children, ...) and +// existence changes are tracked. +// assumed to exist, when directory is not found without further information a remove event is emitted +// missing: can be files or directorees, +// only existence changes are tracked +// expected to not exist, no remove event is emitted when not found initially +// files and directories are assumed to exist, when they are not found without further information a remove event is emitted +// missing is assumed to not exist and no remove event is emitted + +wp.on("change", function(filePath, mtime, explanation) { + // filePath: the changed file + // mtime: last modified time for the changed file + // explanation: textual information how this change was detected +}); + +wp.on("remove", function(filePath, explanation) { + // filePath: the removed file or directory + // explanation: textual information how this change was detected +}); + +wp.on("aggregated", function(changes, removals) { + // changes: a Set of all changed files + // removals: a Set of all removed files + // watchpack gives up ownership on these Sets. +}); + +// Watchpack.prototype.pause() +wp.pause(); +// stops emitting events, but keeps watchers open +// next "watch" call can reuse the watchers +// The watcher will keep aggregating events +// which can be received with getAggregated() + +// Watchpack.prototype.close() +wp.close(); +// stops emitting events and closes all watchers + +// Watchpack.prototype.getAggregated(): { changes: Set, removals: Set } +const { changes, removals } = wp.getAggregated(); +// returns the current aggregated info and removes that from the watcher +// The next aggregated event won't include that info and will only emitted +// when futher changes happen +// Can also be used when paused. + +// Watchpack.prototype.collectTimeInfoEntries(fileInfoEntries: Map, directoryInfoEntries: Map) +wp.collectTimeInfoEntries(fileInfoEntries, directoryInfoEntries); +// collects time info objects for all known files and directories +// this include info from files not directly watched +// key: absolute path, value: object with { safeTime, timestamp } +// safeTime: a point in time at which it is safe to say all changes happened before that +// timestamp: only for files, the mtime timestamp of the file + +// Watchpack.prototype.getTimeInfoEntries() +var fileTimes = wp.getTimeInfoEntries(); +// returns a Map with all known time info objects for files and directories +// similar to collectTimeInfoEntries but returns a single map with all entries + +// (deprecated) +// Watchpack.prototype.getTimes() +var fileTimes = wp.getTimes(); +// returns an object with all known change times for files +// this include timestamps from files not directly watched +// key: absolute path, value: timestamp as number +``` diff --git a/node_modules/watchpack/lib/DirectoryWatcher.js b/node_modules/watchpack/lib/DirectoryWatcher.js new file mode 100644 index 0000000..034447d --- /dev/null +++ b/node_modules/watchpack/lib/DirectoryWatcher.js @@ -0,0 +1,787 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const EventEmitter = require("events").EventEmitter; +const fs = require("graceful-fs"); +const path = require("path"); + +const watchEventSource = require("./watchEventSource"); + +const EXISTANCE_ONLY_TIME_ENTRY = Object.freeze({}); + +let FS_ACCURACY = 2000; + +const IS_OSX = require("os").platform() === "darwin"; +const WATCHPACK_POLLING = process.env.WATCHPACK_POLLING; +const FORCE_POLLING = + `${+WATCHPACK_POLLING}` === WATCHPACK_POLLING + ? +WATCHPACK_POLLING + : !!WATCHPACK_POLLING && WATCHPACK_POLLING !== "false"; + +function withoutCase(str) { + return str.toLowerCase(); +} + +function needCalls(times, callback) { + return function() { + if (--times === 0) { + return callback(); + } + }; +} + +class Watcher extends EventEmitter { + constructor(directoryWatcher, filePath, startTime) { + super(); + this.directoryWatcher = directoryWatcher; + this.path = filePath; + this.startTime = startTime && +startTime; + } + + checkStartTime(mtime, initial) { + const startTime = this.startTime; + if (typeof startTime !== "number") return !initial; + return startTime <= mtime; + } + + close() { + this.emit("closed"); + } +} + +class DirectoryWatcher extends EventEmitter { + constructor(watcherManager, directoryPath, options) { + super(); + if (FORCE_POLLING) { + options.poll = FORCE_POLLING; + } + this.watcherManager = watcherManager; + this.options = options; + this.path = directoryPath; + // safeTime is the point in time after which reading is safe to be unchanged + // timestamp is a value that should be compared with another timestamp (mtime) + /** @type {Map} */ + this.filesWithoutCase = new Map(); + this.directories = new Map(); + this.lastWatchEvent = 0; + this.initialScan = true; + this.ignored = options.ignored || (() => false); + this.nestedWatching = false; + this.polledWatching = + typeof options.poll === "number" + ? options.poll + : options.poll + ? 5007 + : false; + this.timeout = undefined; + this.initialScanRemoved = new Set(); + this.initialScanFinished = undefined; + /** @type {Map>} */ + this.watchers = new Map(); + this.parentWatcher = null; + this.refs = 0; + this._activeEvents = new Map(); + this.closed = false; + this.scanning = false; + this.scanAgain = false; + this.scanAgainInitial = false; + + this.createWatcher(); + this.doScan(true); + } + + createWatcher() { + try { + if (this.polledWatching) { + this.watcher = { + close: () => { + if (this.timeout) { + clearTimeout(this.timeout); + this.timeout = undefined; + } + } + }; + } else { + if (IS_OSX) { + this.watchInParentDirectory(); + } + this.watcher = watchEventSource.watch(this.path); + this.watcher.on("change", this.onWatchEvent.bind(this)); + this.watcher.on("error", this.onWatcherError.bind(this)); + } + } catch (err) { + this.onWatcherError(err); + } + } + + forEachWatcher(path, fn) { + const watchers = this.watchers.get(withoutCase(path)); + if (watchers !== undefined) { + for (const w of watchers) { + fn(w); + } + } + } + + setMissing(itemPath, initial, type) { + if (this.initialScan) { + this.initialScanRemoved.add(itemPath); + } + + const oldDirectory = this.directories.get(itemPath); + if (oldDirectory) { + if (this.nestedWatching) oldDirectory.close(); + this.directories.delete(itemPath); + + this.forEachWatcher(itemPath, w => w.emit("remove", type)); + if (!initial) { + this.forEachWatcher(this.path, w => + w.emit("change", itemPath, null, type, initial) + ); + } + } + + const oldFile = this.files.get(itemPath); + if (oldFile) { + this.files.delete(itemPath); + const key = withoutCase(itemPath); + const count = this.filesWithoutCase.get(key) - 1; + if (count <= 0) { + this.filesWithoutCase.delete(key); + this.forEachWatcher(itemPath, w => w.emit("remove", type)); + } else { + this.filesWithoutCase.set(key, count); + } + + if (!initial) { + this.forEachWatcher(this.path, w => + w.emit("change", itemPath, null, type, initial) + ); + } + } + } + + setFileTime(filePath, mtime, initial, ignoreWhenEqual, type) { + const now = Date.now(); + + if (this.ignored(filePath)) return; + + const old = this.files.get(filePath); + + let safeTime, accuracy; + if (initial) { + safeTime = Math.min(now, mtime) + FS_ACCURACY; + accuracy = FS_ACCURACY; + } else { + safeTime = now; + accuracy = 0; + + if (old && old.timestamp === mtime && mtime + FS_ACCURACY < now) { + // We are sure that mtime is untouched + // This can be caused by some file attribute change + // e. g. when access time has been changed + // but the file content is untouched + return; + } + } + + if (ignoreWhenEqual && old && old.timestamp === mtime) return; + + this.files.set(filePath, { + safeTime, + accuracy, + timestamp: mtime + }); + + if (!old) { + const key = withoutCase(filePath); + const count = this.filesWithoutCase.get(key); + this.filesWithoutCase.set(key, (count || 0) + 1); + if (count !== undefined) { + // There is already a file with case-insensitive-equal name + // On a case-insensitive filesystem we may miss the renaming + // when only casing is changed. + // To be sure that our information is correct + // we trigger a rescan here + this.doScan(false); + } + + this.forEachWatcher(filePath, w => { + if (!initial || w.checkStartTime(safeTime, initial)) { + w.emit("change", mtime, type); + } + }); + } else if (!initial) { + this.forEachWatcher(filePath, w => w.emit("change", mtime, type)); + } + this.forEachWatcher(this.path, w => { + if (!initial || w.checkStartTime(safeTime, initial)) { + w.emit("change", filePath, safeTime, type, initial); + } + }); + } + + setDirectory(directoryPath, birthtime, initial, type) { + if (this.ignored(directoryPath)) return; + if (directoryPath === this.path) { + if (!initial) { + this.forEachWatcher(this.path, w => + w.emit("change", directoryPath, birthtime, type, initial) + ); + } + } else { + const old = this.directories.get(directoryPath); + if (!old) { + const now = Date.now(); + + if (this.nestedWatching) { + this.createNestedWatcher(directoryPath); + } else { + this.directories.set(directoryPath, true); + } + + let safeTime; + if (initial) { + safeTime = Math.min(now, birthtime) + FS_ACCURACY; + } else { + safeTime = now; + } + + this.forEachWatcher(directoryPath, w => { + if (!initial || w.checkStartTime(safeTime, false)) { + w.emit("change", birthtime, type); + } + }); + this.forEachWatcher(this.path, w => { + if (!initial || w.checkStartTime(safeTime, initial)) { + w.emit("change", directoryPath, safeTime, type, initial); + } + }); + } + } + } + + createNestedWatcher(directoryPath) { + const watcher = this.watcherManager.watchDirectory(directoryPath, 1); + watcher.on("change", (filePath, mtime, type, initial) => { + this.forEachWatcher(this.path, w => { + if (!initial || w.checkStartTime(mtime, initial)) { + w.emit("change", filePath, mtime, type, initial); + } + }); + }); + this.directories.set(directoryPath, watcher); + } + + setNestedWatching(flag) { + if (this.nestedWatching !== !!flag) { + this.nestedWatching = !!flag; + if (this.nestedWatching) { + for (const directory of this.directories.keys()) { + this.createNestedWatcher(directory); + } + } else { + for (const [directory, watcher] of this.directories) { + watcher.close(); + this.directories.set(directory, true); + } + } + } + } + + watch(filePath, startTime) { + const key = withoutCase(filePath); + let watchers = this.watchers.get(key); + if (watchers === undefined) { + watchers = new Set(); + this.watchers.set(key, watchers); + } + this.refs++; + const watcher = new Watcher(this, filePath, startTime); + watcher.on("closed", () => { + if (--this.refs <= 0) { + this.close(); + return; + } + watchers.delete(watcher); + if (watchers.size === 0) { + this.watchers.delete(key); + if (this.path === filePath) this.setNestedWatching(false); + } + }); + watchers.add(watcher); + let safeTime; + if (filePath === this.path) { + this.setNestedWatching(true); + safeTime = this.lastWatchEvent; + for (const entry of this.files.values()) { + fixupEntryAccuracy(entry); + safeTime = Math.max(safeTime, entry.safeTime); + } + } else { + const entry = this.files.get(filePath); + if (entry) { + fixupEntryAccuracy(entry); + safeTime = entry.safeTime; + } else { + safeTime = 0; + } + } + if (safeTime) { + if (safeTime >= startTime) { + process.nextTick(() => { + if (this.closed) return; + if (filePath === this.path) { + watcher.emit( + "change", + filePath, + safeTime, + "watch (outdated on attach)", + true + ); + } else { + watcher.emit( + "change", + safeTime, + "watch (outdated on attach)", + true + ); + } + }); + } + } else if (this.initialScan) { + if (this.initialScanRemoved.has(filePath)) { + process.nextTick(() => { + if (this.closed) return; + watcher.emit("remove"); + }); + } + } else if ( + filePath !== this.path && + !this.directories.has(filePath) && + watcher.checkStartTime(this.initialScanFinished, false) + ) { + process.nextTick(() => { + if (this.closed) return; + watcher.emit("initial-missing", "watch (missing on attach)"); + }); + } + return watcher; + } + + onWatchEvent(eventType, filename) { + if (this.closed) return; + if (!filename) { + // In some cases no filename is provided + // This seem to happen on windows + // So some event happened but we don't know which file is affected + // We have to do a full scan of the directory + this.doScan(false); + return; + } + + const filePath = path.join(this.path, filename); + if (this.ignored(filePath)) return; + + if (this._activeEvents.get(filename) === undefined) { + this._activeEvents.set(filename, false); + const checkStats = () => { + if (this.closed) return; + this._activeEvents.set(filename, false); + fs.lstat(filePath, (err, stats) => { + if (this.closed) return; + if (this._activeEvents.get(filename) === true) { + process.nextTick(checkStats); + return; + } + this._activeEvents.delete(filename); + // ENOENT happens when the file/directory doesn't exist + // EPERM happens when the containing directory doesn't exist + if (err) { + if ( + err.code !== "ENOENT" && + err.code !== "EPERM" && + err.code !== "EBUSY" + ) { + this.onStatsError(err); + } else { + if (filename === path.basename(this.path)) { + // This may indicate that the directory itself was removed + if (!fs.existsSync(this.path)) { + this.onDirectoryRemoved("stat failed"); + } + } + } + } + this.lastWatchEvent = Date.now(); + if (!stats) { + this.setMissing(filePath, false, eventType); + } else if (stats.isDirectory()) { + this.setDirectory( + filePath, + +stats.birthtime || 1, + false, + eventType + ); + } else if (stats.isFile() || stats.isSymbolicLink()) { + if (stats.mtime) { + ensureFsAccuracy(stats.mtime); + } + this.setFileTime( + filePath, + +stats.mtime || +stats.ctime || 1, + false, + false, + eventType + ); + } + }); + }; + process.nextTick(checkStats); + } else { + this._activeEvents.set(filename, true); + } + } + + onWatcherError(err) { + if (this.closed) return; + if (err) { + if (err.code !== "EPERM" && err.code !== "ENOENT") { + console.error("Watchpack Error (watcher): " + err); + } + this.onDirectoryRemoved("watch error"); + } + } + + onStatsError(err) { + if (err) { + console.error("Watchpack Error (stats): " + err); + } + } + + onScanError(err) { + if (err) { + console.error("Watchpack Error (initial scan): " + err); + } + this.onScanFinished(); + } + + onScanFinished() { + if (this.polledWatching) { + this.timeout = setTimeout(() => { + if (this.closed) return; + this.doScan(false); + }, this.polledWatching); + } + } + + onDirectoryRemoved(reason) { + if (this.watcher) { + this.watcher.close(); + this.watcher = null; + } + this.watchInParentDirectory(); + const type = `directory-removed (${reason})`; + for (const directory of this.directories.keys()) { + this.setMissing(directory, null, type); + } + for (const file of this.files.keys()) { + this.setMissing(file, null, type); + } + } + + watchInParentDirectory() { + if (!this.parentWatcher) { + const parentDir = path.dirname(this.path); + // avoid watching in the root directory + // removing directories in the root directory is not supported + if (path.dirname(parentDir) === parentDir) return; + + this.parentWatcher = this.watcherManager.watchFile(this.path, 1); + this.parentWatcher.on("change", (mtime, type) => { + if (this.closed) return; + + // On non-osx platforms we don't need this watcher to detect + // directory removal, as an EPERM error indicates that + if ((!IS_OSX || this.polledWatching) && this.parentWatcher) { + this.parentWatcher.close(); + this.parentWatcher = null; + } + // Try to create the watcher when parent directory is found + if (!this.watcher) { + this.createWatcher(); + this.doScan(false); + + // directory was created so we emit an event + this.forEachWatcher(this.path, w => + w.emit("change", this.path, mtime, type, false) + ); + } + }); + this.parentWatcher.on("remove", () => { + this.onDirectoryRemoved("parent directory removed"); + }); + } + } + + doScan(initial) { + if (this.scanning) { + if (this.scanAgain) { + if (!initial) this.scanAgainInitial = false; + } else { + this.scanAgain = true; + this.scanAgainInitial = initial; + } + return; + } + this.scanning = true; + if (this.timeout) { + clearTimeout(this.timeout); + this.timeout = undefined; + } + process.nextTick(() => { + if (this.closed) return; + fs.readdir(this.path, (err, items) => { + if (this.closed) return; + if (err) { + if (err.code === "ENOENT" || err.code === "EPERM") { + this.onDirectoryRemoved("scan readdir failed"); + } else { + this.onScanError(err); + } + this.initialScan = false; + this.initialScanFinished = Date.now(); + if (initial) { + for (const watchers of this.watchers.values()) { + for (const watcher of watchers) { + if (watcher.checkStartTime(this.initialScanFinished, false)) { + watcher.emit( + "initial-missing", + "scan (parent directory missing in initial scan)" + ); + } + } + } + } + if (this.scanAgain) { + this.scanAgain = false; + this.doScan(this.scanAgainInitial); + } else { + this.scanning = false; + } + return; + } + const itemPaths = new Set( + items.map(item => path.join(this.path, item.normalize("NFC"))) + ); + for (const file of this.files.keys()) { + if (!itemPaths.has(file)) { + this.setMissing(file, initial, "scan (missing)"); + } + } + for (const directory of this.directories.keys()) { + if (!itemPaths.has(directory)) { + this.setMissing(directory, initial, "scan (missing)"); + } + } + if (this.scanAgain) { + // Early repeat of scan + this.scanAgain = false; + this.doScan(initial); + return; + } + const itemFinished = needCalls(itemPaths.size + 1, () => { + if (this.closed) return; + this.initialScan = false; + this.initialScanRemoved = null; + this.initialScanFinished = Date.now(); + if (initial) { + const missingWatchers = new Map(this.watchers); + missingWatchers.delete(withoutCase(this.path)); + for (const item of itemPaths) { + missingWatchers.delete(withoutCase(item)); + } + for (const watchers of missingWatchers.values()) { + for (const watcher of watchers) { + if (watcher.checkStartTime(this.initialScanFinished, false)) { + watcher.emit( + "initial-missing", + "scan (missing in initial scan)" + ); + } + } + } + } + if (this.scanAgain) { + this.scanAgain = false; + this.doScan(this.scanAgainInitial); + } else { + this.scanning = false; + this.onScanFinished(); + } + }); + for (const itemPath of itemPaths) { + fs.lstat(itemPath, (err2, stats) => { + if (this.closed) return; + if (err2) { + if ( + err2.code === "ENOENT" || + err2.code === "EPERM" || + err2.code === "EACCES" || + err2.code === "EBUSY" + ) { + this.setMissing(itemPath, initial, "scan (" + err2.code + ")"); + } else { + this.onScanError(err2); + } + itemFinished(); + return; + } + if (stats.isFile() || stats.isSymbolicLink()) { + if (stats.mtime) { + ensureFsAccuracy(stats.mtime); + } + this.setFileTime( + itemPath, + +stats.mtime || +stats.ctime || 1, + initial, + true, + "scan (file)" + ); + } else if (stats.isDirectory()) { + if (!initial || !this.directories.has(itemPath)) + this.setDirectory( + itemPath, + +stats.birthtime || 1, + initial, + "scan (dir)" + ); + } + itemFinished(); + }); + } + itemFinished(); + }); + }); + } + + getTimes() { + const obj = Object.create(null); + let safeTime = this.lastWatchEvent; + for (const [file, entry] of this.files) { + fixupEntryAccuracy(entry); + safeTime = Math.max(safeTime, entry.safeTime); + obj[file] = Math.max(entry.safeTime, entry.timestamp); + } + if (this.nestedWatching) { + for (const w of this.directories.values()) { + const times = w.directoryWatcher.getTimes(); + for (const file of Object.keys(times)) { + const time = times[file]; + safeTime = Math.max(safeTime, time); + obj[file] = time; + } + } + obj[this.path] = safeTime; + } + if (!this.initialScan) { + for (const watchers of this.watchers.values()) { + for (const watcher of watchers) { + const path = watcher.path; + if (!Object.prototype.hasOwnProperty.call(obj, path)) { + obj[path] = null; + } + } + } + } + return obj; + } + + collectTimeInfoEntries(fileTimestamps, directoryTimestamps) { + let safeTime = this.lastWatchEvent; + for (const [file, entry] of this.files) { + fixupEntryAccuracy(entry); + safeTime = Math.max(safeTime, entry.safeTime); + fileTimestamps.set(file, entry); + } + if (this.nestedWatching) { + for (const w of this.directories.values()) { + safeTime = Math.max( + safeTime, + w.directoryWatcher.collectTimeInfoEntries( + fileTimestamps, + directoryTimestamps + ) + ); + } + fileTimestamps.set(this.path, EXISTANCE_ONLY_TIME_ENTRY); + directoryTimestamps.set(this.path, { + safeTime + }); + } else { + for (const dir of this.directories.keys()) { + // No additional info about this directory + // but maybe another DirectoryWatcher has info + fileTimestamps.set(dir, EXISTANCE_ONLY_TIME_ENTRY); + if (!directoryTimestamps.has(dir)) + directoryTimestamps.set(dir, EXISTANCE_ONLY_TIME_ENTRY); + } + fileTimestamps.set(this.path, EXISTANCE_ONLY_TIME_ENTRY); + directoryTimestamps.set(this.path, EXISTANCE_ONLY_TIME_ENTRY); + } + if (!this.initialScan) { + for (const watchers of this.watchers.values()) { + for (const watcher of watchers) { + const path = watcher.path; + if (!fileTimestamps.has(path)) { + fileTimestamps.set(path, null); + } + } + } + } + return safeTime; + } + + close() { + this.closed = true; + this.initialScan = false; + if (this.watcher) { + this.watcher.close(); + this.watcher = null; + } + if (this.nestedWatching) { + for (const w of this.directories.values()) { + w.close(); + } + this.directories.clear(); + } + if (this.parentWatcher) { + this.parentWatcher.close(); + this.parentWatcher = null; + } + this.emit("closed"); + } +} + +module.exports = DirectoryWatcher; +module.exports.EXISTANCE_ONLY_TIME_ENTRY = EXISTANCE_ONLY_TIME_ENTRY; + +function fixupEntryAccuracy(entry) { + if (entry.accuracy > FS_ACCURACY) { + entry.safeTime = entry.safeTime - entry.accuracy + FS_ACCURACY; + entry.accuracy = FS_ACCURACY; + } +} + +function ensureFsAccuracy(mtime) { + if (!mtime) return; + if (FS_ACCURACY > 1 && mtime % 1 !== 0) FS_ACCURACY = 1; + else if (FS_ACCURACY > 10 && mtime % 10 !== 0) FS_ACCURACY = 10; + else if (FS_ACCURACY > 100 && mtime % 100 !== 0) FS_ACCURACY = 100; + else if (FS_ACCURACY > 1000 && mtime % 1000 !== 0) FS_ACCURACY = 1000; +} diff --git a/node_modules/watchpack/lib/LinkResolver.js b/node_modules/watchpack/lib/LinkResolver.js new file mode 100644 index 0000000..daea90b --- /dev/null +++ b/node_modules/watchpack/lib/LinkResolver.js @@ -0,0 +1,107 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const fs = require("fs"); +const path = require("path"); + +// macOS, Linux, and Windows all rely on these errors +const EXPECTED_ERRORS = new Set(["EINVAL", "ENOENT"]); + +// On Windows there is also this error in some cases +if (process.platform === "win32") EXPECTED_ERRORS.add("UNKNOWN"); + +class LinkResolver { + constructor() { + this.cache = new Map(); + } + + /** + * @param {string} file path to file or directory + * @returns {string[]} array of file and all symlinks contributed in the resolving process (first item is the resolved file) + */ + resolve(file) { + const cacheEntry = this.cache.get(file); + if (cacheEntry !== undefined) { + return cacheEntry; + } + const parent = path.dirname(file); + if (parent === file) { + // At root of filesystem there can't be a link + const result = Object.freeze([file]); + this.cache.set(file, result); + return result; + } + // resolve the parent directory to find links there and get the real path + const parentResolved = this.resolve(parent); + let realFile = file; + + // is the parent directory really somewhere else? + if (parentResolved[0] !== parent) { + // get the real location of file + const basename = path.basename(file); + realFile = path.resolve(parentResolved[0], basename); + } + // try to read the link content + try { + const linkContent = fs.readlinkSync(realFile); + + // resolve the link content relative to the parent directory + const resolvedLink = path.resolve(parentResolved[0], linkContent); + + // recursive resolve the link content for more links in the structure + const linkResolved = this.resolve(resolvedLink); + + // merge parent and link resolve results + let result; + if (linkResolved.length > 1 && parentResolved.length > 1) { + // when both contain links we need to duplicate them with a Set + const resultSet = new Set(linkResolved); + // add the link + resultSet.add(realFile); + // add all symlinks of the parent + for (let i = 1; i < parentResolved.length; i++) { + resultSet.add(parentResolved[i]); + } + result = Object.freeze(Array.from(resultSet)); + } else if (parentResolved.length > 1) { + // we have links in the parent but not for the link content location + result = parentResolved.slice(); + result[0] = linkResolved[0]; + // add the link + result.push(realFile); + Object.freeze(result); + } else if (linkResolved.length > 1) { + // we can return the link content location result + result = linkResolved.slice(); + // add the link + result.push(realFile); + Object.freeze(result); + } else { + // neither link content location nor parent have links + // this link is the only link here + result = Object.freeze([ + // the resolve real location + linkResolved[0], + // add the link + realFile + ]); + } + this.cache.set(file, result); + return result; + } catch (e) { + if (!EXPECTED_ERRORS.has(e.code)) { + throw e; + } + // no link + const result = parentResolved.slice(); + result[0] = realFile; + Object.freeze(result); + this.cache.set(file, result); + return result; + } + } +} +module.exports = LinkResolver; diff --git a/node_modules/watchpack/lib/getWatcherManager.js b/node_modules/watchpack/lib/getWatcherManager.js new file mode 100644 index 0000000..e0dcd6a --- /dev/null +++ b/node_modules/watchpack/lib/getWatcherManager.js @@ -0,0 +1,52 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const path = require("path"); +const DirectoryWatcher = require("./DirectoryWatcher"); + +class WatcherManager { + constructor(options) { + this.options = options; + this.directoryWatchers = new Map(); + } + + getDirectoryWatcher(directory) { + const watcher = this.directoryWatchers.get(directory); + if (watcher === undefined) { + const newWatcher = new DirectoryWatcher(this, directory, this.options); + this.directoryWatchers.set(directory, newWatcher); + newWatcher.on("closed", () => { + this.directoryWatchers.delete(directory); + }); + return newWatcher; + } + return watcher; + } + + watchFile(p, startTime) { + const directory = path.dirname(p); + if (directory === p) return null; + return this.getDirectoryWatcher(directory).watch(p, startTime); + } + + watchDirectory(directory, startTime) { + return this.getDirectoryWatcher(directory).watch(directory, startTime); + } +} + +const watcherManagers = new WeakMap(); +/** + * @param {object} options options + * @returns {WatcherManager} the watcher manager + */ +module.exports = options => { + const watcherManager = watcherManagers.get(options); + if (watcherManager !== undefined) return watcherManager; + const newWatcherManager = new WatcherManager(options); + watcherManagers.set(options, newWatcherManager); + return newWatcherManager; +}; +module.exports.WatcherManager = WatcherManager; diff --git a/node_modules/watchpack/lib/reducePlan.js b/node_modules/watchpack/lib/reducePlan.js new file mode 100644 index 0000000..b281ed6 --- /dev/null +++ b/node_modules/watchpack/lib/reducePlan.js @@ -0,0 +1,138 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const path = require("path"); + +/** + * @template T + * @typedef {Object} TreeNode + * @property {string} filePath + * @property {TreeNode} parent + * @property {TreeNode[]} children + * @property {number} entries + * @property {boolean} active + * @property {T[] | T | undefined} value + */ + +/** + * @template T + * @param {Map>} the new plan + */ +module.exports = (plan, limit) => { + const treeMap = new Map(); + // Convert to tree + for (const [filePath, value] of plan) { + treeMap.set(filePath, { + filePath, + parent: undefined, + children: undefined, + entries: 1, + active: true, + value + }); + } + let currentCount = treeMap.size; + // Create parents and calculate sum of entries + for (const node of treeMap.values()) { + const parentPath = path.dirname(node.filePath); + if (parentPath !== node.filePath) { + let parent = treeMap.get(parentPath); + if (parent === undefined) { + parent = { + filePath: parentPath, + parent: undefined, + children: [node], + entries: node.entries, + active: false, + value: undefined + }; + treeMap.set(parentPath, parent); + node.parent = parent; + } else { + node.parent = parent; + if (parent.children === undefined) { + parent.children = [node]; + } else { + parent.children.push(node); + } + do { + parent.entries += node.entries; + parent = parent.parent; + } while (parent); + } + } + } + // Reduce until limit reached + while (currentCount > limit) { + // Select node that helps reaching the limit most effectively without overmerging + const overLimit = currentCount - limit; + let bestNode = undefined; + let bestCost = Infinity; + for (const node of treeMap.values()) { + if (node.entries <= 1 || !node.children || !node.parent) continue; + if (node.children.length === 0) continue; + if (node.children.length === 1 && !node.value) continue; + // Try to select the node with has just a bit more entries than we need to reduce + // When just a bit more is over 30% over the limit, + // also consider just a bit less entries then we need to reduce + const cost = + node.entries - 1 >= overLimit + ? node.entries - 1 - overLimit + : overLimit - node.entries + 1 + limit * 0.3; + if (cost < bestCost) { + bestNode = node; + bestCost = cost; + } + } + if (!bestNode) break; + // Merge all children + const reduction = bestNode.entries - 1; + bestNode.active = true; + bestNode.entries = 1; + currentCount -= reduction; + let parent = bestNode.parent; + while (parent) { + parent.entries -= reduction; + parent = parent.parent; + } + const queue = new Set(bestNode.children); + for (const node of queue) { + node.active = false; + node.entries = 0; + if (node.children) { + for (const child of node.children) queue.add(child); + } + } + } + // Write down new plan + const newPlan = new Map(); + for (const rootNode of treeMap.values()) { + if (!rootNode.active) continue; + const map = new Map(); + const queue = new Set([rootNode]); + for (const node of queue) { + if (node.active && node !== rootNode) continue; + if (node.value) { + if (Array.isArray(node.value)) { + for (const item of node.value) { + map.set(item, node.filePath); + } + } else { + map.set(node.value, node.filePath); + } + } + if (node.children) { + for (const child of node.children) { + queue.add(child); + } + } + } + newPlan.set(rootNode.filePath, map); + } + return newPlan; +}; diff --git a/node_modules/watchpack/lib/watchEventSource.js b/node_modules/watchpack/lib/watchEventSource.js new file mode 100644 index 0000000..6df9ab0 --- /dev/null +++ b/node_modules/watchpack/lib/watchEventSource.js @@ -0,0 +1,333 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const fs = require("fs"); +const path = require("path"); +const { EventEmitter } = require("events"); +const reducePlan = require("./reducePlan"); + +const IS_OSX = require("os").platform() === "darwin"; +const IS_WIN = require("os").platform() === "win32"; +const SUPPORTS_RECURSIVE_WATCHING = IS_OSX || IS_WIN; + +const watcherLimit = + +process.env.WATCHPACK_WATCHER_LIMIT || (IS_OSX ? 2000 : 10000); + +const recursiveWatcherLogging = !!process.env + .WATCHPACK_RECURSIVE_WATCHER_LOGGING; + +let isBatch = false; +let watcherCount = 0; + +/** @type {Map} */ +const pendingWatchers = new Map(); + +/** @type {Map} */ +const recursiveWatchers = new Map(); + +/** @type {Map} */ +const directWatchers = new Map(); + +/** @type {Map} */ +const underlyingWatcher = new Map(); + +class DirectWatcher { + constructor(filePath) { + this.filePath = filePath; + this.watchers = new Set(); + this.watcher = undefined; + try { + const watcher = fs.watch(filePath); + this.watcher = watcher; + watcher.on("change", (type, filename) => { + for (const w of this.watchers) { + w.emit("change", type, filename); + } + }); + watcher.on("error", error => { + for (const w of this.watchers) { + w.emit("error", error); + } + }); + } catch (err) { + process.nextTick(() => { + for (const w of this.watchers) { + w.emit("error", err); + } + }); + } + watcherCount++; + } + + add(watcher) { + underlyingWatcher.set(watcher, this); + this.watchers.add(watcher); + } + + remove(watcher) { + this.watchers.delete(watcher); + if (this.watchers.size === 0) { + directWatchers.delete(this.filePath); + watcherCount--; + if (this.watcher) this.watcher.close(); + } + } + + getWatchers() { + return this.watchers; + } +} + +class RecursiveWatcher { + constructor(rootPath) { + this.rootPath = rootPath; + /** @type {Map} */ + this.mapWatcherToPath = new Map(); + /** @type {Map>} */ + this.mapPathToWatchers = new Map(); + this.watcher = undefined; + try { + const watcher = fs.watch(rootPath, { + recursive: true + }); + this.watcher = watcher; + watcher.on("change", (type, filename) => { + if (!filename) { + if (recursiveWatcherLogging) { + process.stderr.write( + `[watchpack] dispatch ${type} event in recursive watcher (${this.rootPath}) to all watchers\n` + ); + } + for (const w of this.mapWatcherToPath.keys()) { + w.emit("change", type); + } + } else { + const dir = path.dirname(filename); + const watchers = this.mapPathToWatchers.get(dir); + if (recursiveWatcherLogging) { + process.stderr.write( + `[watchpack] dispatch ${type} event in recursive watcher (${ + this.rootPath + }) for '${filename}' to ${ + watchers ? watchers.size : 0 + } watchers\n` + ); + } + if (watchers === undefined) return; + for (const w of watchers) { + w.emit("change", type, path.basename(filename)); + } + } + }); + watcher.on("error", error => { + for (const w of this.mapWatcherToPath.keys()) { + w.emit("error", error); + } + }); + } catch (err) { + process.nextTick(() => { + for (const w of this.mapWatcherToPath.keys()) { + w.emit("error", err); + } + }); + } + watcherCount++; + if (recursiveWatcherLogging) { + process.stderr.write( + `[watchpack] created recursive watcher at ${rootPath}\n` + ); + } + } + + add(filePath, watcher) { + underlyingWatcher.set(watcher, this); + const subpath = filePath.slice(this.rootPath.length + 1) || "."; + this.mapWatcherToPath.set(watcher, subpath); + const set = this.mapPathToWatchers.get(subpath); + if (set === undefined) { + const newSet = new Set(); + newSet.add(watcher); + this.mapPathToWatchers.set(subpath, newSet); + } else { + set.add(watcher); + } + } + + remove(watcher) { + const subpath = this.mapWatcherToPath.get(watcher); + if (!subpath) return; + this.mapWatcherToPath.delete(watcher); + const set = this.mapPathToWatchers.get(subpath); + set.delete(watcher); + if (set.size === 0) { + this.mapPathToWatchers.delete(subpath); + } + if (this.mapWatcherToPath.size === 0) { + recursiveWatchers.delete(this.rootPath); + watcherCount--; + if (this.watcher) this.watcher.close(); + if (recursiveWatcherLogging) { + process.stderr.write( + `[watchpack] closed recursive watcher at ${this.rootPath}\n` + ); + } + } + } + + getWatchers() { + return this.mapWatcherToPath; + } +} + +class Watcher extends EventEmitter { + close() { + if (pendingWatchers.has(this)) { + pendingWatchers.delete(this); + return; + } + const watcher = underlyingWatcher.get(this); + watcher.remove(this); + underlyingWatcher.delete(this); + } +} + +const createDirectWatcher = filePath => { + const existing = directWatchers.get(filePath); + if (existing !== undefined) return existing; + const w = new DirectWatcher(filePath); + directWatchers.set(filePath, w); + return w; +}; + +const createRecursiveWatcher = rootPath => { + const existing = recursiveWatchers.get(rootPath); + if (existing !== undefined) return existing; + const w = new RecursiveWatcher(rootPath); + recursiveWatchers.set(rootPath, w); + return w; +}; + +const execute = () => { + /** @type {Map} */ + const map = new Map(); + const addWatcher = (watcher, filePath) => { + const entry = map.get(filePath); + if (entry === undefined) { + map.set(filePath, watcher); + } else if (Array.isArray(entry)) { + entry.push(watcher); + } else { + map.set(filePath, [entry, watcher]); + } + }; + for (const [watcher, filePath] of pendingWatchers) { + addWatcher(watcher, filePath); + } + pendingWatchers.clear(); + + // Fast case when we are not reaching the limit + if (!SUPPORTS_RECURSIVE_WATCHING || watcherLimit - watcherCount >= map.size) { + // Create watchers for all entries in the map + for (const [filePath, entry] of map) { + const w = createDirectWatcher(filePath); + if (Array.isArray(entry)) { + for (const item of entry) w.add(item); + } else { + w.add(entry); + } + } + return; + } + + // Reconsider existing watchers to improving watch plan + for (const watcher of recursiveWatchers.values()) { + for (const [w, subpath] of watcher.getWatchers()) { + addWatcher(w, path.join(watcher.rootPath, subpath)); + } + } + for (const watcher of directWatchers.values()) { + for (const w of watcher.getWatchers()) { + addWatcher(w, watcher.filePath); + } + } + + // Merge map entries to keep watcher limit + // Create a 10% buffer to be able to enter fast case more often + const plan = reducePlan(map, watcherLimit * 0.9); + + // Update watchers for all entries in the map + for (const [filePath, entry] of plan) { + if (entry.size === 1) { + for (const [watcher, filePath] of entry) { + const w = createDirectWatcher(filePath); + const old = underlyingWatcher.get(watcher); + if (old === w) continue; + w.add(watcher); + if (old !== undefined) old.remove(watcher); + } + } else { + const filePaths = new Set(entry.values()); + if (filePaths.size > 1) { + const w = createRecursiveWatcher(filePath); + for (const [watcher, watcherPath] of entry) { + const old = underlyingWatcher.get(watcher); + if (old === w) continue; + w.add(watcherPath, watcher); + if (old !== undefined) old.remove(watcher); + } + } else { + for (const filePath of filePaths) { + const w = createDirectWatcher(filePath); + for (const watcher of entry.keys()) { + const old = underlyingWatcher.get(watcher); + if (old === w) continue; + w.add(watcher); + if (old !== undefined) old.remove(watcher); + } + } + } + } + } +}; + +exports.watch = filePath => { + const watcher = new Watcher(); + // Find an existing watcher + const directWatcher = directWatchers.get(filePath); + if (directWatcher !== undefined) { + directWatcher.add(watcher); + return watcher; + } + let current = filePath; + for (;;) { + const recursiveWatcher = recursiveWatchers.get(current); + if (recursiveWatcher !== undefined) { + recursiveWatcher.add(filePath, watcher); + return watcher; + } + const parent = path.dirname(current); + if (parent === current) break; + current = parent; + } + // Queue up watcher for creation + pendingWatchers.set(watcher, filePath); + if (!isBatch) execute(); + return watcher; +}; + +exports.batch = fn => { + isBatch = true; + try { + fn(); + } finally { + isBatch = false; + execute(); + } +}; + +exports.getNumberOfWatchers = () => { + return watcherCount; +}; diff --git a/node_modules/watchpack/lib/watchpack.js b/node_modules/watchpack/lib/watchpack.js new file mode 100644 index 0000000..0b567fc --- /dev/null +++ b/node_modules/watchpack/lib/watchpack.js @@ -0,0 +1,393 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const getWatcherManager = require("./getWatcherManager"); +const LinkResolver = require("./LinkResolver"); +const EventEmitter = require("events").EventEmitter; +const globToRegExp = require("glob-to-regexp"); +const watchEventSource = require("./watchEventSource"); + +const EMPTY_ARRAY = []; +const EMPTY_OPTIONS = {}; + +function addWatchersToSet(watchers, set) { + for (const ww of watchers) { + const w = ww.watcher; + if (!set.has(w.directoryWatcher)) { + set.add(w.directoryWatcher); + } + } +} + +const stringToRegexp = ignored => { + if (ignored.length === 0) { + return; + } + const source = globToRegExp(ignored, { globstar: true, extended: true }) + .source; + return source.slice(0, source.length - 1) + "(?:$|\\/)"; +}; + +const ignoredToFunction = ignored => { + if (Array.isArray(ignored)) { + const stringRegexps = ignored.map(i => stringToRegexp(i)).filter(Boolean); + if (stringRegexps.length === 0) { + return () => false; + } + const regexp = new RegExp(stringRegexps.join("|")); + return x => regexp.test(x.replace(/\\/g, "/")); + } else if (typeof ignored === "string") { + const stringRegexp = stringToRegexp(ignored); + if (!stringRegexp) { + return () => false; + } + const regexp = new RegExp(stringRegexp); + return x => regexp.test(x.replace(/\\/g, "/")); + } else if (ignored instanceof RegExp) { + return x => ignored.test(x.replace(/\\/g, "/")); + } else if (ignored instanceof Function) { + return ignored; + } else if (ignored) { + throw new Error(`Invalid option for 'ignored': ${ignored}`); + } else { + return () => false; + } +}; + +const normalizeOptions = options => { + return { + followSymlinks: !!options.followSymlinks, + ignored: ignoredToFunction(options.ignored), + poll: options.poll + }; +}; + +const normalizeCache = new WeakMap(); +const cachedNormalizeOptions = options => { + const cacheEntry = normalizeCache.get(options); + if (cacheEntry !== undefined) return cacheEntry; + const normalized = normalizeOptions(options); + normalizeCache.set(options, normalized); + return normalized; +}; + +class WatchpackFileWatcher { + constructor(watchpack, watcher, files) { + this.files = Array.isArray(files) ? files : [files]; + this.watcher = watcher; + watcher.on("initial-missing", type => { + for (const file of this.files) { + if (!watchpack._missing.has(file)) + watchpack._onRemove(file, file, type); + } + }); + watcher.on("change", (mtime, type) => { + for (const file of this.files) { + watchpack._onChange(file, mtime, file, type); + } + }); + watcher.on("remove", type => { + for (const file of this.files) { + watchpack._onRemove(file, file, type); + } + }); + } + + update(files) { + if (!Array.isArray(files)) { + if (this.files.length !== 1) { + this.files = [files]; + } else if (this.files[0] !== files) { + this.files[0] = files; + } + } else { + this.files = files; + } + } + + close() { + this.watcher.close(); + } +} + +class WatchpackDirectoryWatcher { + constructor(watchpack, watcher, directories) { + this.directories = Array.isArray(directories) ? directories : [directories]; + this.watcher = watcher; + watcher.on("initial-missing", type => { + for (const item of this.directories) { + watchpack._onRemove(item, item, type); + } + }); + watcher.on("change", (file, mtime, type) => { + for (const item of this.directories) { + watchpack._onChange(item, mtime, file, type); + } + }); + watcher.on("remove", type => { + for (const item of this.directories) { + watchpack._onRemove(item, item, type); + } + }); + } + + update(directories) { + if (!Array.isArray(directories)) { + if (this.directories.length !== 1) { + this.directories = [directories]; + } else if (this.directories[0] !== directories) { + this.directories[0] = directories; + } + } else { + this.directories = directories; + } + } + + close() { + this.watcher.close(); + } +} + +class Watchpack extends EventEmitter { + constructor(options) { + super(); + if (!options) options = EMPTY_OPTIONS; + this.options = options; + this.aggregateTimeout = + typeof options.aggregateTimeout === "number" + ? options.aggregateTimeout + : 200; + this.watcherOptions = cachedNormalizeOptions(options); + this.watcherManager = getWatcherManager(this.watcherOptions); + this.fileWatchers = new Map(); + this.directoryWatchers = new Map(); + this._missing = new Set(); + this.startTime = undefined; + this.paused = false; + this.aggregatedChanges = new Set(); + this.aggregatedRemovals = new Set(); + this.aggregateTimer = undefined; + this._onTimeout = this._onTimeout.bind(this); + } + + watch(arg1, arg2, arg3) { + let files, directories, missing, startTime; + if (!arg2) { + ({ + files = EMPTY_ARRAY, + directories = EMPTY_ARRAY, + missing = EMPTY_ARRAY, + startTime + } = arg1); + } else { + files = arg1; + directories = arg2; + missing = EMPTY_ARRAY; + startTime = arg3; + } + this.paused = false; + const fileWatchers = this.fileWatchers; + const directoryWatchers = this.directoryWatchers; + const ignored = this.watcherOptions.ignored; + const filter = path => !ignored(path); + const addToMap = (map, key, item) => { + const list = map.get(key); + if (list === undefined) { + map.set(key, item); + } else if (Array.isArray(list)) { + list.push(item); + } else { + map.set(key, [list, item]); + } + }; + const fileWatchersNeeded = new Map(); + const directoryWatchersNeeded = new Map(); + const missingFiles = new Set(); + if (this.watcherOptions.followSymlinks) { + const resolver = new LinkResolver(); + for (const file of files) { + if (filter(file)) { + for (const innerFile of resolver.resolve(file)) { + if (file === innerFile || filter(innerFile)) { + addToMap(fileWatchersNeeded, innerFile, file); + } + } + } + } + for (const file of missing) { + if (filter(file)) { + for (const innerFile of resolver.resolve(file)) { + if (file === innerFile || filter(innerFile)) { + missingFiles.add(file); + addToMap(fileWatchersNeeded, innerFile, file); + } + } + } + } + for (const dir of directories) { + if (filter(dir)) { + let first = true; + for (const innerItem of resolver.resolve(dir)) { + if (filter(innerItem)) { + addToMap( + first ? directoryWatchersNeeded : fileWatchersNeeded, + innerItem, + dir + ); + } + first = false; + } + } + } + } else { + for (const file of files) { + if (filter(file)) { + addToMap(fileWatchersNeeded, file, file); + } + } + for (const file of missing) { + if (filter(file)) { + missingFiles.add(file); + addToMap(fileWatchersNeeded, file, file); + } + } + for (const dir of directories) { + if (filter(dir)) { + addToMap(directoryWatchersNeeded, dir, dir); + } + } + } + // Close unneeded old watchers + // and update existing watchers + for (const [key, w] of fileWatchers) { + const needed = fileWatchersNeeded.get(key); + if (needed === undefined) { + w.close(); + fileWatchers.delete(key); + } else { + w.update(needed); + fileWatchersNeeded.delete(key); + } + } + for (const [key, w] of directoryWatchers) { + const needed = directoryWatchersNeeded.get(key); + if (needed === undefined) { + w.close(); + directoryWatchers.delete(key); + } else { + w.update(needed); + directoryWatchersNeeded.delete(key); + } + } + // Create new watchers and install handlers on these watchers + watchEventSource.batch(() => { + for (const [key, files] of fileWatchersNeeded) { + const watcher = this.watcherManager.watchFile(key, startTime); + if (watcher) { + fileWatchers.set(key, new WatchpackFileWatcher(this, watcher, files)); + } + } + for (const [key, directories] of directoryWatchersNeeded) { + const watcher = this.watcherManager.watchDirectory(key, startTime); + if (watcher) { + directoryWatchers.set( + key, + new WatchpackDirectoryWatcher(this, watcher, directories) + ); + } + } + }); + this._missing = missingFiles; + this.startTime = startTime; + } + + close() { + this.paused = true; + if (this.aggregateTimer) clearTimeout(this.aggregateTimer); + for (const w of this.fileWatchers.values()) w.close(); + for (const w of this.directoryWatchers.values()) w.close(); + this.fileWatchers.clear(); + this.directoryWatchers.clear(); + } + + pause() { + this.paused = true; + if (this.aggregateTimer) clearTimeout(this.aggregateTimer); + } + + getTimes() { + const directoryWatchers = new Set(); + addWatchersToSet(this.fileWatchers.values(), directoryWatchers); + addWatchersToSet(this.directoryWatchers.values(), directoryWatchers); + const obj = Object.create(null); + for (const w of directoryWatchers) { + const times = w.getTimes(); + for (const file of Object.keys(times)) obj[file] = times[file]; + } + return obj; + } + + getTimeInfoEntries() { + const map = new Map(); + this.collectTimeInfoEntries(map, map); + return map; + } + + collectTimeInfoEntries(fileTimestamps, directoryTimestamps) { + const allWatchers = new Set(); + addWatchersToSet(this.fileWatchers.values(), allWatchers); + addWatchersToSet(this.directoryWatchers.values(), allWatchers); + const safeTime = { value: 0 }; + for (const w of allWatchers) { + w.collectTimeInfoEntries(fileTimestamps, directoryTimestamps, safeTime); + } + } + + getAggregated() { + if (this.aggregateTimer) { + clearTimeout(this.aggregateTimer); + this.aggregateTimer = undefined; + } + const changes = this.aggregatedChanges; + const removals = this.aggregatedRemovals; + this.aggregatedChanges = new Set(); + this.aggregatedRemovals = new Set(); + return { changes, removals }; + } + + _onChange(item, mtime, file, type) { + file = file || item; + if (!this.paused) { + this.emit("change", file, mtime, type); + if (this.aggregateTimer) clearTimeout(this.aggregateTimer); + this.aggregateTimer = setTimeout(this._onTimeout, this.aggregateTimeout); + } + this.aggregatedRemovals.delete(item); + this.aggregatedChanges.add(item); + } + + _onRemove(item, file, type) { + file = file || item; + if (!this.paused) { + this.emit("remove", file, type); + if (this.aggregateTimer) clearTimeout(this.aggregateTimer); + this.aggregateTimer = setTimeout(this._onTimeout, this.aggregateTimeout); + } + this.aggregatedChanges.delete(item); + this.aggregatedRemovals.add(item); + } + + _onTimeout() { + this.aggregateTimer = undefined; + const changes = this.aggregatedChanges; + const removals = this.aggregatedRemovals; + this.aggregatedChanges = new Set(); + this.aggregatedRemovals = new Set(); + this.emit("aggregated", changes, removals); + } +} + +module.exports = Watchpack; diff --git a/node_modules/watchpack/package.json b/node_modules/watchpack/package.json new file mode 100644 index 0000000..997e606 --- /dev/null +++ b/node_modules/watchpack/package.json @@ -0,0 +1,49 @@ +{ + "name": "watchpack", + "version": "2.4.2", + "description": "", + "main": "./lib/watchpack.js", + "directories": { + "test": "test" + }, + "files": [ + "lib/" + ], + "scripts": { + "pretty-files": "prettier \"lib/**.*\" \"test/**/*.js\" --write", + "lint": "eslint lib", + "test:only": "mocha", + "test:coverage": "istanbul cover node_modules/mocha/bin/_mocha", + "pretest": "yarn lint", + "test": "mocha" + }, + "repository": { + "type": "git", + "url": "https://github.com/webpack/watchpack.git" + }, + "author": "Tobias Koppers @sokra", + "license": "MIT", + "bugs": { + "url": "https://github.com/webpack/watchpack/issues" + }, + "homepage": "https://github.com/webpack/watchpack", + "devDependencies": { + "coveralls": "^3.0.0", + "eslint": "^5.11.1", + "eslint-config-prettier": "^4.3.0", + "eslint-plugin-prettier": "^3.1.0", + "istanbul": "^0.4.3", + "mocha": "^5.0.1", + "prettier": "^1.11.0", + "rimraf": "^2.6.2", + "should": "^8.3.1", + "write-file-atomic": "^3.0.1" + }, + "dependencies": { + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.1.2" + }, + "engines": { + "node": ">=10.13.0" + } +} diff --git a/node_modules/webpack-sources/LICENSE b/node_modules/webpack-sources/LICENSE new file mode 100644 index 0000000..7c6f895 --- /dev/null +++ b/node_modules/webpack-sources/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 JS Foundation and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/webpack-sources/README.md b/node_modules/webpack-sources/README.md new file mode 100644 index 0000000..5372884 --- /dev/null +++ b/node_modules/webpack-sources/README.md @@ -0,0 +1,228 @@ +# webpack-sources + +Contains multiple classes which represent a `Source`. A `Source` can be asked for source code, size, source map and hash. + +## `Source` + +Base class for all sources. + +### Public methods + +All methods should be considered as expensive as they may need to do computations. + +#### `source` + +```typescript +Source.prototype.source() -> String | Buffer +``` + +Returns the represented source code as string or Buffer (for binary Sources). + +#### `buffer` + +```typescript +Source.prototype.buffer() -> Buffer +``` + +Returns the represented source code as Buffer. Strings are converted to utf-8. + +#### `size` + +```typescript +Source.prototype.size() -> Number +``` + +Returns the size in bytes of the represented source code. + +#### `map` + +```typescript +Source.prototype.map(options?: Object) -> Object | null +``` + +Returns the SourceMap of the represented source code as JSON. May return `null` if no SourceMap is available. + +The `options` object can contain the following keys: + +- `columns: Boolean` (default `true`): If set to false the implementation may omit mappings for columns. + +#### `sourceAndMap` + +```typescript +Source.prototype.sourceAndMap(options?: Object) -> { + source: String | Buffer, + map: Object | null +} +``` + +Returns both, source code (like `Source.prototype.source()` and SourceMap (like `Source.prototype.map()`). This method could have better performance than calling `source()` and `map()` separately. + +See `map()` for `options`. + +#### `updateHash` + +```typescript +Source.prototype.updateHash(hash: Hash) -> void +``` + +Updates the provided `Hash` object with the content of the represented source code. (`Hash` is an object with an `update` method, which is called with string values) + +## `RawSource` + +Represents source code without SourceMap. + +```typescript +new RawSource(sourceCode: String | Buffer) +``` + +## `OriginalSource` + +Represents source code, which is a copy of the original file. + +```typescript +new OriginalSource( + sourceCode: String | Buffer, + name: String +) +``` + +- `sourceCode`: The source code. +- `name`: The filename of the original source code. + +OriginalSource tries to create column mappings if requested, by splitting the source code at typical statement borders (`;`, `{`, `}`). + +## `SourceMapSource` + +Represents source code with SourceMap, optionally having an additional SourceMap for the original source. + +```typescript +new SourceMapSource( + sourceCode: String | Buffer, + name: String, + sourceMap: Object | String | Buffer, + originalSource?: String | Buffer, + innerSourceMap?: Object | String | Buffer, + removeOriginalSource?: boolean +) +``` + +- `sourceCode`: The source code. +- `name`: The filename of the original source code. +- `sourceMap`: The SourceMap for the source code. +- `originalSource`: The source code of the original file. Can be omitted if the `sourceMap` already contains the original source code. +- `innerSourceMap`: The SourceMap for the `originalSource`/`name`. +- `removeOriginalSource`: Removes the source code for `name` from the final map, keeping only the deeper mappings for that file. + +The `SourceMapSource` supports "identity" mappings for the `innerSourceMap`. +When original source matches generated source for a mapping it's assumed to be mapped char by char allowing to keep finer mappings from `sourceMap`. + +## `CachedSource` + +Decorates a `Source` and caches returned results of `map`, `source`, `buffer`, `size` and `sourceAndMap` in memory. `updateHash` is not cached. +It tries to reused cached results from other methods to avoid calculations, i. e. when `source` is already cached, calling `size` will get the size from the cached source, calling `sourceAndMap` will only call `map` on the wrapped Source. + +```typescript +new CachedSource(source: Source) +new CachedSource(source: Source | () => Source, cachedData?: CachedData) +``` + +Instead of passing a `Source` object directly one can pass an function that returns a `Source` object. The function is only called when needed and once. + +### Public methods + +#### `getCachedData()` + +Returns the cached data for passing to the constructor. All cached entries are converted to Buffers and strings are avoided. + +#### `original()` + +Returns the original `Source` object. + +#### `originalLazy()` + +Returns the original `Source` object or a function returning these. + +## `PrefixSource` + +Prefix every line of the decorated `Source` with a provided string. + +```typescript +new PrefixSource( + prefix: String, + source: Source | String | Buffer +) +``` + +## `ConcatSource` + +Concatenate multiple `Source`s or strings to a single source. + +```typescript +new ConcatSource( + ...items?: Source | String +) +``` + +### Public methods + +#### `add` + +```typescript +ConcatSource.prototype.add(item: Source | String) +``` + +Adds an item to the source. + +## `ReplaceSource` + +Decorates a `Source` with replacements and insertions of source code. + +The `ReplaceSource` supports "identity" mappings for child source. +When original source matches generated source for a mapping it's assumed to be mapped char by char allowing to split mappings at replacements/insertions. + +### Public methods + +#### `replace` + +```typescript +ReplaceSource.prototype.replace( + start: Number, + end: Number, + replacement: String +) +``` + +Replaces chars from `start` (0-indexed, inclusive) to `end` (0-indexed, inclusive) with `replacement`. + +Locations represents locations in the original source and are not influenced by other replacements or insertions. + +#### `insert` + +```typescript +ReplaceSource.prototype.insert( + pos: Number, + insertion: String +) +``` + +Inserts the `insertion` before char `pos` (0-indexed). + +Location represents location in the original source and is not influenced by other replacements or insertions. + +#### `original` + +Get decorated `Source`. + +## `CompatSource` + +Converts a Source-like object into a real Source object. + +### Public methods + +#### static `from` + +```typescript +CompatSource.from(sourceLike: any | Source) +``` + +If `sourceLike` is a real Source it returns it unmodified. Otherwise it returns it wrapped in a CompatSource. diff --git a/node_modules/webpack-sources/lib/CachedSource.js b/node_modules/webpack-sources/lib/CachedSource.js new file mode 100644 index 0000000..5fc2d4c --- /dev/null +++ b/node_modules/webpack-sources/lib/CachedSource.js @@ -0,0 +1,274 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Source = require("./Source"); +const streamChunksOfSourceMap = require("./helpers/streamChunksOfSourceMap"); +const streamChunksOfRawSource = require("./helpers/streamChunksOfRawSource"); +const streamAndGetSourceAndMap = require("./helpers/streamAndGetSourceAndMap"); + +const mapToBufferedMap = map => { + if (typeof map !== "object" || !map) return map; + const bufferedMap = Object.assign({}, map); + if (map.mappings) { + bufferedMap.mappings = Buffer.from(map.mappings, "utf-8"); + } + if (map.sourcesContent) { + bufferedMap.sourcesContent = map.sourcesContent.map( + str => str && Buffer.from(str, "utf-8") + ); + } + return bufferedMap; +}; + +const bufferedMapToMap = bufferedMap => { + if (typeof bufferedMap !== "object" || !bufferedMap) return bufferedMap; + const map = Object.assign({}, bufferedMap); + if (bufferedMap.mappings) { + map.mappings = bufferedMap.mappings.toString("utf-8"); + } + if (bufferedMap.sourcesContent) { + map.sourcesContent = bufferedMap.sourcesContent.map( + buffer => buffer && buffer.toString("utf-8") + ); + } + return map; +}; + +class CachedSource extends Source { + constructor(source, cachedData) { + super(); + this._source = source; + this._cachedSourceType = cachedData ? cachedData.source : undefined; + this._cachedSource = undefined; + this._cachedBuffer = cachedData ? cachedData.buffer : undefined; + this._cachedSize = cachedData ? cachedData.size : undefined; + this._cachedMaps = cachedData ? cachedData.maps : new Map(); + this._cachedHashUpdate = cachedData ? cachedData.hash : undefined; + } + + getCachedData() { + const bufferedMaps = new Map(); + for (const pair of this._cachedMaps) { + let cacheEntry = pair[1]; + if (cacheEntry.bufferedMap === undefined) { + cacheEntry.bufferedMap = mapToBufferedMap( + this._getMapFromCacheEntry(cacheEntry) + ); + } + bufferedMaps.set(pair[0], { + map: undefined, + bufferedMap: cacheEntry.bufferedMap + }); + } + // We don't want to cache strings + // So if we have a caches sources + // create a buffer from it and only store + // if it was a Buffer or string + if (this._cachedSource) { + this.buffer(); + } + return { + buffer: this._cachedBuffer, + source: + this._cachedSourceType !== undefined + ? this._cachedSourceType + : typeof this._cachedSource === "string" + ? true + : Buffer.isBuffer(this._cachedSource) + ? false + : undefined, + size: this._cachedSize, + maps: bufferedMaps, + hash: this._cachedHashUpdate + }; + } + + originalLazy() { + return this._source; + } + + original() { + if (typeof this._source === "function") this._source = this._source(); + return this._source; + } + + source() { + const source = this._getCachedSource(); + if (source !== undefined) return source; + return (this._cachedSource = this.original().source()); + } + + _getMapFromCacheEntry(cacheEntry) { + if (cacheEntry.map !== undefined) { + return cacheEntry.map; + } else if (cacheEntry.bufferedMap !== undefined) { + return (cacheEntry.map = bufferedMapToMap(cacheEntry.bufferedMap)); + } + } + + _getCachedSource() { + if (this._cachedSource !== undefined) return this._cachedSource; + if (this._cachedBuffer && this._cachedSourceType !== undefined) { + return (this._cachedSource = this._cachedSourceType + ? this._cachedBuffer.toString("utf-8") + : this._cachedBuffer); + } + } + + buffer() { + if (this._cachedBuffer !== undefined) return this._cachedBuffer; + if (this._cachedSource !== undefined) { + if (Buffer.isBuffer(this._cachedSource)) { + return (this._cachedBuffer = this._cachedSource); + } + return (this._cachedBuffer = Buffer.from(this._cachedSource, "utf-8")); + } + if (typeof this.original().buffer === "function") { + return (this._cachedBuffer = this.original().buffer()); + } + const bufferOrString = this.source(); + if (Buffer.isBuffer(bufferOrString)) { + return (this._cachedBuffer = bufferOrString); + } + return (this._cachedBuffer = Buffer.from(bufferOrString, "utf-8")); + } + + size() { + if (this._cachedSize !== undefined) return this._cachedSize; + if (this._cachedBuffer !== undefined) { + return (this._cachedSize = this._cachedBuffer.length); + } + const source = this._getCachedSource(); + if (source !== undefined) { + return (this._cachedSize = Buffer.byteLength(source)); + } + return (this._cachedSize = this.original().size()); + } + + sourceAndMap(options) { + const key = options ? JSON.stringify(options) : "{}"; + const cacheEntry = this._cachedMaps.get(key); + // Look for a cached map + if (cacheEntry !== undefined) { + // We have a cached map in some representation + const map = this._getMapFromCacheEntry(cacheEntry); + // Either get the cached source or compute it + return { source: this.source(), map }; + } + // Look for a cached source + let source = this._getCachedSource(); + // Compute the map + let map; + if (source !== undefined) { + map = this.original().map(options); + } else { + // Compute the source and map together. + const sourceAndMap = this.original().sourceAndMap(options); + source = sourceAndMap.source; + map = sourceAndMap.map; + this._cachedSource = source; + } + this._cachedMaps.set(key, { + map, + bufferedMap: undefined + }); + return { source, map }; + } + + streamChunks(options, onChunk, onSource, onName) { + const key = options ? JSON.stringify(options) : "{}"; + if ( + this._cachedMaps.has(key) && + (this._cachedBuffer !== undefined || this._cachedSource !== undefined) + ) { + const { source, map } = this.sourceAndMap(options); + if (map) { + return streamChunksOfSourceMap( + source, + map, + onChunk, + onSource, + onName, + !!(options && options.finalSource), + true + ); + } else { + return streamChunksOfRawSource( + source, + onChunk, + onSource, + onName, + !!(options && options.finalSource) + ); + } + } + const { result, source, map } = streamAndGetSourceAndMap( + this.original(), + options, + onChunk, + onSource, + onName + ); + this._cachedSource = source; + this._cachedMaps.set(key, { + map, + bufferedMap: undefined + }); + return result; + } + + map(options) { + const key = options ? JSON.stringify(options) : "{}"; + const cacheEntry = this._cachedMaps.get(key); + if (cacheEntry !== undefined) { + return this._getMapFromCacheEntry(cacheEntry); + } + const map = this.original().map(options); + this._cachedMaps.set(key, { + map, + bufferedMap: undefined + }); + return map; + } + + updateHash(hash) { + if (this._cachedHashUpdate !== undefined) { + for (const item of this._cachedHashUpdate) hash.update(item); + return; + } + const update = []; + let currentString = undefined; + const tracker = { + update: item => { + if (typeof item === "string" && item.length < 10240) { + if (currentString === undefined) { + currentString = item; + } else { + currentString += item; + if (currentString.length > 102400) { + update.push(Buffer.from(currentString)); + currentString = undefined; + } + } + } else { + if (currentString !== undefined) { + update.push(Buffer.from(currentString)); + currentString = undefined; + } + update.push(item); + } + } + }; + this.original().updateHash(tracker); + if (currentString !== undefined) { + update.push(Buffer.from(currentString)); + } + for (const item of update) hash.update(item); + this._cachedHashUpdate = update; + } +} + +module.exports = CachedSource; diff --git a/node_modules/webpack-sources/lib/CompatSource.js b/node_modules/webpack-sources/lib/CompatSource.js new file mode 100644 index 0000000..0b9d9bd --- /dev/null +++ b/node_modules/webpack-sources/lib/CompatSource.js @@ -0,0 +1,66 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Source = require("./Source"); + +class CompatSource extends Source { + static from(sourceLike) { + return sourceLike instanceof Source + ? sourceLike + : new CompatSource(sourceLike); + } + + constructor(sourceLike) { + super(); + this._sourceLike = sourceLike; + } + + source() { + return this._sourceLike.source(); + } + + buffer() { + if (typeof this._sourceLike.buffer === "function") { + return this._sourceLike.buffer(); + } + return super.buffer(); + } + + size() { + if (typeof this._sourceLike.size === "function") { + return this._sourceLike.size(); + } + return super.size(); + } + + map(options) { + if (typeof this._sourceLike.map === "function") { + return this._sourceLike.map(options); + } + return super.map(options); + } + + sourceAndMap(options) { + if (typeof this._sourceLike.sourceAndMap === "function") { + return this._sourceLike.sourceAndMap(options); + } + return super.sourceAndMap(options); + } + + updateHash(hash) { + if (typeof this._sourceLike.updateHash === "function") { + return this._sourceLike.updateHash(hash); + } + if (typeof this._sourceLike.map === "function") { + throw new Error( + "A Source-like object with a 'map' method must also provide an 'updateHash' method" + ); + } + hash.update(this.buffer()); + } +} + +module.exports = CompatSource; diff --git a/node_modules/webpack-sources/lib/ConcatSource.js b/node_modules/webpack-sources/lib/ConcatSource.js new file mode 100644 index 0000000..3c7e7f2 --- /dev/null +++ b/node_modules/webpack-sources/lib/ConcatSource.js @@ -0,0 +1,319 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Source = require("./Source"); +const RawSource = require("./RawSource"); +const streamChunks = require("./helpers/streamChunks"); +const { getMap, getSourceAndMap } = require("./helpers/getFromStreamChunks"); + +const stringsAsRawSources = new WeakSet(); + +class ConcatSource extends Source { + constructor() { + super(); + this._children = []; + for (let i = 0; i < arguments.length; i++) { + const item = arguments[i]; + if (item instanceof ConcatSource) { + for (const child of item._children) { + this._children.push(child); + } + } else { + this._children.push(item); + } + } + this._isOptimized = arguments.length === 0; + } + + getChildren() { + if (!this._isOptimized) this._optimize(); + return this._children; + } + + add(item) { + if (item instanceof ConcatSource) { + for (const child of item._children) { + this._children.push(child); + } + } else { + this._children.push(item); + } + this._isOptimized = false; + } + + addAllSkipOptimizing(items) { + for (const item of items) { + this._children.push(item); + } + } + + buffer() { + if (!this._isOptimized) this._optimize(); + const buffers = []; + for (const child of this._children) { + if (typeof child.buffer === "function") { + buffers.push(child.buffer()); + } else { + const bufferOrString = child.source(); + if (Buffer.isBuffer(bufferOrString)) { + buffers.push(bufferOrString); + } else { + // This will not happen + buffers.push(Buffer.from(bufferOrString, "utf-8")); + } + } + } + return Buffer.concat(buffers); + } + + source() { + if (!this._isOptimized) this._optimize(); + let source = ""; + for (const child of this._children) { + source += child.source(); + } + return source; + } + + size() { + if (!this._isOptimized) this._optimize(); + let size = 0; + for (const child of this._children) { + size += child.size(); + } + return size; + } + + map(options) { + return getMap(this, options); + } + + sourceAndMap(options) { + return getSourceAndMap(this, options); + } + + streamChunks(options, onChunk, onSource, onName) { + if (!this._isOptimized) this._optimize(); + if (this._children.length === 1) + return this._children[0].streamChunks(options, onChunk, onSource, onName); + let currentLineOffset = 0; + let currentColumnOffset = 0; + let sourceMapping = new Map(); + let nameMapping = new Map(); + const finalSource = !!(options && options.finalSource); + let code = ""; + let needToCloseMapping = false; + for (const item of this._children) { + const sourceIndexMapping = []; + const nameIndexMapping = []; + let lastMappingLine = 0; + const { generatedLine, generatedColumn, source } = streamChunks( + item, + options, + // eslint-disable-next-line no-loop-func + ( + chunk, + generatedLine, + generatedColumn, + sourceIndex, + originalLine, + originalColumn, + nameIndex + ) => { + const line = generatedLine + currentLineOffset; + const column = + generatedLine === 1 + ? generatedColumn + currentColumnOffset + : generatedColumn; + if (needToCloseMapping) { + if (generatedLine !== 1 || generatedColumn !== 0) { + onChunk( + undefined, + currentLineOffset + 1, + currentColumnOffset, + -1, + -1, + -1, + -1 + ); + } + needToCloseMapping = false; + } + const resultSourceIndex = + sourceIndex < 0 || sourceIndex >= sourceIndexMapping.length + ? -1 + : sourceIndexMapping[sourceIndex]; + const resultNameIndex = + nameIndex < 0 || nameIndex >= nameIndexMapping.length + ? -1 + : nameIndexMapping[nameIndex]; + lastMappingLine = resultSourceIndex < 0 ? 0 : generatedLine; + if (finalSource) { + if (chunk !== undefined) code += chunk; + if (resultSourceIndex >= 0) { + onChunk( + undefined, + line, + column, + resultSourceIndex, + originalLine, + originalColumn, + resultNameIndex + ); + } + } else { + if (resultSourceIndex < 0) { + onChunk(chunk, line, column, -1, -1, -1, -1); + } else { + onChunk( + chunk, + line, + column, + resultSourceIndex, + originalLine, + originalColumn, + resultNameIndex + ); + } + } + }, + (i, source, sourceContent) => { + let globalIndex = sourceMapping.get(source); + if (globalIndex === undefined) { + sourceMapping.set(source, (globalIndex = sourceMapping.size)); + onSource(globalIndex, source, sourceContent); + } + sourceIndexMapping[i] = globalIndex; + }, + (i, name) => { + let globalIndex = nameMapping.get(name); + if (globalIndex === undefined) { + nameMapping.set(name, (globalIndex = nameMapping.size)); + onName(globalIndex, name); + } + nameIndexMapping[i] = globalIndex; + } + ); + if (source !== undefined) code += source; + if (needToCloseMapping) { + if (generatedLine !== 1 || generatedColumn !== 0) { + onChunk( + undefined, + currentLineOffset + 1, + currentColumnOffset, + -1, + -1, + -1, + -1 + ); + needToCloseMapping = false; + } + } + if (generatedLine > 1) { + currentColumnOffset = generatedColumn; + } else { + currentColumnOffset += generatedColumn; + } + needToCloseMapping = + needToCloseMapping || + (finalSource && lastMappingLine === generatedLine); + currentLineOffset += generatedLine - 1; + } + return { + generatedLine: currentLineOffset + 1, + generatedColumn: currentColumnOffset, + source: finalSource ? code : undefined + }; + } + + updateHash(hash) { + if (!this._isOptimized) this._optimize(); + hash.update("ConcatSource"); + for (const item of this._children) { + item.updateHash(hash); + } + } + + _optimize() { + const newChildren = []; + let currentString = undefined; + let currentRawSources = undefined; + const addStringToRawSources = string => { + if (currentRawSources === undefined) { + currentRawSources = string; + } else if (Array.isArray(currentRawSources)) { + currentRawSources.push(string); + } else { + currentRawSources = [ + typeof currentRawSources === "string" + ? currentRawSources + : currentRawSources.source(), + string + ]; + } + }; + const addSourceToRawSources = source => { + if (currentRawSources === undefined) { + currentRawSources = source; + } else if (Array.isArray(currentRawSources)) { + currentRawSources.push(source.source()); + } else { + currentRawSources = [ + typeof currentRawSources === "string" + ? currentRawSources + : currentRawSources.source(), + source.source() + ]; + } + }; + const mergeRawSources = () => { + if (Array.isArray(currentRawSources)) { + const rawSource = new RawSource(currentRawSources.join("")); + stringsAsRawSources.add(rawSource); + newChildren.push(rawSource); + } else if (typeof currentRawSources === "string") { + const rawSource = new RawSource(currentRawSources); + stringsAsRawSources.add(rawSource); + newChildren.push(rawSource); + } else { + newChildren.push(currentRawSources); + } + }; + for (const child of this._children) { + if (typeof child === "string") { + if (currentString === undefined) { + currentString = child; + } else { + currentString += child; + } + } else { + if (currentString !== undefined) { + addStringToRawSources(currentString); + currentString = undefined; + } + if (stringsAsRawSources.has(child)) { + addSourceToRawSources(child); + } else { + if (currentRawSources !== undefined) { + mergeRawSources(); + currentRawSources = undefined; + } + newChildren.push(child); + } + } + } + if (currentString !== undefined) { + addStringToRawSources(currentString); + } + if (currentRawSources !== undefined) { + mergeRawSources(); + } + this._children = newChildren; + this._isOptimized = true; + } +} + +module.exports = ConcatSource; diff --git a/node_modules/webpack-sources/lib/OriginalSource.js b/node_modules/webpack-sources/lib/OriginalSource.js new file mode 100644 index 0000000..59da29a --- /dev/null +++ b/node_modules/webpack-sources/lib/OriginalSource.js @@ -0,0 +1,135 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const { getMap, getSourceAndMap } = require("./helpers/getFromStreamChunks"); +const splitIntoLines = require("./helpers/splitIntoLines"); +const getGeneratedSourceInfo = require("./helpers/getGeneratedSourceInfo"); +const Source = require("./Source"); +const splitIntoPotentialTokens = require("./helpers/splitIntoPotentialTokens"); + +class OriginalSource extends Source { + constructor(value, name) { + super(); + const isBuffer = Buffer.isBuffer(value); + this._value = isBuffer ? undefined : value; + this._valueAsBuffer = isBuffer ? value : undefined; + this._name = name; + } + + getName() { + return this._name; + } + + source() { + if (this._value === undefined) { + this._value = this._valueAsBuffer.toString("utf-8"); + } + return this._value; + } + + buffer() { + if (this._valueAsBuffer === undefined) { + this._valueAsBuffer = Buffer.from(this._value, "utf-8"); + } + return this._valueAsBuffer; + } + + map(options) { + return getMap(this, options); + } + + sourceAndMap(options) { + return getSourceAndMap(this, options); + } + + /** + * @param {object} options options + * @param {function(string, number, number, number, number, number, number): void} onChunk called for each chunk of code + * @param {function(number, string, string)} onSource called for each source + * @param {function(number, string)} onName called for each name + * @returns {void} + */ + streamChunks(options, onChunk, onSource, onName) { + if (this._value === undefined) { + this._value = this._valueAsBuffer.toString("utf-8"); + } + onSource(0, this._name, this._value); + const finalSource = !!(options && options.finalSource); + if (!options || options.columns !== false) { + // With column info we need to read all lines and split them + const matches = splitIntoPotentialTokens(this._value); + let line = 1; + let column = 0; + if (matches !== null) { + for (const match of matches) { + const isEndOfLine = match.endsWith("\n"); + if (isEndOfLine && match.length === 1) { + if (!finalSource) onChunk(match, line, column, -1, -1, -1, -1); + } else { + const chunk = finalSource ? undefined : match; + onChunk(chunk, line, column, 0, line, column, -1); + } + if (isEndOfLine) { + line++; + column = 0; + } else { + column += match.length; + } + } + } + return { + generatedLine: line, + generatedColumn: column, + source: finalSource ? this._value : undefined + }; + } else if (finalSource) { + // Without column info and with final source we only + // need meta info to generate mapping + const result = getGeneratedSourceInfo(this._value); + const { generatedLine, generatedColumn } = result; + if (generatedColumn === 0) { + for (let line = 1; line < generatedLine; line++) + onChunk(undefined, line, 0, 0, line, 0, -1); + } else { + for (let line = 1; line <= generatedLine; line++) + onChunk(undefined, line, 0, 0, line, 0, -1); + } + return result; + } else { + // Without column info, but also without final source + // we need to split source by lines + let line = 1; + const matches = splitIntoLines(this._value); + let match; + for (match of matches) { + onChunk(finalSource ? undefined : match, line, 0, 0, line, 0, -1); + line++; + } + return matches.length === 0 || match.endsWith("\n") + ? { + generatedLine: matches.length + 1, + generatedColumn: 0, + source: finalSource ? this._value : undefined + } + : { + generatedLine: matches.length, + generatedColumn: match.length, + source: finalSource ? this._value : undefined + }; + } + } + + updateHash(hash) { + if (this._valueAsBuffer === undefined) { + this._valueAsBuffer = Buffer.from(this._value, "utf-8"); + } + hash.update("OriginalSource"); + hash.update(this._valueAsBuffer); + hash.update(this._name || ""); + } +} + +module.exports = OriginalSource; diff --git a/node_modules/webpack-sources/lib/PrefixSource.js b/node_modules/webpack-sources/lib/PrefixSource.js new file mode 100644 index 0000000..a54314c --- /dev/null +++ b/node_modules/webpack-sources/lib/PrefixSource.js @@ -0,0 +1,114 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Source = require("./Source"); +const RawSource = require("./RawSource"); +const streamChunks = require("./helpers/streamChunks"); +const { getMap, getSourceAndMap } = require("./helpers/getFromStreamChunks"); + +const REPLACE_REGEX = /\n(?=.|\s)/g; + +class PrefixSource extends Source { + constructor(prefix, source) { + super(); + this._source = + typeof source === "string" || Buffer.isBuffer(source) + ? new RawSource(source, true) + : source; + this._prefix = prefix; + } + + getPrefix() { + return this._prefix; + } + + original() { + return this._source; + } + + source() { + const node = this._source.source(); + const prefix = this._prefix; + return prefix + node.replace(REPLACE_REGEX, "\n" + prefix); + } + + // TODO efficient buffer() implementation + + map(options) { + return getMap(this, options); + } + + sourceAndMap(options) { + return getSourceAndMap(this, options); + } + + streamChunks(options, onChunk, onSource, onName) { + const prefix = this._prefix; + const prefixOffset = prefix.length; + const linesOnly = !!(options && options.columns === false); + const { generatedLine, generatedColumn, source } = streamChunks( + this._source, + options, + ( + chunk, + generatedLine, + generatedColumn, + sourceIndex, + originalLine, + originalColumn, + nameIndex + ) => { + if (generatedColumn !== 0) { + // In the middle of the line, we just adject the column + generatedColumn += prefixOffset; + } else if (chunk !== undefined) { + // At the start of the line, when we have source content + // add the prefix as generated mapping + // (in lines only mode we just add it to the original mapping + // for performance reasons) + if (linesOnly || sourceIndex < 0) { + chunk = prefix + chunk; + } else if (prefixOffset > 0) { + onChunk(prefix, generatedLine, generatedColumn, -1, -1, -1, -1); + generatedColumn += prefixOffset; + } + } else if (!linesOnly) { + // Without source content, we only need to adject the column info + // expect in lines only mode where prefix is added to original mapping + generatedColumn += prefixOffset; + } + onChunk( + chunk, + generatedLine, + generatedColumn, + sourceIndex, + originalLine, + originalColumn, + nameIndex + ); + }, + onSource, + onName + ); + return { + generatedLine, + generatedColumn: + generatedColumn === 0 ? 0 : prefixOffset + generatedColumn, + source: + source !== undefined + ? prefix + source.replace(REPLACE_REGEX, "\n" + prefix) + : undefined + }; + } + + updateHash(hash) { + hash.update("PrefixSource"); + this._source.updateHash(hash); + hash.update(this._prefix); + } +} + +module.exports = PrefixSource; diff --git a/node_modules/webpack-sources/lib/RawSource.js b/node_modules/webpack-sources/lib/RawSource.js new file mode 100644 index 0000000..71f1341 --- /dev/null +++ b/node_modules/webpack-sources/lib/RawSource.js @@ -0,0 +1,81 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const streamChunksOfRawSource = require("./helpers/streamChunksOfRawSource"); +const Source = require("./Source"); + +class RawSource extends Source { + constructor(value, convertToString = false) { + super(); + const isBuffer = Buffer.isBuffer(value); + if (!isBuffer && typeof value !== "string") { + throw new TypeError("argument 'value' must be either string of Buffer"); + } + this._valueIsBuffer = !convertToString && isBuffer; + this._value = convertToString && isBuffer ? undefined : value; + this._valueAsBuffer = isBuffer ? value : undefined; + this._valueAsString = isBuffer ? undefined : value; + } + + isBuffer() { + return this._valueIsBuffer; + } + + source() { + if (this._value === undefined) { + this._value = this._valueAsBuffer.toString("utf-8"); + } + return this._value; + } + + buffer() { + if (this._valueAsBuffer === undefined) { + this._valueAsBuffer = Buffer.from(this._value, "utf-8"); + } + return this._valueAsBuffer; + } + + map(options) { + return null; + } + + /** + * @param {object} options options + * @param {function(string, number, number, number, number, number, number): void} onChunk called for each chunk of code + * @param {function(number, string, string)} onSource called for each source + * @param {function(number, string)} onName called for each name + * @returns {void} + */ + streamChunks(options, onChunk, onSource, onName) { + if (this._value === undefined) { + this._value = Buffer.from(this._valueAsBuffer, "utf-8"); + } + if (this._valueAsString === undefined) { + this._valueAsString = + typeof this._value === "string" + ? this._value + : this._value.toString("utf-8"); + } + return streamChunksOfRawSource( + this._valueAsString, + onChunk, + onSource, + onName, + !!(options && options.finalSource) + ); + } + + updateHash(hash) { + if (this._valueAsBuffer === undefined) { + this._valueAsBuffer = Buffer.from(this._value, "utf-8"); + } + hash.update("RawSource"); + hash.update(this._valueAsBuffer); + } +} + +module.exports = RawSource; diff --git a/node_modules/webpack-sources/lib/ReplaceSource.js b/node_modules/webpack-sources/lib/ReplaceSource.js new file mode 100644 index 0000000..1a678d1 --- /dev/null +++ b/node_modules/webpack-sources/lib/ReplaceSource.js @@ -0,0 +1,467 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const { getMap, getSourceAndMap } = require("./helpers/getFromStreamChunks"); +const streamChunks = require("./helpers/streamChunks"); +const Source = require("./Source"); +const splitIntoLines = require("./helpers/splitIntoLines"); + +// since v8 7.0, Array.prototype.sort is stable +const hasStableSort = + typeof process === "object" && + process.versions && + typeof process.versions.v8 === "string" && + !/^[0-6]\./.test(process.versions.v8); + +// This is larger than max string length +const MAX_SOURCE_POSITION = 0x20000000; + +class Replacement { + constructor(start, end, content, name) { + this.start = start; + this.end = end; + this.content = content; + this.name = name; + if (!hasStableSort) { + this.index = -1; + } + } +} + +class ReplaceSource extends Source { + constructor(source, name) { + super(); + this._source = source; + this._name = name; + /** @type {Replacement[]} */ + this._replacements = []; + this._isSorted = true; + } + + getName() { + return this._name; + } + + getReplacements() { + this._sortReplacements(); + return this._replacements; + } + + replace(start, end, newValue, name) { + if (typeof newValue !== "string") + throw new Error( + "insertion must be a string, but is a " + typeof newValue + ); + this._replacements.push(new Replacement(start, end, newValue, name)); + this._isSorted = false; + } + + insert(pos, newValue, name) { + if (typeof newValue !== "string") + throw new Error( + "insertion must be a string, but is a " + + typeof newValue + + ": " + + newValue + ); + this._replacements.push(new Replacement(pos, pos - 1, newValue, name)); + this._isSorted = false; + } + + source() { + if (this._replacements.length === 0) { + return this._source.source(); + } + let current = this._source.source(); + let pos = 0; + const result = []; + + this._sortReplacements(); + for (const replacement of this._replacements) { + const start = Math.floor(replacement.start); + const end = Math.floor(replacement.end + 1); + if (pos < start) { + const offset = start - pos; + result.push(current.slice(0, offset)); + current = current.slice(offset); + pos = start; + } + result.push(replacement.content); + if (pos < end) { + const offset = end - pos; + current = current.slice(offset); + pos = end; + } + } + result.push(current); + return result.join(""); + } + + map(options) { + if (this._replacements.length === 0) { + return this._source.map(options); + } + return getMap(this, options); + } + + sourceAndMap(options) { + if (this._replacements.length === 0) { + return this._source.sourceAndMap(options); + } + return getSourceAndMap(this, options); + } + + original() { + return this._source; + } + + _sortReplacements() { + if (this._isSorted) return; + if (hasStableSort) { + this._replacements.sort(function (a, b) { + const diff1 = a.start - b.start; + if (diff1 !== 0) return diff1; + const diff2 = a.end - b.end; + if (diff2 !== 0) return diff2; + return 0; + }); + } else { + this._replacements.forEach((repl, i) => (repl.index = i)); + this._replacements.sort(function (a, b) { + const diff1 = a.start - b.start; + if (diff1 !== 0) return diff1; + const diff2 = a.end - b.end; + if (diff2 !== 0) return diff2; + return a.index - b.index; + }); + } + this._isSorted = true; + } + + streamChunks(options, onChunk, onSource, onName) { + this._sortReplacements(); + const repls = this._replacements; + let pos = 0; + let i = 0; + let replacmentEnd = -1; + let nextReplacement = + i < repls.length ? Math.floor(repls[i].start) : MAX_SOURCE_POSITION; + let generatedLineOffset = 0; + let generatedColumnOffset = 0; + let generatedColumnOffsetLine = 0; + const sourceContents = []; + const nameMapping = new Map(); + const nameIndexMapping = []; + const checkOriginalContent = (sourceIndex, line, column, expectedChunk) => { + let content = + sourceIndex < sourceContents.length + ? sourceContents[sourceIndex] + : undefined; + if (content === undefined) return false; + if (typeof content === "string") { + content = splitIntoLines(content); + sourceContents[sourceIndex] = content; + } + const contentLine = line <= content.length ? content[line - 1] : null; + if (contentLine === null) return false; + return ( + contentLine.slice(column, column + expectedChunk.length) === + expectedChunk + ); + }; + let { generatedLine, generatedColumn } = streamChunks( + this._source, + Object.assign({}, options, { finalSource: false }), + ( + chunk, + generatedLine, + generatedColumn, + sourceIndex, + originalLine, + originalColumn, + nameIndex + ) => { + let chunkPos = 0; + let endPos = pos + chunk.length; + + // Skip over when it has been replaced + if (replacmentEnd > pos) { + // Skip over the whole chunk + if (replacmentEnd >= endPos) { + const line = generatedLine + generatedLineOffset; + if (chunk.endsWith("\n")) { + generatedLineOffset--; + if (generatedColumnOffsetLine === line) { + // undo exiting corrections form the current line + generatedColumnOffset += generatedColumn; + } + } else if (generatedColumnOffsetLine === line) { + generatedColumnOffset -= chunk.length; + } else { + generatedColumnOffset = -chunk.length; + generatedColumnOffsetLine = line; + } + pos = endPos; + return; + } + + // Partially skip over chunk + chunkPos = replacmentEnd - pos; + if ( + checkOriginalContent( + sourceIndex, + originalLine, + originalColumn, + chunk.slice(0, chunkPos) + ) + ) { + originalColumn += chunkPos; + } + pos += chunkPos; + const line = generatedLine + generatedLineOffset; + if (generatedColumnOffsetLine === line) { + generatedColumnOffset -= chunkPos; + } else { + generatedColumnOffset = -chunkPos; + generatedColumnOffsetLine = line; + } + generatedColumn += chunkPos; + } + + // Is a replacement in the chunk? + if (nextReplacement < endPos) { + do { + let line = generatedLine + generatedLineOffset; + if (nextReplacement > pos) { + // Emit chunk until replacement + const offset = nextReplacement - pos; + const chunkSlice = chunk.slice(chunkPos, chunkPos + offset); + onChunk( + chunkSlice, + line, + generatedColumn + + (line === generatedColumnOffsetLine + ? generatedColumnOffset + : 0), + sourceIndex, + originalLine, + originalColumn, + nameIndex < 0 || nameIndex >= nameIndexMapping.length + ? -1 + : nameIndexMapping[nameIndex] + ); + generatedColumn += offset; + chunkPos += offset; + pos = nextReplacement; + if ( + checkOriginalContent( + sourceIndex, + originalLine, + originalColumn, + chunkSlice + ) + ) { + originalColumn += chunkSlice.length; + } + } + + // Insert replacement content splitted into chunks by lines + const { content, name } = repls[i]; + let matches = splitIntoLines(content); + let replacementNameIndex = nameIndex; + if (sourceIndex >= 0 && name) { + let globalIndex = nameMapping.get(name); + if (globalIndex === undefined) { + globalIndex = nameMapping.size; + nameMapping.set(name, globalIndex); + onName(globalIndex, name); + } + replacementNameIndex = globalIndex; + } + for (let m = 0; m < matches.length; m++) { + const contentLine = matches[m]; + onChunk( + contentLine, + line, + generatedColumn + + (line === generatedColumnOffsetLine + ? generatedColumnOffset + : 0), + sourceIndex, + originalLine, + originalColumn, + replacementNameIndex + ); + + // Only the first chunk has name assigned + replacementNameIndex = -1; + + if (m === matches.length - 1 && !contentLine.endsWith("\n")) { + if (generatedColumnOffsetLine === line) { + generatedColumnOffset += contentLine.length; + } else { + generatedColumnOffset = contentLine.length; + generatedColumnOffsetLine = line; + } + } else { + generatedLineOffset++; + line++; + generatedColumnOffset = -generatedColumn; + generatedColumnOffsetLine = line; + } + } + + // Remove replaced content by settings this variable + replacmentEnd = Math.max( + replacmentEnd, + Math.floor(repls[i].end + 1) + ); + + // Move to next replacment + i++; + nextReplacement = + i < repls.length + ? Math.floor(repls[i].start) + : MAX_SOURCE_POSITION; + + // Skip over when it has been replaced + const offset = chunk.length - endPos + replacmentEnd - chunkPos; + if (offset > 0) { + // Skip over whole chunk + if (replacmentEnd >= endPos) { + let line = generatedLine + generatedLineOffset; + if (chunk.endsWith("\n")) { + generatedLineOffset--; + if (generatedColumnOffsetLine === line) { + // undo exiting corrections form the current line + generatedColumnOffset += generatedColumn; + } + } else if (generatedColumnOffsetLine === line) { + generatedColumnOffset -= chunk.length - chunkPos; + } else { + generatedColumnOffset = chunkPos - chunk.length; + generatedColumnOffsetLine = line; + } + pos = endPos; + return; + } + + // Partially skip over chunk + const line = generatedLine + generatedLineOffset; + if ( + checkOriginalContent( + sourceIndex, + originalLine, + originalColumn, + chunk.slice(chunkPos, chunkPos + offset) + ) + ) { + originalColumn += offset; + } + chunkPos += offset; + pos += offset; + if (generatedColumnOffsetLine === line) { + generatedColumnOffset -= offset; + } else { + generatedColumnOffset = -offset; + generatedColumnOffsetLine = line; + } + generatedColumn += offset; + } + } while (nextReplacement < endPos); + } + + // Emit remaining chunk + if (chunkPos < chunk.length) { + const chunkSlice = chunkPos === 0 ? chunk : chunk.slice(chunkPos); + const line = generatedLine + generatedLineOffset; + onChunk( + chunkSlice, + line, + generatedColumn + + (line === generatedColumnOffsetLine ? generatedColumnOffset : 0), + sourceIndex, + originalLine, + originalColumn, + nameIndex < 0 ? -1 : nameIndexMapping[nameIndex] + ); + } + pos = endPos; + }, + (sourceIndex, source, sourceContent) => { + while (sourceContents.length < sourceIndex) + sourceContents.push(undefined); + sourceContents[sourceIndex] = sourceContent; + onSource(sourceIndex, source, sourceContent); + }, + (nameIndex, name) => { + let globalIndex = nameMapping.get(name); + if (globalIndex === undefined) { + globalIndex = nameMapping.size; + nameMapping.set(name, globalIndex); + onName(globalIndex, name); + } + nameIndexMapping[nameIndex] = globalIndex; + } + ); + + // Handle remaining replacements + let remainer = ""; + for (; i < repls.length; i++) { + remainer += repls[i].content; + } + + // Insert remaining replacements content splitted into chunks by lines + let line = generatedLine + generatedLineOffset; + let matches = splitIntoLines(remainer); + for (let m = 0; m < matches.length; m++) { + const contentLine = matches[m]; + onChunk( + contentLine, + line, + generatedColumn + + (line === generatedColumnOffsetLine ? generatedColumnOffset : 0), + -1, + -1, + -1, + -1 + ); + + if (m === matches.length - 1 && !contentLine.endsWith("\n")) { + if (generatedColumnOffsetLine === line) { + generatedColumnOffset += contentLine.length; + } else { + generatedColumnOffset = contentLine.length; + generatedColumnOffsetLine = line; + } + } else { + generatedLineOffset++; + line++; + generatedColumnOffset = -generatedColumn; + generatedColumnOffsetLine = line; + } + } + + return { + generatedLine: line, + generatedColumn: + generatedColumn + + (line === generatedColumnOffsetLine ? generatedColumnOffset : 0) + }; + } + + updateHash(hash) { + this._sortReplacements(); + hash.update("ReplaceSource"); + this._source.updateHash(hash); + hash.update(this._name || ""); + for (const repl of this._replacements) { + hash.update(`${repl.start}${repl.end}${repl.content}${repl.name}`); + } + } +} + +module.exports = ReplaceSource; diff --git a/node_modules/webpack-sources/lib/SizeOnlySource.js b/node_modules/webpack-sources/lib/SizeOnlySource.js new file mode 100644 index 0000000..a6e9294 --- /dev/null +++ b/node_modules/webpack-sources/lib/SizeOnlySource.js @@ -0,0 +1,42 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Source = require("./Source"); + +class SizeOnlySource extends Source { + constructor(size) { + super(); + this._size = size; + } + + _error() { + return new Error( + "Content and Map of this Source is not available (only size() is supported)" + ); + } + + size() { + return this._size; + } + + source() { + throw this._error(); + } + + buffer() { + throw this._error(); + } + + map(options) { + throw this._error(); + } + + updateHash() { + throw this._error(); + } +} + +module.exports = SizeOnlySource; diff --git a/node_modules/webpack-sources/lib/Source.js b/node_modules/webpack-sources/lib/Source.js new file mode 100644 index 0000000..fb86c2e --- /dev/null +++ b/node_modules/webpack-sources/lib/Source.js @@ -0,0 +1,38 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +class Source { + source() { + throw new Error("Abstract"); + } + + buffer() { + const source = this.source(); + if (Buffer.isBuffer(source)) return source; + return Buffer.from(source, "utf-8"); + } + + size() { + return this.buffer().length; + } + + map(options) { + return null; + } + + sourceAndMap(options) { + return { + source: this.source(), + map: this.map(options) + }; + } + + updateHash(hash) { + throw new Error("Abstract"); + } +} + +module.exports = Source; diff --git a/node_modules/webpack-sources/lib/SourceMapSource.js b/node_modules/webpack-sources/lib/SourceMapSource.js new file mode 100644 index 0000000..88a7cb8 --- /dev/null +++ b/node_modules/webpack-sources/lib/SourceMapSource.js @@ -0,0 +1,247 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Source = require("./Source"); +const streamChunksOfSourceMap = require("./helpers/streamChunksOfSourceMap"); +const streamChunksOfCombinedSourceMap = require("./helpers/streamChunksOfCombinedSourceMap"); +const { getMap, getSourceAndMap } = require("./helpers/getFromStreamChunks"); + +class SourceMapSource extends Source { + constructor( + value, + name, + sourceMap, + originalSource, + innerSourceMap, + removeOriginalSource + ) { + super(); + const valueIsBuffer = Buffer.isBuffer(value); + this._valueAsString = valueIsBuffer ? undefined : value; + this._valueAsBuffer = valueIsBuffer ? value : undefined; + + this._name = name; + + this._hasSourceMap = !!sourceMap; + const sourceMapIsBuffer = Buffer.isBuffer(sourceMap); + const sourceMapIsString = typeof sourceMap === "string"; + this._sourceMapAsObject = + sourceMapIsBuffer || sourceMapIsString ? undefined : sourceMap; + this._sourceMapAsString = sourceMapIsString ? sourceMap : undefined; + this._sourceMapAsBuffer = sourceMapIsBuffer ? sourceMap : undefined; + + this._hasOriginalSource = !!originalSource; + const originalSourceIsBuffer = Buffer.isBuffer(originalSource); + this._originalSourceAsString = originalSourceIsBuffer + ? undefined + : originalSource; + this._originalSourceAsBuffer = originalSourceIsBuffer + ? originalSource + : undefined; + + this._hasInnerSourceMap = !!innerSourceMap; + const innerSourceMapIsBuffer = Buffer.isBuffer(innerSourceMap); + const innerSourceMapIsString = typeof innerSourceMap === "string"; + this._innerSourceMapAsObject = + innerSourceMapIsBuffer || innerSourceMapIsString + ? undefined + : innerSourceMap; + this._innerSourceMapAsString = innerSourceMapIsString + ? innerSourceMap + : undefined; + this._innerSourceMapAsBuffer = innerSourceMapIsBuffer + ? innerSourceMap + : undefined; + + this._removeOriginalSource = removeOriginalSource; + } + + _ensureValueBuffer() { + if (this._valueAsBuffer === undefined) { + this._valueAsBuffer = Buffer.from(this._valueAsString, "utf-8"); + } + } + + _ensureValueString() { + if (this._valueAsString === undefined) { + this._valueAsString = this._valueAsBuffer.toString("utf-8"); + } + } + + _ensureOriginalSourceBuffer() { + if (this._originalSourceAsBuffer === undefined && this._hasOriginalSource) { + this._originalSourceAsBuffer = Buffer.from( + this._originalSourceAsString, + "utf-8" + ); + } + } + + _ensureOriginalSourceString() { + if (this._originalSourceAsString === undefined && this._hasOriginalSource) { + this._originalSourceAsString = this._originalSourceAsBuffer.toString( + "utf-8" + ); + } + } + + _ensureInnerSourceMapObject() { + if (this._innerSourceMapAsObject === undefined && this._hasInnerSourceMap) { + this._ensureInnerSourceMapString(); + this._innerSourceMapAsObject = JSON.parse(this._innerSourceMapAsString); + } + } + + _ensureInnerSourceMapBuffer() { + if (this._innerSourceMapAsBuffer === undefined && this._hasInnerSourceMap) { + this._ensureInnerSourceMapString(); + this._innerSourceMapAsBuffer = Buffer.from( + this._innerSourceMapAsString, + "utf-8" + ); + } + } + + _ensureInnerSourceMapString() { + if (this._innerSourceMapAsString === undefined && this._hasInnerSourceMap) { + if (this._innerSourceMapAsBuffer !== undefined) { + this._innerSourceMapAsString = this._innerSourceMapAsBuffer.toString( + "utf-8" + ); + } else { + this._innerSourceMapAsString = JSON.stringify( + this._innerSourceMapAsObject + ); + } + } + } + + _ensureSourceMapObject() { + if (this._sourceMapAsObject === undefined) { + this._ensureSourceMapString(); + this._sourceMapAsObject = JSON.parse(this._sourceMapAsString); + } + } + + _ensureSourceMapBuffer() { + if (this._sourceMapAsBuffer === undefined) { + this._ensureSourceMapString(); + this._sourceMapAsBuffer = Buffer.from(this._sourceMapAsString, "utf-8"); + } + } + + _ensureSourceMapString() { + if (this._sourceMapAsString === undefined) { + if (this._sourceMapAsBuffer !== undefined) { + this._sourceMapAsString = this._sourceMapAsBuffer.toString("utf-8"); + } else { + this._sourceMapAsString = JSON.stringify(this._sourceMapAsObject); + } + } + } + + getArgsAsBuffers() { + this._ensureValueBuffer(); + this._ensureSourceMapBuffer(); + this._ensureOriginalSourceBuffer(); + this._ensureInnerSourceMapBuffer(); + return [ + this._valueAsBuffer, + this._name, + this._sourceMapAsBuffer, + this._originalSourceAsBuffer, + this._innerSourceMapAsBuffer, + this._removeOriginalSource + ]; + } + + buffer() { + this._ensureValueBuffer(); + return this._valueAsBuffer; + } + + source() { + this._ensureValueString(); + return this._valueAsString; + } + + map(options) { + if (!this._hasInnerSourceMap) { + this._ensureSourceMapObject(); + return this._sourceMapAsObject; + } + return getMap(this, options); + } + + sourceAndMap(options) { + if (!this._hasInnerSourceMap) { + this._ensureValueString(); + this._ensureSourceMapObject(); + return { + source: this._valueAsString, + map: this._sourceMapAsObject + }; + } + return getSourceAndMap(this, options); + } + + streamChunks(options, onChunk, onSource, onName) { + this._ensureValueString(); + this._ensureSourceMapObject(); + this._ensureOriginalSourceString(); + if (this._hasInnerSourceMap) { + this._ensureInnerSourceMapObject(); + return streamChunksOfCombinedSourceMap( + this._valueAsString, + this._sourceMapAsObject, + this._name, + this._originalSourceAsString, + this._innerSourceMapAsObject, + this._removeOriginalSource, + onChunk, + onSource, + onName, + !!(options && options.finalSource), + !!(options && options.columns !== false) + ); + } else { + return streamChunksOfSourceMap( + this._valueAsString, + this._sourceMapAsObject, + onChunk, + onSource, + onName, + !!(options && options.finalSource), + !!(options && options.columns !== false) + ); + } + } + + updateHash(hash) { + this._ensureValueBuffer(); + this._ensureSourceMapBuffer(); + this._ensureOriginalSourceBuffer(); + this._ensureInnerSourceMapBuffer(); + + hash.update("SourceMapSource"); + + hash.update(this._valueAsBuffer); + + hash.update(this._sourceMapAsBuffer); + + if (this._hasOriginalSource) { + hash.update(this._originalSourceAsBuffer); + } + + if (this._hasInnerSourceMap) { + hash.update(this._innerSourceMapAsBuffer); + } + + hash.update(this._removeOriginalSource ? "true" : "false"); + } +} + +module.exports = SourceMapSource; diff --git a/node_modules/webpack-sources/lib/helpers/createMappingsSerializer.js b/node_modules/webpack-sources/lib/helpers/createMappingsSerializer.js new file mode 100644 index 0000000..8dafe43 --- /dev/null +++ b/node_modules/webpack-sources/lib/helpers/createMappingsSerializer.js @@ -0,0 +1,206 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split( + "" +); + +const CONTINUATION_BIT = 0x20; + +const createMappingsSerializer = options => { + const linesOnly = options && options.columns === false; + return linesOnly + ? createLinesOnlyMappingsSerializer() + : createFullMappingsSerializer(); +}; + +const createFullMappingsSerializer = () => { + let currentLine = 1; + let currentColumn = 0; + let currentSourceIndex = 0; + let currentOriginalLine = 1; + let currentOriginalColumn = 0; + let currentNameIndex = 0; + let activeMapping = false; + let activeName = false; + let initial = true; + return ( + generatedLine, + generatedColumn, + sourceIndex, + originalLine, + originalColumn, + nameIndex + ) => { + if (activeMapping && currentLine === generatedLine) { + // A mapping is still active + if ( + sourceIndex === currentSourceIndex && + originalLine === currentOriginalLine && + originalColumn === currentOriginalColumn && + !activeName && + nameIndex < 0 + ) { + // avoid repeating the same original mapping + return ""; + } + } else { + // No mapping is active + if (sourceIndex < 0) { + // avoid writing unneccessary generated mappings + return ""; + } + } + + let str; + if (currentLine < generatedLine) { + str = ";".repeat(generatedLine - currentLine); + currentLine = generatedLine; + currentColumn = 0; + initial = false; + } else if (initial) { + str = ""; + initial = false; + } else { + str = ","; + } + + const writeValue = value => { + const sign = (value >>> 31) & 1; + const mask = value >> 31; + const absValue = (value + mask) ^ mask; + let data = (absValue << 1) | sign; + for (;;) { + const sextet = data & 0x1f; + data >>= 5; + if (data === 0) { + str += ALPHABET[sextet]; + break; + } else { + str += ALPHABET[sextet | CONTINUATION_BIT]; + } + } + }; + writeValue(generatedColumn - currentColumn); + currentColumn = generatedColumn; + if (sourceIndex >= 0) { + activeMapping = true; + if (sourceIndex === currentSourceIndex) { + str += "A"; + } else { + writeValue(sourceIndex - currentSourceIndex); + currentSourceIndex = sourceIndex; + } + writeValue(originalLine - currentOriginalLine); + currentOriginalLine = originalLine; + if (originalColumn === currentOriginalColumn) { + str += "A"; + } else { + writeValue(originalColumn - currentOriginalColumn); + currentOriginalColumn = originalColumn; + } + if (nameIndex >= 0) { + writeValue(nameIndex - currentNameIndex); + currentNameIndex = nameIndex; + activeName = true; + } else { + activeName = false; + } + } else { + activeMapping = false; + } + return str; + }; +}; + +const createLinesOnlyMappingsSerializer = () => { + let lastWrittenLine = 0; + let currentLine = 1; + let currentSourceIndex = 0; + let currentOriginalLine = 1; + return ( + generatedLine, + _generatedColumn, + sourceIndex, + originalLine, + _originalColumn, + _nameIndex + ) => { + if (sourceIndex < 0) { + // avoid writing generated mappings at all + return ""; + } + if (lastWrittenLine === generatedLine) { + // avoid writing multiple original mappings per line + return ""; + } + let str; + const writeValue = value => { + const sign = (value >>> 31) & 1; + const mask = value >> 31; + const absValue = (value + mask) ^ mask; + let data = (absValue << 1) | sign; + for (;;) { + const sextet = data & 0x1f; + data >>= 5; + if (data === 0) { + str += ALPHABET[sextet]; + break; + } else { + str += ALPHABET[sextet | CONTINUATION_BIT]; + } + } + }; + lastWrittenLine = generatedLine; + if (generatedLine === currentLine + 1) { + currentLine = generatedLine; + if (sourceIndex === currentSourceIndex) { + currentSourceIndex = sourceIndex; + if (originalLine === currentOriginalLine + 1) { + currentOriginalLine = originalLine; + return ";AACA"; + } else { + str = ";AA"; + writeValue(originalLine - currentOriginalLine); + currentOriginalLine = originalLine; + return str + "A"; + } + } else { + str = ";A"; + writeValue(sourceIndex - currentSourceIndex); + currentSourceIndex = sourceIndex; + writeValue(originalLine - currentOriginalLine); + currentOriginalLine = originalLine; + return str + "A"; + } + } else { + str = ";".repeat(generatedLine - currentLine); + currentLine = generatedLine; + if (sourceIndex === currentSourceIndex) { + currentSourceIndex = sourceIndex; + if (originalLine === currentOriginalLine + 1) { + currentOriginalLine = originalLine; + return str + "AACA"; + } else { + str += "AA"; + writeValue(originalLine - currentOriginalLine); + currentOriginalLine = originalLine; + return str + "A"; + } + } else { + str += "A"; + writeValue(sourceIndex - currentSourceIndex); + currentSourceIndex = sourceIndex; + writeValue(originalLine - currentOriginalLine); + currentOriginalLine = originalLine; + return str + "A"; + } + } + }; +}; + +module.exports = createMappingsSerializer; diff --git a/node_modules/webpack-sources/lib/helpers/getFromStreamChunks.js b/node_modules/webpack-sources/lib/helpers/getFromStreamChunks.js new file mode 100644 index 0000000..f45c639 --- /dev/null +++ b/node_modules/webpack-sources/lib/helpers/getFromStreamChunks.js @@ -0,0 +1,129 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const createMappingsSerializer = require("./createMappingsSerializer"); + +exports.getSourceAndMap = (inputSource, options) => { + let code = ""; + let mappings = ""; + let sources = []; + let sourcesContent = []; + let names = []; + const addMapping = createMappingsSerializer(options); + const { source } = inputSource.streamChunks( + Object.assign({}, options, { finalSource: true }), + ( + chunk, + generatedLine, + generatedColumn, + sourceIndex, + originalLine, + originalColumn, + nameIndex + ) => { + if (chunk !== undefined) code += chunk; + mappings += addMapping( + generatedLine, + generatedColumn, + sourceIndex, + originalLine, + originalColumn, + nameIndex + ); + }, + (sourceIndex, source, sourceContent) => { + while (sources.length < sourceIndex) { + sources.push(null); + } + sources[sourceIndex] = source; + if (sourceContent !== undefined) { + while (sourcesContent.length < sourceIndex) { + sourcesContent.push(null); + } + sourcesContent[sourceIndex] = sourceContent; + } + }, + (nameIndex, name) => { + while (names.length < nameIndex) { + names.push(null); + } + names[nameIndex] = name; + } + ); + return { + source: source !== undefined ? source : code, + map: + mappings.length > 0 + ? { + version: 3, + file: "x", + mappings, + sources, + sourcesContent: + sourcesContent.length > 0 ? sourcesContent : undefined, + names + } + : null + }; +}; + +exports.getMap = (source, options) => { + let mappings = ""; + let sources = []; + let sourcesContent = []; + let names = []; + const addMapping = createMappingsSerializer(options); + source.streamChunks( + Object.assign({}, options, { source: false, finalSource: true }), + ( + chunk, + generatedLine, + generatedColumn, + sourceIndex, + originalLine, + originalColumn, + nameIndex + ) => { + mappings += addMapping( + generatedLine, + generatedColumn, + sourceIndex, + originalLine, + originalColumn, + nameIndex + ); + }, + (sourceIndex, source, sourceContent) => { + while (sources.length < sourceIndex) { + sources.push(null); + } + sources[sourceIndex] = source; + if (sourceContent !== undefined) { + while (sourcesContent.length < sourceIndex) { + sourcesContent.push(null); + } + sourcesContent[sourceIndex] = sourceContent; + } + }, + (nameIndex, name) => { + while (names.length < nameIndex) { + names.push(null); + } + names[nameIndex] = name; + } + ); + return mappings.length > 0 + ? { + version: 3, + file: "x", + mappings, + sources, + sourcesContent: sourcesContent.length > 0 ? sourcesContent : undefined, + names + } + : null; +}; diff --git a/node_modules/webpack-sources/lib/helpers/getGeneratedSourceInfo.js b/node_modules/webpack-sources/lib/helpers/getGeneratedSourceInfo.js new file mode 100644 index 0000000..2cc12fc --- /dev/null +++ b/node_modules/webpack-sources/lib/helpers/getGeneratedSourceInfo.js @@ -0,0 +1,33 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const CHAR_CODE_NEW_LINE = "\n".charCodeAt(0); + +const getGeneratedSourceInfo = source => { + if (source === undefined) { + return {}; + } + const lastLineStart = source.lastIndexOf("\n"); + if (lastLineStart === -1) { + return { + generatedLine: 1, + generatedColumn: source.length, + source + }; + } + let generatedLine = 2; + for (let i = 0; i < lastLineStart; i++) { + if (source.charCodeAt(i) === CHAR_CODE_NEW_LINE) generatedLine++; + } + return { + generatedLine, + generatedColumn: source.length - lastLineStart - 1, + source + }; +}; + +module.exports = getGeneratedSourceInfo; diff --git a/node_modules/webpack-sources/lib/helpers/getName.js b/node_modules/webpack-sources/lib/helpers/getName.js new file mode 100644 index 0000000..db6a863 --- /dev/null +++ b/node_modules/webpack-sources/lib/helpers/getName.js @@ -0,0 +1,14 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const getName = (sourceMap, index) => { + if (index < 0) return null; + const { names } = sourceMap; + return names[index]; +}; + +module.exports = getName; diff --git a/node_modules/webpack-sources/lib/helpers/getSource.js b/node_modules/webpack-sources/lib/helpers/getSource.js new file mode 100644 index 0000000..b236563 --- /dev/null +++ b/node_modules/webpack-sources/lib/helpers/getSource.js @@ -0,0 +1,17 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const getSource = (sourceMap, index) => { + if (index < 0) return null; + const { sourceRoot, sources } = sourceMap; + const source = sources[index]; + if (!sourceRoot) return source; + if (sourceRoot.endsWith("/")) return sourceRoot + source; + return sourceRoot + "/" + source; +}; + +module.exports = getSource; diff --git a/node_modules/webpack-sources/lib/helpers/readMappings.js b/node_modules/webpack-sources/lib/helpers/readMappings.js new file mode 100644 index 0000000..31cb48d --- /dev/null +++ b/node_modules/webpack-sources/lib/helpers/readMappings.js @@ -0,0 +1,116 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ALPHABET = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +const CONTINUATION_BIT = 0x20; +const END_SEGMENT_BIT = 0x40; +const NEXT_LINE = END_SEGMENT_BIT | 0x01; +const INVALID = END_SEGMENT_BIT | 0x02; +const DATA_MASK = 0x1f; + +const ccToValue = new Uint8Array("z".charCodeAt(0) + 1); +{ + ccToValue.fill(INVALID); + for (let i = 0; i < ALPHABET.length; i++) { + ccToValue[ALPHABET.charCodeAt(i)] = i; + } + ccToValue[",".charCodeAt(0)] = END_SEGMENT_BIT; + ccToValue[";".charCodeAt(0)] = NEXT_LINE; +} +const ccMax = ccToValue.length - 1; + +/** + * @param {string} mappings the mappings string + * @param {function(number, number, number, number, number, number): void} onMapping called for each mapping + * @returns {void} + */ +const readMappings = (mappings, onMapping) => { + // generatedColumn, [sourceIndex, originalLine, orignalColumn, [nameIndex]] + const currentData = new Uint32Array([0, 0, 1, 0, 0]); + let currentDataPos = 0; + // currentValue will include a sign bit at bit 0 + let currentValue = 0; + let currentValuePos = 0; + let generatedLine = 1; + let generatedColumn = -1; + for (let i = 0; i < mappings.length; i++) { + const cc = mappings.charCodeAt(i); + if (cc > ccMax) continue; + const value = ccToValue[cc]; + if ((value & END_SEGMENT_BIT) !== 0) { + // End current segment + if (currentData[0] > generatedColumn) { + if (currentDataPos === 1) { + onMapping(generatedLine, currentData[0], -1, -1, -1, -1); + } else if (currentDataPos === 4) { + onMapping( + generatedLine, + currentData[0], + currentData[1], + currentData[2], + currentData[3], + -1 + ); + } else if (currentDataPos === 5) { + onMapping( + generatedLine, + currentData[0], + currentData[1], + currentData[2], + currentData[3], + currentData[4] + ); + } + generatedColumn = currentData[0]; + } + currentDataPos = 0; + if (value === NEXT_LINE) { + // Start new line + generatedLine++; + currentData[0] = 0; + generatedColumn = -1; + } + } else if ((value & CONTINUATION_BIT) === 0) { + // last sextet + currentValue |= value << currentValuePos; + const finalValue = + currentValue & 1 ? -(currentValue >> 1) : currentValue >> 1; + currentData[currentDataPos++] += finalValue; + currentValuePos = 0; + currentValue = 0; + } else { + currentValue |= (value & DATA_MASK) << currentValuePos; + currentValuePos += 5; + } + } + // End current segment + if (currentDataPos === 1) { + onMapping(generatedLine, currentData[0], -1, -1, -1, -1); + } else if (currentDataPos === 4) { + onMapping( + generatedLine, + currentData[0], + currentData[1], + currentData[2], + currentData[3], + -1 + ); + } else if (currentDataPos === 5) { + onMapping( + generatedLine, + currentData[0], + currentData[1], + currentData[2], + currentData[3], + currentData[4] + ); + } +}; + +module.exports = readMappings; diff --git a/node_modules/webpack-sources/lib/helpers/splitIntoLines.js b/node_modules/webpack-sources/lib/helpers/splitIntoLines.js new file mode 100644 index 0000000..e9ccafd --- /dev/null +++ b/node_modules/webpack-sources/lib/helpers/splitIntoLines.js @@ -0,0 +1,21 @@ +const splitIntoLines = str => { + const results = []; + const len = str.length; + let i = 0; + for (; i < len; ) { + const cc = str.charCodeAt(i); + // 10 is "\n".charCodeAt(0) + if (cc === 10) { + results.push("\n"); + i++; + } else { + let j = i + 1; + // 10 is "\n".charCodeAt(0) + while (j < len && str.charCodeAt(j) !== 10) j++; + results.push(str.slice(i, j + 1)); + i = j + 1; + } + } + return results; +}; +module.exports = splitIntoLines; diff --git a/node_modules/webpack-sources/lib/helpers/splitIntoPotentialTokens.js b/node_modules/webpack-sources/lib/helpers/splitIntoPotentialTokens.js new file mode 100644 index 0000000..0f0bc42 --- /dev/null +++ b/node_modules/webpack-sources/lib/helpers/splitIntoPotentialTokens.js @@ -0,0 +1,41 @@ +// \n = 10 +// ; = 59 +// { = 123 +// } = 125 +// = 32 +// \r = 13 +// \t = 9 + +const splitIntoPotentialTokens = str => { + const len = str.length; + if (len === 0) return null; + const results = []; + let i = 0; + for (; i < len; ) { + const s = i; + block: { + let cc = str.charCodeAt(i); + while (cc !== 10 && cc !== 59 && cc !== 123 && cc !== 125) { + if (++i >= len) break block; + cc = str.charCodeAt(i); + } + while ( + cc === 59 || + cc === 32 || + cc === 123 || + cc === 125 || + cc === 13 || + cc === 9 + ) { + if (++i >= len) break block; + cc = str.charCodeAt(i); + } + if (cc === 10) { + i++; + } + } + results.push(str.slice(s, i)); + } + return results; +}; +module.exports = splitIntoPotentialTokens; diff --git a/node_modules/webpack-sources/lib/helpers/streamAndGetSourceAndMap.js b/node_modules/webpack-sources/lib/helpers/streamAndGetSourceAndMap.js new file mode 100644 index 0000000..529fd76 --- /dev/null +++ b/node_modules/webpack-sources/lib/helpers/streamAndGetSourceAndMap.js @@ -0,0 +1,102 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const createMappingsSerializer = require("./createMappingsSerializer"); +const streamChunks = require("./streamChunks"); + +const streamAndGetSourceAndMap = ( + inputSource, + options, + onChunk, + onSource, + onName +) => { + let code = ""; + let mappings = ""; + let sources = []; + let sourcesContent = []; + let names = []; + const addMapping = createMappingsSerializer( + Object.assign({}, options, { columns: true }) + ); + const finalSource = !!(options && options.finalSource); + const { generatedLine, generatedColumn, source } = streamChunks( + inputSource, + options, + ( + chunk, + generatedLine, + generatedColumn, + sourceIndex, + originalLine, + originalColumn, + nameIndex + ) => { + if (chunk !== undefined) code += chunk; + mappings += addMapping( + generatedLine, + generatedColumn, + sourceIndex, + originalLine, + originalColumn, + nameIndex + ); + return onChunk( + finalSource ? undefined : chunk, + generatedLine, + generatedColumn, + sourceIndex, + originalLine, + originalColumn, + nameIndex + ); + }, + (sourceIndex, source, sourceContent) => { + while (sources.length < sourceIndex) { + sources.push(null); + } + sources[sourceIndex] = source; + if (sourceContent !== undefined) { + while (sourcesContent.length < sourceIndex) { + sourcesContent.push(null); + } + sourcesContent[sourceIndex] = sourceContent; + } + return onSource(sourceIndex, source, sourceContent); + }, + (nameIndex, name) => { + while (names.length < nameIndex) { + names.push(null); + } + names[nameIndex] = name; + return onName(nameIndex, name); + } + ); + const resultSource = source !== undefined ? source : code; + return { + result: { + generatedLine, + generatedColumn, + source: finalSource ? resultSource : undefined + }, + source: resultSource, + map: + mappings.length > 0 + ? { + version: 3, + file: "x", + mappings, + sources, + sourcesContent: + sourcesContent.length > 0 ? sourcesContent : undefined, + names + } + : null + }; +}; + +module.exports = streamAndGetSourceAndMap; diff --git a/node_modules/webpack-sources/lib/helpers/streamChunks.js b/node_modules/webpack-sources/lib/helpers/streamChunks.js new file mode 100644 index 0000000..4bd3824 --- /dev/null +++ b/node_modules/webpack-sources/lib/helpers/streamChunks.js @@ -0,0 +1,36 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const streamChunksOfRawSource = require("./streamChunksOfRawSource"); +const streamChunksOfSourceMap = require("./streamChunksOfSourceMap"); + +module.exports = (source, options, onChunk, onSource, onName) => { + if (typeof source.streamChunks === "function") { + return source.streamChunks(options, onChunk, onSource, onName); + } else { + const sourceAndMap = source.sourceAndMap(options); + if (sourceAndMap.map) { + return streamChunksOfSourceMap( + sourceAndMap.source, + sourceAndMap.map, + onChunk, + onSource, + onName, + !!(options && options.finalSource), + !!(options && options.columns !== false) + ); + } else { + return streamChunksOfRawSource( + sourceAndMap.source, + onChunk, + onSource, + onName, + !!(options && options.finalSource) + ); + } + } +}; diff --git a/node_modules/webpack-sources/lib/helpers/streamChunksOfCombinedSourceMap.js b/node_modules/webpack-sources/lib/helpers/streamChunksOfCombinedSourceMap.js new file mode 100644 index 0000000..b40774d --- /dev/null +++ b/node_modules/webpack-sources/lib/helpers/streamChunksOfCombinedSourceMap.js @@ -0,0 +1,329 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const streamChunksOfSourceMap = require("./streamChunksOfSourceMap"); +const splitIntoLines = require("./splitIntoLines"); + +const streamChunksOfCombinedSourceMap = ( + source, + sourceMap, + innerSourceName, + innerSource, + innerSourceMap, + removeInnerSource, + onChunk, + onSource, + onName, + finalSource, + columns +) => { + let sourceMapping = new Map(); + let nameMapping = new Map(); + const sourceIndexMapping = []; + const nameIndexMapping = []; + const nameIndexValueMapping = []; + let innerSourceIndex = -2; + const innerSourceIndexMapping = []; + const innerSourceIndexValueMapping = []; + const innerSourceContents = []; + const innerSourceContentLines = []; + const innerNameIndexMapping = []; + const innerNameIndexValueMapping = []; + const innerSourceMapLineData = []; + const findInnerMapping = (line, column) => { + if (line > innerSourceMapLineData.length) return -1; + const { mappingsData } = innerSourceMapLineData[line - 1]; + let l = 0; + let r = mappingsData.length / 5; + while (l < r) { + let m = (l + r) >> 1; + if (mappingsData[m * 5] <= column) { + l = m + 1; + } else { + r = m; + } + } + if (l === 0) return -1; + return l - 1; + }; + return streamChunksOfSourceMap( + source, + sourceMap, + ( + chunk, + generatedLine, + generatedColumn, + sourceIndex, + originalLine, + originalColumn, + nameIndex + ) => { + // Check if this is a mapping to the inner source + if (sourceIndex === innerSourceIndex) { + // Check if there is a mapping in the inner source + const idx = findInnerMapping(originalLine, originalColumn); + if (idx !== -1) { + const { chunks, mappingsData } = innerSourceMapLineData[ + originalLine - 1 + ]; + const mi = idx * 5; + const innerSourceIndex = mappingsData[mi + 1]; + const innerOriginalLine = mappingsData[mi + 2]; + let innerOriginalColumn = mappingsData[mi + 3]; + let innerNameIndex = mappingsData[mi + 4]; + if (innerSourceIndex >= 0) { + // Check for an identity mapping + // where we are allowed to adjust the original column + const innerChunk = chunks[idx]; + const innerGeneratedColumn = mappingsData[mi]; + const locationInChunk = originalColumn - innerGeneratedColumn; + if (locationInChunk > 0) { + let originalSourceLines = + innerSourceIndex < innerSourceContentLines.length + ? innerSourceContentLines[innerSourceIndex] + : null; + if (originalSourceLines === undefined) { + const originalSource = innerSourceContents[innerSourceIndex]; + originalSourceLines = originalSource + ? splitIntoLines(originalSource) + : null; + innerSourceContentLines[innerSourceIndex] = originalSourceLines; + } + if (originalSourceLines !== null) { + const originalChunk = + innerOriginalLine <= originalSourceLines.length + ? originalSourceLines[innerOriginalLine - 1].slice( + innerOriginalColumn, + innerOriginalColumn + locationInChunk + ) + : ""; + if (innerChunk.slice(0, locationInChunk) === originalChunk) { + innerOriginalColumn += locationInChunk; + innerNameIndex = -1; + } + } + } + + // We have a inner mapping to original source + + // emit source when needed and compute global source index + let sourceIndex = + innerSourceIndex < innerSourceIndexMapping.length + ? innerSourceIndexMapping[innerSourceIndex] + : -2; + if (sourceIndex === -2) { + const [source, sourceContent] = + innerSourceIndex < innerSourceIndexValueMapping.length + ? innerSourceIndexValueMapping[innerSourceIndex] + : [null, undefined]; + let globalIndex = sourceMapping.get(source); + if (globalIndex === undefined) { + sourceMapping.set(source, (globalIndex = sourceMapping.size)); + onSource(globalIndex, source, sourceContent); + } + sourceIndex = globalIndex; + innerSourceIndexMapping[innerSourceIndex] = sourceIndex; + } + + // emit name when needed and compute global name index + let finalNameIndex = -1; + if (innerNameIndex >= 0) { + // when we have a inner name + finalNameIndex = + innerNameIndex < innerNameIndexMapping.length + ? innerNameIndexMapping[innerNameIndex] + : -2; + if (finalNameIndex === -2) { + const name = + innerNameIndex < innerNameIndexValueMapping.length + ? innerNameIndexValueMapping[innerNameIndex] + : undefined; + if (name) { + let globalIndex = nameMapping.get(name); + if (globalIndex === undefined) { + nameMapping.set(name, (globalIndex = nameMapping.size)); + onName(globalIndex, name); + } + finalNameIndex = globalIndex; + } else { + finalNameIndex = -1; + } + innerNameIndexMapping[innerNameIndex] = finalNameIndex; + } + } else if (nameIndex >= 0) { + // when we don't have an inner name, + // but we have an outer name + // it can be used when inner original code equals to the name + let originalSourceLines = + innerSourceContentLines[innerSourceIndex]; + if (originalSourceLines === undefined) { + const originalSource = innerSourceContents[innerSourceIndex]; + originalSourceLines = originalSource + ? splitIntoLines(originalSource) + : null; + innerSourceContentLines[innerSourceIndex] = originalSourceLines; + } + if (originalSourceLines !== null) { + const name = nameIndexValueMapping[nameIndex]; + const originalName = + innerOriginalLine <= originalSourceLines.length + ? originalSourceLines[innerOriginalLine - 1].slice( + innerOriginalColumn, + innerOriginalColumn + name.length + ) + : ""; + if (name === originalName) { + finalNameIndex = + nameIndex < nameIndexMapping.length + ? nameIndexMapping[nameIndex] + : -2; + if (finalNameIndex === -2) { + const name = nameIndexValueMapping[nameIndex]; + if (name) { + let globalIndex = nameMapping.get(name); + if (globalIndex === undefined) { + nameMapping.set(name, (globalIndex = nameMapping.size)); + onName(globalIndex, name); + } + finalNameIndex = globalIndex; + } else { + finalNameIndex = -1; + } + nameIndexMapping[nameIndex] = finalNameIndex; + } + } + } + } + onChunk( + chunk, + generatedLine, + generatedColumn, + sourceIndex, + innerOriginalLine, + innerOriginalColumn, + finalNameIndex + ); + return; + } + } + + // We have a mapping to the inner source, but no inner mapping + if (removeInnerSource) { + onChunk(chunk, generatedLine, generatedColumn, -1, -1, -1, -1); + return; + } else { + if (sourceIndexMapping[sourceIndex] === -2) { + let globalIndex = sourceMapping.get(innerSourceName); + if (globalIndex === undefined) { + sourceMapping.set(source, (globalIndex = sourceMapping.size)); + onSource(globalIndex, innerSourceName, innerSource); + } + sourceIndexMapping[sourceIndex] = globalIndex; + } + } + } + + const finalSourceIndex = + sourceIndex < 0 || sourceIndex >= sourceIndexMapping.length + ? -1 + : sourceIndexMapping[sourceIndex]; + if (finalSourceIndex < 0) { + // no source, so we make it a generated chunk + onChunk(chunk, generatedLine, generatedColumn, -1, -1, -1, -1); + } else { + // Pass through the chunk with mapping + let finalNameIndex = -1; + if (nameIndex >= 0 && nameIndex < nameIndexMapping.length) { + finalNameIndex = nameIndexMapping[nameIndex]; + if (finalNameIndex === -2) { + const name = nameIndexValueMapping[nameIndex]; + let globalIndex = nameMapping.get(name); + if (globalIndex === undefined) { + nameMapping.set(name, (globalIndex = nameMapping.size)); + onName(globalIndex, name); + } + finalNameIndex = globalIndex; + nameIndexMapping[nameIndex] = finalNameIndex; + } + } + onChunk( + chunk, + generatedLine, + generatedColumn, + finalSourceIndex, + originalLine, + originalColumn, + finalNameIndex + ); + } + }, + (i, source, sourceContent) => { + if (source === innerSourceName) { + innerSourceIndex = i; + if (innerSource !== undefined) sourceContent = innerSource; + else innerSource = sourceContent; + sourceIndexMapping[i] = -2; + streamChunksOfSourceMap( + sourceContent, + innerSourceMap, + ( + chunk, + generatedLine, + generatedColumn, + sourceIndex, + originalLine, + originalColumn, + nameIndex + ) => { + while (innerSourceMapLineData.length < generatedLine) { + innerSourceMapLineData.push({ + mappingsData: [], + chunks: [] + }); + } + const data = innerSourceMapLineData[generatedLine - 1]; + data.mappingsData.push( + generatedColumn, + sourceIndex, + originalLine, + originalColumn, + nameIndex + ); + data.chunks.push(chunk); + }, + (i, source, sourceContent) => { + innerSourceContents[i] = sourceContent; + innerSourceContentLines[i] = undefined; + innerSourceIndexMapping[i] = -2; + innerSourceIndexValueMapping[i] = [source, sourceContent]; + }, + (i, name) => { + innerNameIndexMapping[i] = -2; + innerNameIndexValueMapping[i] = name; + }, + false, + columns + ); + } else { + let globalIndex = sourceMapping.get(source); + if (globalIndex === undefined) { + sourceMapping.set(source, (globalIndex = sourceMapping.size)); + onSource(globalIndex, source, sourceContent); + } + sourceIndexMapping[i] = globalIndex; + } + }, + (i, name) => { + nameIndexMapping[i] = -2; + nameIndexValueMapping[i] = name; + }, + finalSource, + columns + ); +}; + +module.exports = streamChunksOfCombinedSourceMap; diff --git a/node_modules/webpack-sources/lib/helpers/streamChunksOfRawSource.js b/node_modules/webpack-sources/lib/helpers/streamChunksOfRawSource.js new file mode 100644 index 0000000..133022a --- /dev/null +++ b/node_modules/webpack-sources/lib/helpers/streamChunksOfRawSource.js @@ -0,0 +1,34 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const getGeneratedSourceInfo = require("./getGeneratedSourceInfo"); +const splitIntoLines = require("./splitIntoLines"); + +const streamChunksOfRawSource = (source, onChunk, onSource, onName) => { + let line = 1; + const matches = splitIntoLines(source); + let match; + for (match of matches) { + onChunk(match, line, 0, -1, -1, -1, -1); + line++; + } + return matches.length === 0 || match.endsWith("\n") + ? { + generatedLine: matches.length + 1, + generatedColumn: 0 + } + : { + generatedLine: matches.length, + generatedColumn: match.length + }; +}; + +module.exports = (source, onChunk, onSource, onName, finalSource) => { + return finalSource + ? getGeneratedSourceInfo(source) + : streamChunksOfRawSource(source, onChunk, onSource, onName); +}; diff --git a/node_modules/webpack-sources/lib/helpers/streamChunksOfSourceMap.js b/node_modules/webpack-sources/lib/helpers/streamChunksOfSourceMap.js new file mode 100644 index 0000000..c57cb34 --- /dev/null +++ b/node_modules/webpack-sources/lib/helpers/streamChunksOfSourceMap.js @@ -0,0 +1,412 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const getGeneratedSourceInfo = require("./getGeneratedSourceInfo"); +const getSource = require("./getSource"); +const readMappings = require("./readMappings"); +const splitIntoLines = require("./splitIntoLines"); + +const streamChunksOfSourceMapFull = ( + source, + sourceMap, + onChunk, + onSource, + onName +) => { + const lines = splitIntoLines(source); + if (lines.length === 0) { + return { + generatedLine: 1, + generatedColumn: 0 + }; + } + const { sources, sourcesContent, names, mappings } = sourceMap; + for (let i = 0; i < sources.length; i++) { + onSource( + i, + getSource(sourceMap, i), + (sourcesContent && sourcesContent[i]) || undefined + ); + } + if (names) { + for (let i = 0; i < names.length; i++) { + onName(i, names[i]); + } + } + + const lastLine = lines[lines.length - 1]; + const lastNewLine = lastLine.endsWith("\n"); + const finalLine = lastNewLine ? lines.length + 1 : lines.length; + const finalColumn = lastNewLine ? 0 : lastLine.length; + + let currentGeneratedLine = 1; + let currentGeneratedColumn = 0; + + let mappingActive = false; + let activeMappingSourceIndex = -1; + let activeMappingOriginalLine = -1; + let activeMappingOriginalColumn = -1; + let activeMappingNameIndex = -1; + + const onMapping = ( + generatedLine, + generatedColumn, + sourceIndex, + originalLine, + originalColumn, + nameIndex + ) => { + if (mappingActive && currentGeneratedLine <= lines.length) { + let chunk; + const mappingLine = currentGeneratedLine; + const mappingColumn = currentGeneratedColumn; + const line = lines[currentGeneratedLine - 1]; + if (generatedLine !== currentGeneratedLine) { + chunk = line.slice(currentGeneratedColumn); + currentGeneratedLine++; + currentGeneratedColumn = 0; + } else { + chunk = line.slice(currentGeneratedColumn, generatedColumn); + currentGeneratedColumn = generatedColumn; + } + if (chunk) { + onChunk( + chunk, + mappingLine, + mappingColumn, + activeMappingSourceIndex, + activeMappingOriginalLine, + activeMappingOriginalColumn, + activeMappingNameIndex + ); + } + mappingActive = false; + } + if (generatedLine > currentGeneratedLine && currentGeneratedColumn > 0) { + if (currentGeneratedLine <= lines.length) { + const chunk = lines[currentGeneratedLine - 1].slice( + currentGeneratedColumn + ); + onChunk( + chunk, + currentGeneratedLine, + currentGeneratedColumn, + -1, + -1, + -1, + -1 + ); + } + currentGeneratedLine++; + currentGeneratedColumn = 0; + } + while (generatedLine > currentGeneratedLine) { + if (currentGeneratedLine <= lines.length) { + onChunk( + lines[currentGeneratedLine - 1], + currentGeneratedLine, + 0, + -1, + -1, + -1, + -1 + ); + } + currentGeneratedLine++; + } + if (generatedColumn > currentGeneratedColumn) { + if (currentGeneratedLine <= lines.length) { + const chunk = lines[currentGeneratedLine - 1].slice( + currentGeneratedColumn, + generatedColumn + ); + onChunk( + chunk, + currentGeneratedLine, + currentGeneratedColumn, + -1, + -1, + -1, + -1 + ); + } + currentGeneratedColumn = generatedColumn; + } + if ( + sourceIndex >= 0 && + (generatedLine < finalLine || + (generatedLine === finalLine && generatedColumn < finalColumn)) + ) { + mappingActive = true; + activeMappingSourceIndex = sourceIndex; + activeMappingOriginalLine = originalLine; + activeMappingOriginalColumn = originalColumn; + activeMappingNameIndex = nameIndex; + } + }; + readMappings(mappings, onMapping); + onMapping(finalLine, finalColumn, -1, -1, -1, -1); + return { + generatedLine: finalLine, + generatedColumn: finalColumn + }; +}; + +const streamChunksOfSourceMapLinesFull = ( + source, + sourceMap, + onChunk, + onSource, + _onName +) => { + const lines = splitIntoLines(source); + if (lines.length === 0) { + return { + generatedLine: 1, + generatedColumn: 0 + }; + } + const { sources, sourcesContent, mappings } = sourceMap; + for (let i = 0; i < sources.length; i++) { + onSource( + i, + getSource(sourceMap, i), + (sourcesContent && sourcesContent[i]) || undefined + ); + } + + let currentGeneratedLine = 1; + + const onMapping = ( + generatedLine, + _generatedColumn, + sourceIndex, + originalLine, + originalColumn, + _nameIndex + ) => { + if ( + sourceIndex < 0 || + generatedLine < currentGeneratedLine || + generatedLine > lines.length + ) { + return; + } + while (generatedLine > currentGeneratedLine) { + if (currentGeneratedLine <= lines.length) { + onChunk( + lines[currentGeneratedLine - 1], + currentGeneratedLine, + 0, + -1, + -1, + -1, + -1 + ); + } + currentGeneratedLine++; + } + if (generatedLine <= lines.length) { + onChunk( + lines[generatedLine - 1], + generatedLine, + 0, + sourceIndex, + originalLine, + originalColumn, + -1 + ); + currentGeneratedLine++; + } + }; + readMappings(mappings, onMapping); + for (; currentGeneratedLine <= lines.length; currentGeneratedLine++) { + onChunk( + lines[currentGeneratedLine - 1], + currentGeneratedLine, + 0, + -1, + -1, + -1, + -1 + ); + } + + const lastLine = lines[lines.length - 1]; + const lastNewLine = lastLine.endsWith("\n"); + + const finalLine = lastNewLine ? lines.length + 1 : lines.length; + const finalColumn = lastNewLine ? 0 : lastLine.length; + + return { + generatedLine: finalLine, + generatedColumn: finalColumn + }; +}; + +const streamChunksOfSourceMapFinal = ( + source, + sourceMap, + onChunk, + onSource, + onName +) => { + const result = getGeneratedSourceInfo(source); + const { generatedLine: finalLine, generatedColumn: finalColumn } = result; + + if (finalLine === 1 && finalColumn === 0) return result; + const { sources, sourcesContent, names, mappings } = sourceMap; + for (let i = 0; i < sources.length; i++) { + onSource( + i, + getSource(sourceMap, i), + (sourcesContent && sourcesContent[i]) || undefined + ); + } + if (names) { + for (let i = 0; i < names.length; i++) { + onName(i, names[i]); + } + } + + let mappingActiveLine = 0; + + const onMapping = ( + generatedLine, + generatedColumn, + sourceIndex, + originalLine, + originalColumn, + nameIndex + ) => { + if ( + generatedLine >= finalLine && + (generatedColumn >= finalColumn || generatedLine > finalLine) + ) { + return; + } + if (sourceIndex >= 0) { + onChunk( + undefined, + generatedLine, + generatedColumn, + sourceIndex, + originalLine, + originalColumn, + nameIndex + ); + mappingActiveLine = generatedLine; + } else if (mappingActiveLine === generatedLine) { + onChunk(undefined, generatedLine, generatedColumn, -1, -1, -1, -1); + mappingActiveLine = 0; + } + }; + readMappings(mappings, onMapping); + return result; +}; + +const streamChunksOfSourceMapLinesFinal = ( + source, + sourceMap, + onChunk, + onSource, + _onName +) => { + const result = getGeneratedSourceInfo(source); + const { generatedLine, generatedColumn } = result; + if (generatedLine === 1 && generatedColumn === 0) { + return { + generatedLine: 1, + generatedColumn: 0 + }; + } + + const { sources, sourcesContent, mappings } = sourceMap; + for (let i = 0; i < sources.length; i++) { + onSource( + i, + getSource(sourceMap, i), + (sourcesContent && sourcesContent[i]) || undefined + ); + } + + const finalLine = generatedColumn === 0 ? generatedLine - 1 : generatedLine; + + let currentGeneratedLine = 1; + + const onMapping = ( + generatedLine, + _generatedColumn, + sourceIndex, + originalLine, + originalColumn, + _nameIndex + ) => { + if ( + sourceIndex >= 0 && + currentGeneratedLine <= generatedLine && + generatedLine <= finalLine + ) { + onChunk( + undefined, + generatedLine, + 0, + sourceIndex, + originalLine, + originalColumn, + -1 + ); + currentGeneratedLine = generatedLine + 1; + } + }; + readMappings(mappings, onMapping); + return result; +}; + +module.exports = ( + source, + sourceMap, + onChunk, + onSource, + onName, + finalSource, + columns +) => { + if (columns) { + return finalSource + ? streamChunksOfSourceMapFinal( + source, + sourceMap, + onChunk, + onSource, + onName + ) + : streamChunksOfSourceMapFull( + source, + sourceMap, + onChunk, + onSource, + onName + ); + } else { + return finalSource + ? streamChunksOfSourceMapLinesFinal( + source, + sourceMap, + onChunk, + onSource, + onName + ) + : streamChunksOfSourceMapLinesFull( + source, + sourceMap, + onChunk, + onSource, + onName + ); + } +}; diff --git a/node_modules/webpack-sources/lib/index.js b/node_modules/webpack-sources/lib/index.js new file mode 100644 index 0000000..0c11c2f --- /dev/null +++ b/node_modules/webpack-sources/lib/index.js @@ -0,0 +1,30 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const defineExport = (name, fn) => { + let value; + Object.defineProperty(exports, name, { + get: () => { + if (fn !== undefined) { + value = fn(); + fn = undefined; + } + return value; + }, + configurable: true + }); +}; + +defineExport("Source", () => require("./Source")); + +defineExport("RawSource", () => require("./RawSource")); +defineExport("OriginalSource", () => require("./OriginalSource")); +defineExport("SourceMapSource", () => require("./SourceMapSource")); +defineExport("CachedSource", () => require("./CachedSource")); +defineExport("ConcatSource", () => require("./ConcatSource")); +defineExport("ReplaceSource", () => require("./ReplaceSource")); +defineExport("PrefixSource", () => require("./PrefixSource")); +defineExport("SizeOnlySource", () => require("./SizeOnlySource")); +defineExport("CompatSource", () => require("./CompatSource")); diff --git a/node_modules/webpack-sources/package.json b/node_modules/webpack-sources/package.json new file mode 100644 index 0000000..33ae44c --- /dev/null +++ b/node_modules/webpack-sources/package.json @@ -0,0 +1,58 @@ +{ + "name": "webpack-sources", + "version": "3.2.3", + "description": "Source code handling classes for webpack", + "main": "./lib/index.js", + "scripts": { + "pretest": "yarn lint", + "test": "jest", + "lint": "eslint --cache lib test/*.js", + "cover": "jest --coverage" + }, + "devDependencies": { + "coveralls": "^3.0.2", + "eslint": "^7.7.0", + "eslint-config-prettier": "^6.11.0", + "eslint-plugin-jest": "^23.20.0", + "eslint-plugin-mocha": "^8.0.0", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-nodeca": "^1.0.3", + "eslint-plugin-prettier": "^3.0.1", + "istanbul": "^0.4.1", + "jest": "^26.4.0", + "prettier": "^2.0.5", + "source-map": "^0.7.3", + "sourcemap-validator": "^2.1.0" + }, + "files": [ + "lib/", + "!lib/helpers/__mocks__" + ], + "engines": { + "node": ">=10.13.0" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/webpack/webpack-sources.git" + }, + "keywords": [ + "webpack", + "source-map" + ], + "author": "Tobias Koppers @sokra", + "license": "MIT", + "bugs": { + "url": "https://github.com/webpack/webpack-sources/issues" + }, + "homepage": "https://github.com/webpack/webpack-sources#readme", + "jest": { + "forceExit": true, + "testMatch": [ + "/test/*.js" + ], + "transformIgnorePatterns": [ + "" + ], + "testEnvironment": "node" + } +} diff --git a/node_modules/webpack/LICENSE b/node_modules/webpack/LICENSE new file mode 100644 index 0000000..8c11fc7 --- /dev/null +++ b/node_modules/webpack/LICENSE @@ -0,0 +1,20 @@ +Copyright JS Foundation and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/webpack/README.md b/node_modules/webpack/README.md new file mode 100644 index 0000000..e26e3b2 --- /dev/null +++ b/node_modules/webpack/README.md @@ -0,0 +1,727 @@ +
+ + + +
+
+ +[![npm][npm]][npm-url] + +[![node][node]][node-url] +[![builds1][builds1]][builds1-url] +[![builds2][builds2]][builds2-url] +[![dependency-review][dependency-review]][dependency-review-url] +[![coverage][cover]][cover-url] +[![PR's welcome][prs]][prs-url] + +
+ + + + + + + + install size + + + + + + + + + + + + + + + + + + + +

webpack

+

+ Webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset. +

+
+ +## Table of Contents + +1. [Install](#install) +2. [Introduction](#introduction) +3. [Concepts](#concepts) +4. [Contributing](#contributing) +5. [Support](#support) +6. [Core Team](#core-team) +7. [Sponsoring](#sponsoring) +8. [Premium Partners](#premium-partners) +9. [Other Backers and Sponsors](#other-backers-and-sponsors) +10. [Gold Sponsors](#gold-sponsors) +11. [Silver Sponsors](#silver-sponsors) +12. [Bronze Sponsors](#bronze-sponsors) +13. [Backers](#backers) +14. [Special Thanks](#special-thanks-to) + +

Install

+ +Install with npm: + +```bash +npm install --save-dev webpack +``` + +Install with yarn: + +```bash +yarn add webpack --dev +``` + +

Introduction

+ +Webpack is a bundler for modules. The main purpose is to bundle JavaScript +files for usage in a browser, yet it is also capable of transforming, bundling, +or packaging just about any resource or asset. + +**TL;DR** + +- Bundles [ES Modules](https://www.2ality.com/2014/09/es6-modules-final.html), [CommonJS](http://wiki.commonjs.org/), and [AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) modules (even combined). +- Can create a single bundle or multiple chunks that are asynchronously loaded at runtime (to reduce initial loading time). +- Dependencies are resolved during compilation, reducing the runtime size. +- Loaders can preprocess files while compiling, e.g. TypeScript to JavaScript, Handlebars strings to compiled functions, images to Base64, etc. +- Highly modular plugin system to do whatever else your application requires. + +### Get Started + +Check out webpack's quick [**Get Started**](https://webpack.js.org/guides/getting-started) guide and the [other guides](https://webpack.js.org/guides/). + +### Browser Compatibility + +Webpack supports all browsers that are [ES5-compliant](https://kangax.github.io/compat-table/es5/) (IE8 and below are not supported). +Webpack also needs `Promise` for `import()` and `require.ensure()`. If you want to support older browsers, you will need to [load a polyfill](https://webpack.js.org/guides/shimming/) before using these expressions. + +

Concepts

+ +### [Plugins](https://webpack.js.org/plugins/) + +Webpack has a [rich plugin +interface](https://webpack.js.org/plugins/). Most of the features +within webpack itself use this plugin interface. This makes webpack very +**flexible**. + +| Name | Status | Install Size | Description | +| :---------------------------------------: | :----------------: | :-----------------: | :-------------------------------------------------------------------------------------- | +| [mini-css-extract-plugin][mini-css] | ![mini-css-npm] | ![mini-css-size] | Extracts CSS into separate files. It creates a CSS file per JS file which contains CSS. | +| [compression-webpack-plugin][compression] | ![compression-npm] | ![compression-size] | Prepares compressed versions of assets to serve them with Content-Encoding | +| [html-webpack-plugin][html-plugin] | ![html-plugin-npm] | ![html-plugin-size] | Simplifies creation of HTML files (`index.html`) to serve your bundles | +| [pug-plugin][pug-plugin] | ![pug-plugin-npm] | ![pug-plugin-size] | Renders Pug files to HTML, extracts JS and CSS from sources specified directly in Pug. | + +[common-npm]: https://img.shields.io/npm/v/webpack.svg +[mini-css]: https://github.com/webpack-contrib/mini-css-extract-plugin +[mini-css-npm]: https://img.shields.io/npm/v/mini-css-extract-plugin.svg +[mini-css-size]: https://packagephobia.com/badge?p=mini-css-extract-plugin +[component]: https://github.com/webpack-contrib/component-webpack-plugin +[component-npm]: https://img.shields.io/npm/v/component-webpack-plugin.svg +[component-size]: https://packagephobia.com/badge?p=component-webpack-plugin +[compression]: https://github.com/webpack-contrib/compression-webpack-plugin +[compression-npm]: https://img.shields.io/npm/v/compression-webpack-plugin.svg +[compression-size]: https://packagephobia.com/badge?p=compression-webpack-plugin +[html-plugin]: https://github.com/jantimon/html-webpack-plugin +[html-plugin-npm]: https://img.shields.io/npm/v/html-webpack-plugin.svg +[html-plugin-size]: https://packagephobia.com/badge?p=html-webpack-plugin +[pug-plugin]: https://github.com/webdiscus/pug-plugin +[pug-plugin-npm]: https://img.shields.io/npm/v/pug-plugin.svg +[pug-plugin-size]: https://packagephobia.com/badge?p=pug-plugin + +### [Loaders](https://webpack.js.org/loaders/) + +Webpack enables the use of loaders to preprocess files. This allows you to bundle +**any static resource** way beyond JavaScript. You can easily [write your own +loaders](https://webpack.js.org/api/loaders/) using Node.js. + +Loaders are activated by using `loadername!` prefixes in `require()` statements, +or are automatically applied via regex from your webpack configuration. + +#### Files + +| Name | Status | Install Size | Description | +| :---------------: | :--------: | :----------: | :------------------------------------------------------- | +| [val-loader][val] | ![val-npm] | ![val-size] | Executes code as module and considers exports as JS code | + +[val]: https://github.com/webpack-contrib/val-loader +[val-npm]: https://img.shields.io/npm/v/val-loader.svg +[val-size]: https://packagephobia.com/badge?p=val-loader + +#### JSON + +| Name | Status | Install Size | Description | +| :---------------------------------------------------------------------------------------------------------------------------------------: | :---------: | :----------: | :------------------------------: | +| | ![cson-npm] | ![cson-size] | Loads and transpiles a CSON file | + +[cson-npm]: https://img.shields.io/npm/v/cson-loader.svg +[cson-size]: https://packagephobia.com/badge?p=cson-loader + +#### Transpiling + +| Name | Status | Install Size | Description | +| :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-----------: | :------------: | :------------------------------------------------------------------------------------------------ | +| | ![babel-npm] | ![babel-size] | Loads ES2015+ code and transpiles to ES5 using Babel | +| | ![type-npm] | ![type-size] | Loads TypeScript like JavaScript | +| | ![coffee-npm] | ![coffee-size] | Loads CoffeeScript like JavaScript | + +[babel-npm]: https://img.shields.io/npm/v/babel-loader.svg +[babel-size]: https://packagephobia.com/badge?p=babel-loader +[coffee-npm]: https://img.shields.io/npm/v/coffee-loader.svg +[coffee-size]: https://packagephobia.com/badge?p=coffee-loader +[type-npm]: https://img.shields.io/npm/v/ts-loader.svg +[type-size]: https://packagephobia.com/badge?p=ts-loader + +#### Templating + +| Name | Status | Install Size | Description | +| :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-------------: | :--------------: | :-------------------------------------------------------------------------------------- | +| | ![html-npm] | ![html-size] | Exports HTML as string, requires references to static resources | +| | ![pug-npm] | ![pug-size] | Loads Pug templates and returns a function | +| | ![pug3-npm] | ![pug3-size] | Compiles Pug to a function or HTML string, useful for use with Vue, React, Angular | +| | ![md-npm] | ![md-size] | Compiles Markdown to HTML | +| | ![posthtml-npm] | ![posthtml-size] | Loads and transforms a HTML file using [PostHTML](https://github.com/posthtml/posthtml) | +| | ![hbs-npm] | ![hbs-size] | Compiles Handlebars to HTML | + +[html-npm]: https://img.shields.io/npm/v/html-loader.svg +[html-size]: https://packagephobia.com/badge?p=html-loader +[pug-npm]: https://img.shields.io/npm/v/pug-loader.svg +[pug-size]: https://packagephobia.com/badge?p=pug-loader +[pug3-npm]: https://img.shields.io/npm/v/@webdiscus/pug-loader.svg +[pug3-size]: https://packagephobia.com/badge?p=@webdiscus/pug-loader +[jade-npm]: https://img.shields.io/npm/v/jade-loader.svg +[jade-size]: https://packagephobia.com/badge?p=jade-loader +[md-npm]: https://img.shields.io/npm/v/markdown-loader.svg +[md-size]: https://packagephobia.com/badge?p=markdown-loader +[posthtml-npm]: https://img.shields.io/npm/v/posthtml-loader.svg +[posthtml-size]: https://packagephobia.com/badge?p=posthtml-loader +[hbs-npm]: https://img.shields.io/npm/v/handlebars-loader.svg +[hbs-size]: https://packagephobia.com/badge?p=handlebars-loader + +#### Styling + +| Name | Status | Install Size | Description | +| :-------------------------------------------------------------------------------------------------------------------------------------------: | :------------: | :-------------: | :----------------------------------------------------------------------- | +| `